• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef HARDWARE_GOOGLE_CAMERA_HAL_GOOGLE_CAMERA_HAL_CAMERA_DEVICE__SESSION_H_
18 #define HARDWARE_GOOGLE_CAMERA_HAL_GOOGLE_CAMERA_HAL_CAMERA_DEVICE__SESSION_H_
19 
20 #include <map>
21 #include <memory>
22 #include <set>
23 #include <shared_mutex>
24 #include <vector>
25 
26 #include "camera_buffer_allocator_hwl.h"
27 #include "camera_device_session_hwl.h"
28 #include "capture_session.h"
29 #include "capture_session_utils.h"
30 #include "hal_camera_metadata.h"
31 #include "hal_types.h"
32 #include "hwl_types.h"
33 #include "pending_requests_tracker.h"
34 #include "stream_buffer_cache_manager.h"
35 #include "thermal_types.h"
36 #include "zoom_ratio_mapper.h"
37 
38 namespace android {
39 namespace google_camera_hal {
40 
41 // Defines callbacks to be invoked by a CameraDeviceSession.
42 struct CameraDeviceSessionCallback {
43   // Callback to notify when a camera device produces a capture result.
44   ProcessCaptureResultFunc process_capture_result;
45 
46   // Callback to notify when a camera device produces a batched capture result.
47   ProcessBatchCaptureResultFunc process_batch_capture_result;
48 
49   // Callback to notify a shutter or error.
50   NotifyFunc notify;
51 
52   // Callback to notify a batched shutter or error.
53   NotifyBatchFunc notify_batch;
54 
55   // Callback to request stream buffers.
56   RequestStreamBuffersFunc request_stream_buffers;
57 
58   // Callback to return stream buffers.
59   ReturnStreamBuffersFunc return_stream_buffers;
60 };
61 
62 // Defines callbacks to get thermal information.
63 struct ThermalCallback {
64   // Register a thermal changed callback.
65   RegisterThermalChangedCallbackFunc register_thermal_changed_callback;
66 
67   // Unregister the thermal changed callback.
68   UnregisterThermalChangedCallbackFunc unregister_thermal_changed_callback;
69 };
70 
71 // Entry point for getting an external capture session.
72 using GetCaptureSessionFactoryFunc = ExternalCaptureSessionFactory* (*)();
73 
74 // CameraDeviceSession implements functions needed for the HIDL camera device
75 // session interface, ICameraDeviceSession. It contains the methods to configure
76 // and request captures from an active camera device.
77 class CameraDeviceSession {
78  public:
79   // Create a CameraDeviceSession.
80   // device_session_hwl is a CameraDeviceSessionHwl that will be managed by this
81   // class.
82   // If device_session_hwl is nullptr, this method will return nullptr.
83   // camera_allocator_hwl is owned by the caller and must be valid during the
84   // lifetime of CameraDeviceSession
85   static std::unique_ptr<CameraDeviceSession> Create(
86       std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
87       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries,
88       CameraBufferAllocatorHwl* camera_allocator_hwl = nullptr);
89 
90   virtual ~CameraDeviceSession();
91 
92   // Set session callbacks
93   // Must be called before ConfigureStreams().
94   // session_callback will be invoked for capture results and messages.
95   // thermal_callback will be invoked for getting thermal information.
96   void SetSessionCallback(const CameraDeviceSessionCallback& session_callback,
97                           const ThermalCallback& thermal_callback);
98 
99   // Construct the default request settings for a request template type.
100   status_t ConstructDefaultRequestSettings(
101       RequestTemplate type,
102       std::unique_ptr<HalCameraMetadata>* default_settings);
103 
104   // Configure streams.
105   // stream_config is the requested stream configuration.
106   // v2 is whether the ConfigureStreams call is made by the configureStreamsV2
107   //    AIDL call or not.
108   // hal_configured_streams is filled by this method with configured stream.
109   status_t ConfigureStreams(const StreamConfiguration& stream_config, bool v2,
110                             ConfigureStreamsReturn* configured_streams);
111 
112   // Process a capture request.
113   // num_processed_requests is filled by this method with the number of
114   // processed requests.
115   status_t ProcessCaptureRequest(const std::vector<CaptureRequest>& requests,
116                                  uint32_t* num_processed_requests);
117 
118   // Remove the buffer caches kept in the camera device session.
119   void RemoveBufferCache(const std::vector<BufferCache>& buffer_caches);
120 
121   // Flush all pending requests.
122   status_t Flush();
123 
124   void RepeatingRequestEnd(int32_t frame_number,
125                            const std::vector<int32_t>& stream_ids);
126 
127   // Check reconfiguration is required or not
128   // old_session is old session parameter
129   // new_session is new session parameter
130   // If reconfiguration is required, set reconfiguration_required to true
131   // If reconfiguration is not required, set reconfiguration_required to false
132   status_t IsReconfigurationRequired(const HalCameraMetadata* old_session,
133                                      const HalCameraMetadata* new_session,
134                                      bool* reconfiguration_required);
135 
136   std::unique_ptr<google::camera_common::Profiler> GetProfiler(uint32_t camere_id,
137                                                                int option);
138 
139  protected:
140   CameraDeviceSession() = default;
141 
142  private:
143   // Define buffer cache hashing in order to use BufferCache as a key of an
144   // unordered map.
145   struct BufferCacheHashing {
operatorBufferCacheHashing146     unsigned long operator()(const BufferCache& buffer_cache) const {
147       std::string s = "s" + std::to_string(buffer_cache.stream_id) + "b" +
148                       std::to_string(buffer_cache.buffer_id);
149       return std::hash<std::string>{}(s);
150     }
151   };
152 
153   status_t Initialize(
154       std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
155       CameraBufferAllocatorHwl* camera_allocator_hwl,
156       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries);
157 
158   // Initialize callbacks from HWL and callbacks to the client.
159   void InitializeCallbacks();
160 
161   // Initialize buffer management support.
162   status_t InitializeBufferManagement(HalCameraMetadata* characteristics);
163 
164   // Update all buffer handles in buffers with the imported buffer handles.
165   // Must be protected by imported_buffer_handle_map_lock_.
166   status_t UpdateBufferHandlesLocked(
167       std::vector<StreamBuffer>* buffers,
168       bool update_hal_buffer_managed_streams = false);
169 
170   // Import the buffer handles in the request.
171   status_t ImportRequestBufferHandles(const CaptureRequest& request);
172 
173   // Import the buffer handles of buffers.
174   status_t ImportBufferHandles(const std::vector<StreamBuffer>& buffers);
175 
176   // Import the buffer handle of a buffer.
177   // Must be protected by imported_buffer_handle_map_lock_.
178   status_t ImportBufferHandleLocked(const StreamBuffer& buffer);
179 
180   // Create a request with updated buffer handles and modified settings.
181   // Must be protected by session_lock_.
182   status_t CreateCaptureRequestLocked(const CaptureRequest& request,
183                                       CaptureRequest* updated_request);
184 
185   // Add a buffer handle to the imported buffer handle map. If the buffer cache
186   // is already in the map but the buffer handle doesn't match, it will
187   // return BAD_VALUE.
188   // Must be protected by imported_buffer_handle_map_lock_.
189   status_t AddImportedBufferHandlesLocked(const BufferCache& buffer_cache,
190                                           buffer_handle_t buffer_handle);
191 
192   // Return if the buffer handle for a certain buffer ID is imported.
193   // Must be protected by imported_buffer_handle_map_lock_.
194   bool IsBufferImportedLocked(int32_t stream_id, uint32_t buffer_id);
195 
196   // Free all imported buffer handles belonging to the stream id.
197   // Must be protected by imported_buffer_handle_map_lock_.
198   void FreeBufferHandlesLocked(int32_t stream_id);
199 
200   void FreeImportedBufferHandles();
201 
202   // Clean up stale streams with new stream configuration.
203   // Must be protected by session_lock_.
204   void CleanupStaleStreamsLocked(const std::vector<Stream>& new_streams);
205 
206   // Append output intent to request settings.
207   // Must be protected by session_lock_.
208   void AppendOutputIntentToSettingsLocked(const CaptureRequest& request,
209                                           CaptureRequest* updated_request);
210 
211   // Invoked by HWL to request stream buffers when buffer management is
212   // supported.
213   status_t RequestStreamBuffers(int32_t stream_id, uint32_t num_buffers,
214                                 std::vector<StreamBuffer>* buffers,
215                                 StreamBufferRequestError* request_status);
216 
217   // Invoked by HWL to return stream buffers when buffer management is
218   // supported.
219   void ReturnStreamBuffers(const std::vector<StreamBuffer>& buffers);
220 
221   // Update imported buffer handle map for the requested buffers and update
222   // the buffer handle in requested buffers.
223   status_t UpdateRequestedBufferHandles(std::vector<StreamBuffer>* buffers);
224 
225   // Request buffers from stream buffer cache manager
226   status_t RequestBuffersFromStreamBufferCacheManager(
227       int32_t stream_id, uint32_t num_buffers,
228       std::vector<StreamBuffer>* buffers, uint32_t frame_number);
229 
230   // Register configured streams into stream buffer cache manager
231   status_t RegisterStreamsIntoCacheManagerLocked(
232       const StreamConfiguration& stream_config,
233       const std::vector<HalStream>& hal_stream);
234 
235   // Update the inflight requests/streams and notify SBC for flushing if the
236   // inflight requests/streams map is empty.
237   status_t UpdatePendingRequest(CaptureResult* result);
238 
239   // Process the notification returned from the HWL
240   void Notify(const NotifyMessage& result);
241 
242   // Process the batched notification returned from the HWL
243   void NotifyBatch(const std::vector<NotifyMessage>& results);
244 
245   // Process the capture result returned from the HWL
246   void ProcessCaptureResult(std::unique_ptr<CaptureResult> result);
247 
248   // Process the batched capture result returned from the HWL
249   void ProcessBatchCaptureResult(
250       std::vector<std::unique_ptr<CaptureResult>> results);
251 
252   // Notify error message with error code for stream of frame[frame_number].
253   // Caller is responsible to make sure this function is called only once for any frame.
254   void NotifyErrorMessage(uint32_t frame_number, int32_t stream_id,
255                           ErrorCode error_code);
256 
257   // Notify buffer error for all output streams in request
258   void NotifyBufferError(const CaptureRequest& request);
259 
260   // Notify buffer error for stream_id in frame_number
261   void NotifyBufferError(uint32_t frame_number, int32_t stream_id,
262                          uint64_t buffer_id);
263 
264   // Try to check if result contains placeholder buffer or placeholder buffer
265   // from this result has been observed. If so, handle this result specifically.
266   // Set result_handled as true.
267   status_t TryHandlePlaceholderResult(CaptureResult* result,
268                                       bool* result_handled);
269 
270   // Check if all streams in the current session are active in SBC manager
271   status_t HandleSBCInactiveStreams(const CaptureRequest& request,
272                                     bool* all_active);
273 
274   // Check the capture request before sending it to HWL. Only needed when HAL
275   // Buffer Management is supported. The SBC manager determines if it is
276   // necessasry to process the request still by checking if all streams are
277   // still active for buffer requests.
278   void CheckRequestForStreamBufferCacheManager(const CaptureRequest& request,
279                                                bool* need_to_process);
280 
281   // Return true if a request is valid. Must be exclusively protected by
282   // session_lock_.
283   status_t ValidateRequestLocked(const CaptureRequest& request);
284 
285   // Invoked when thermal status changes.
286   void NotifyThrottling(const Temperature& temperature);
287 
288   // Unregister thermal callback.
289   void UnregisterThermalCallback();
290 
291   // Load HAL external capture session libraries.
292   status_t LoadExternalCaptureSession(
293       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries);
294 
295   void InitializeZoomRatioMapper(HalCameraMetadata* characteristics);
296 
297   // For all the stream ID groups, derive the mapping between all stream IDs
298   // within that group to one single stream ID for easier tracking.
299   void DeriveGroupedStreamIdMap();
300 
301   // Try handling a single capture result. Returns true when the result callback
302   // was sent in the function, or failed to handle it by running into an
303   // error. So the caller could skip sending the result callback when the
304   // function returned true.
305   bool TryHandleCaptureResult(std::unique_ptr<CaptureResult>& result);
306 
307   // Tracks the returned buffers in capture results.
308   void TrackReturnedBuffers(const std::vector<StreamBuffer>& buffers);
309 
310   // Checks if `message` should be sent to the framework. It also updates the
311   // last shutter timestamp if systrace is enabled.
312   bool ShouldSendNotifyMessage(const NotifyMessage& message);
313 
314   uint32_t camera_id_ = 0;
315   std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl_;
316 
317   // Assuming callbacks to framework is thread-safe, the shared mutex is only
318   // used to protect member variable writing and reading.
319   std::shared_mutex session_callback_lock_;
320   // Session callback to the client. Protected by session_callback_lock_
321   CameraDeviceSessionCallback session_callback_;
322 
323   // Camera Device Session callback to the camera device session. Protected by
324   // session_callback_lock_
325   CameraDeviceSessionCallback camera_device_session_callback_;
326 
327   // Callback to get thermal information. Protected by session_callback_lock_.
328   ThermalCallback thermal_callback_;
329 
330   // Session callback from HWL session. Protected by session_callback_lock_
331   HwlSessionCallback hwl_session_callback_;
332 
333   // imported_buffer_handle_map_lock_ protects the following variables as noted.
334   std::mutex imported_buffer_handle_map_lock_;
335 
336   // Store the imported buffer handles from camera framework. Protected by
337   // imported_buffer_handle_map_lock.
338   std::unordered_map<BufferCache, buffer_handle_t, BufferCacheHashing>
339       imported_buffer_handle_map_;
340 
341   // session_lock_ protects the following variables as noted.
342   std::mutex session_lock_;
343 
344   // capture_session_lock_ protects the following variables as noted.
345   std::shared_mutex capture_session_lock_;
346 
347   std::unique_ptr<CaptureSession>
348       capture_session_;  // Protected by capture_session_lock_.
349 
350   // Map from a stream ID to the configured stream received from frameworks.
351   // Protected by session_lock_.
352   std::unordered_map<int32_t, Stream> configured_streams_map_;
353 
354   // Map from all stream IDs within a stream group to one single stream ID for
355   // easier request/buffer tracking. For example, if a stream group contains 3
356   // streams: {1, 2, 3}, The mapping could be {2->1, 3->1}. All requests and
357   // buffers for stream 2 and stream 3 will be mapped to stream 1 for tracking.
358   std::unordered_map<int32_t, int32_t> grouped_stream_id_map_;
359 
360   // Last valid settings in capture request. Must be protected by session_lock_.
361   std::unique_ptr<HalCameraMetadata> last_request_settings_;
362 
363   // If thermal status has become >= ThrottlingSeverity::Severe since stream
364   // configuration.
365   // Must be protected by session_lock_.
366   uint8_t thermal_throttling_ = false;
367 
368   // If device session has notified capture session about thermal throttling.
369   // Must be protected by session_lock_.
370   bool thermal_throttling_notified_ = false;
371 
372   // Predefined wrapper capture session entry points
373   static std::vector<WrapperCaptureSessionEntryFuncs> kWrapperCaptureSessionEntries;
374 
375   // Predefined capture session entry points
376   static std::vector<CaptureSessionEntryFuncs> kCaptureSessionEntries;
377 
378   // External capture session entry points
379   std::vector<ExternalCaptureSessionFactory*> external_capture_session_entries_;
380 
381   // Opened library handles that should be closed on destruction
382   std::vector<void*> external_capture_session_lib_handles_;
383 
384   // hwl allocator
385   CameraBufferAllocatorHwl* camera_allocator_hwl_ = nullptr;
386 
387   // If buffer management API support is used for the session configured
388   bool buffer_management_used_ = false;
389 
390   // If session specific hal buffer manager is supported by the HAL
391   bool session_buffer_management_supported_ = false;
392 
393   // The set of hal buffer managed stream ids. This is set during capture
394   // session creation time and is constant thereafter. As per the AIDL interface
395   // contract, the framework also does not every call configureStreams while
396   // captures are ongoing - i.e. all buffers and output metadata is not returned
397   // to the framework. Consequently, this does not need to be protected  after
398   // stream configuration is completed.
399   std::set<int32_t> hal_buffer_managed_stream_ids_;
400 
401   // Pending requests tracker used when buffer management API is enabled.
402   // Protected by session_lock_.
403   std::unique_ptr<PendingRequestsTracker> pending_requests_tracker_;
404 
405   // Stream buffer cache manager supports the HAL Buffer Management by caching
406   // buffers acquired from framework
407   std::unique_ptr<StreamBufferCacheManager> stream_buffer_cache_manager_;
408 
409   // If we receives valid settings since stream configuration.
410   // Protected by session_lock_.
411   bool has_valid_settings_ = false;
412 
413   // If the previous output intent had a stream with video encoder usage.
414   bool prev_output_intent_has_video_ = false;
415 
416   // request_record_lock_ protects the following variables as noted
417   std::mutex request_record_lock_;
418 
419   // Map from frame number to a set of stream ids, which exist in
420   // request[frame number] - only used by hal buffer managed streams
421   // Protected by request_record_lock_;
422   std::map<uint32_t, std::set<int32_t>> pending_request_streams_;
423 
424   // Set of requests that have been notified for ERROR_REQUEST during buffer
425   // request stage.
426   // Protected by request_record_lock_;
427   std::set<uint32_t> error_notified_requests_;
428 
429   // Set of placeholder buffer observed
430   std::set<buffer_handle_t> placeholder_buffer_observed_;
431 
432   // The last shutter timestamp in nanoseconds if systrace is enabled. Reset
433   // after stream configuration.
434   int64_t last_timestamp_ns_for_trace_ = 0;
435 
436   // Whether this stream configuration is a multi-res reprocessing configuration
437   bool multi_res_reprocess_ = false;
438 
439   // Flush is running or not
440   std::atomic<bool> is_flushing_ = false;
441 
442   // Zoom ratio mapper
443   ZoomRatioMapper zoom_ratio_mapper_;
444 
445   // Record the result metadata of pending request
446   // Protected by request_record_lock_;
447   std::set<uint32_t> pending_results_;
448 
449   // Record the shutters need to ignore for error result case
450   // Protected by request_record_lock_;
451   std::set<uint32_t> ignore_shutters_;
452 
453   // Stream use cases supported by this camera device
454   std::map<uint32_t, std::set<int64_t>> camera_id_to_stream_use_cases_;
455 
456   static constexpr int32_t kInvalidStreamId = -1;
457 
458   // Whether measure the time of buffer allocation
459   bool measure_buffer_allocation_time_ = false;
460 };
461 
462 }  // namespace google_camera_hal
463 }  // namespace android
464 
465 #endif  // HARDWARE_GOOGLE_CAMERA_HAL_GOOGLE_CAMERA_HAL_CAMERA_DEVICE__SESSION_H_
466