• 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 <android/hardware/graphics/mapper/2.0/IMapper.h>
21 #include <android/hardware/graphics/mapper/3.0/IMapper.h>
22 #include <android/hardware/graphics/mapper/4.0/IMapper.h>
23 #include <memory>
24 #include <set>
25 #include <shared_mutex>
26 
27 #include "camera_buffer_allocator_hwl.h"
28 #include "camera_device_session_hwl.h"
29 #include "capture_session.h"
30 #include "hal_camera_metadata.h"
31 #include "hal_types.h"
32 #include "pending_requests_tracker.h"
33 #include "stream_buffer_cache_manager.h"
34 #include "thermal_types.h"
35 #include "zoom_ratio_mapper.h"
36 
37 namespace android {
38 namespace google_camera_hal {
39 
40 // Defines callbacks to be invoked by a CameraDeviceSession.
41 struct CameraDeviceSessionCallback {
42   // Callback to notify when a camera device produces a capture result.
43   ProcessCaptureResultFunc process_capture_result;
44 
45   // Callback to notify shutters or errors.
46   NotifyFunc notify;
47 
48   // Callback to request stream buffers.
49   RequestStreamBuffersFunc request_stream_buffers;
50 
51   // Callback to return stream buffers.
52   ReturnStreamBuffersFunc return_stream_buffers;
53 };
54 
55 // Defines callbacks to get thermal information.
56 struct ThermalCallback {
57   // Register a thermal changed callback.
58   RegisterThermalChangedCallbackFunc register_thermal_changed_callback;
59 
60   // Unregister the thermal changed callback.
61   UnregisterThermalChangedCallbackFunc unregister_thermal_changed_callback;
62 };
63 
64 // Session function invoked to query if particular stream config supported
65 using StreamConfigSupportedFunc =
66     std::function<bool(CameraDeviceSessionHwl* device_session_hwl,
67                        const StreamConfiguration& stream_config)>;
68 
69 // Session function invoked to create session instance
70 using CaptureSessionCreateFunc = std::function<std::unique_ptr<CaptureSession>(
71     CameraDeviceSessionHwl* device_session_hwl,
72     const StreamConfiguration& stream_config,
73     ProcessCaptureResultFunc process_capture_result, NotifyFunc notify,
74     HwlRequestBuffersFunc request_stream_buffers,
75     std::vector<HalStream>* hal_configured_streams,
76     CameraBufferAllocatorHwl* camera_allocator_hwl)>;
77 
78 // define entry points to capture session
79 struct CaptureSessionEntryFuncs {
80   StreamConfigSupportedFunc IsStreamConfigurationSupported;
81   CaptureSessionCreateFunc CreateSession;
82 };
83 
84 // Entry point for getting an external capture session.
85 using GetCaptureSessionFactoryFunc = ExternalCaptureSessionFactory* (*)();
86 
87 // CameraDeviceSession implements functions needed for the HIDL camera device
88 // session interface, ICameraDeviceSession. It contains the methods to configure
89 // and request captures from an active camera device.
90 class CameraDeviceSession {
91  public:
92   // Create a CameraDeviceSession.
93   // device_session_hwl is a CameraDeviceSessionHwl that will be managed by this
94   // class.
95   // If device_session_hwl is nullptr, this method will return nullptr.
96   // camera_allocator_hwl is owned by the caller and must be valid during the
97   // lifetime of CameraDeviceSession
98   static std::unique_ptr<CameraDeviceSession> Create(
99       std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
100       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries,
101       CameraBufferAllocatorHwl* camera_allocator_hwl = nullptr);
102 
103   virtual ~CameraDeviceSession();
104 
105   // Set session callbacks
106   // Must be called before ConfigureStreams().
107   // session_callback will be invoked for capture results and messages.
108   // thermal_callback will be invoked for getting thermal information.
109   void SetSessionCallback(const CameraDeviceSessionCallback& session_callback,
110                           const ThermalCallback& thermal_callback);
111 
112   // Construct the default request settings for a request template type.
113   status_t ConstructDefaultRequestSettings(
114       RequestTemplate type,
115       std::unique_ptr<HalCameraMetadata>* default_settings);
116 
117   // Configure streams.
118   // stream_config is the requested stream configuration.
119   // hal_configured_streams is filled by this method with configured stream.
120   status_t ConfigureStreams(const StreamConfiguration& stream_config,
121                             std::vector<HalStream>* hal_configured_streams);
122 
123   // Process a capture request.
124   // num_processed_requests is filled by this method with the number of
125   // processed requests.
126   status_t ProcessCaptureRequest(const std::vector<CaptureRequest>& requests,
127                                  uint32_t* num_processed_requests);
128 
129   // Remove the buffer caches kept in the camera device session.
130   void RemoveBufferCache(const std::vector<BufferCache>& buffer_caches);
131 
132   // Flush all pending requests.
133   status_t Flush();
134 
135   // Check reconfiguration is required or not
136   // old_session is old session parameter
137   // new_session is new session parameter
138   // If reconfiguration is required, set reconfiguration_required to true
139   // If reconfiguration is not required, set reconfiguration_required to false
140   status_t IsReconfigurationRequired(const HalCameraMetadata* old_session,
141                                      const HalCameraMetadata* new_session,
142                                      bool* reconfiguration_required);
143 
144  protected:
145   CameraDeviceSession() = default;
146 
147  private:
148   // Define buffer cache hashing in order to use BufferCache as a key of an
149   // unordered map.
150   struct BufferCacheHashing {
operatorBufferCacheHashing151     unsigned long operator()(const BufferCache& buffer_cache) const {
152       std::string s = "s" + std::to_string(buffer_cache.stream_id) + "b" +
153                       std::to_string(buffer_cache.buffer_id);
154       return std::hash<std::string>{}(s);
155     }
156   };
157 
158   status_t Initialize(
159       std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl,
160       CameraBufferAllocatorHwl* camera_allocator_hwl,
161       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries);
162 
163   // Initialize the latest available gralloc buffer mapper.
164   status_t InitializeBufferMapper();
165 
166   // Initialize callbacks from HWL and callbacks to the client.
167   void InitializeCallbacks();
168 
169   // Initialize buffer management support.
170   status_t InitializeBufferManagement(HalCameraMetadata* characteristics);
171 
172   // Update all buffer handles in buffers with the imported buffer handles.
173   // Must be protected by imported_buffer_handle_map_lock_.
174   status_t UpdateBufferHandlesLocked(std::vector<StreamBuffer>* buffers);
175 
176   // Import the buffer handles in the request.
177   status_t ImportRequestBufferHandles(const CaptureRequest& request);
178 
179   // Import the buffer handles of buffers.
180   status_t ImportBufferHandles(const std::vector<StreamBuffer>& buffers);
181 
182   // Import the buffer handle of a buffer.
183   // Must be protected by imported_buffer_handle_map_lock_.
184   template <class T, class U>
185   status_t ImportBufferHandleLocked(const sp<T> buffer_mapper,
186                                     const StreamBuffer& buffer);
187 
188   // Create a request with updated buffer handles and modified settings.
189   // Must be protected by session_lock_.
190   status_t CreateCaptureRequestLocked(const CaptureRequest& request,
191                                       CaptureRequest* updated_request);
192 
193   // Add a buffer handle to the imported buffer handle map. If the buffer cache
194   // is already in the map but the buffer handle doesn't match, it will
195   // return BAD_VALUE.
196   // Must be protected by imported_buffer_handle_map_lock_.
197   status_t AddImportedBufferHandlesLocked(const BufferCache& buffer_cache,
198                                           buffer_handle_t buffer_handle);
199 
200   // Return if the buffer handle for a certain buffer ID is imported.
201   // Must be protected by imported_buffer_handle_map_lock_.
202   bool IsBufferImportedLocked(int32_t stream_id, uint32_t buffer_id);
203 
204   // Free all imported buffer handles belonging to the stream id.
205   // Must be protected by imported_buffer_handle_map_lock_.
206   template <class T>
207   void FreeBufferHandlesLocked(const sp<T> buffer_mapper, int32_t stream_id);
208 
209   template <class T>
210   void FreeImportedBufferHandles(const sp<T> buffer_mapper);
211 
212   // Clean up stale streams with new stream configuration.
213   // Must be protected by session_lock_.
214   void CleanupStaleStreamsLocked(const std::vector<Stream>& new_streams);
215 
216   // Append output intent to request settings.
217   // Must be protected by session_lock_.
218   void AppendOutputIntentToSettingsLocked(const CaptureRequest& request,
219                                           CaptureRequest* updated_request);
220 
221   // Invoked by HWL to request stream buffers when buffer management is
222   // supported.
223   status_t RequestStreamBuffers(int32_t stream_id, uint32_t num_buffers,
224                                 std::vector<StreamBuffer>* buffers,
225                                 StreamBufferRequestError* request_status);
226 
227   // Invoked by HWL to return stream buffers when buffer management is
228   // supported.
229   void ReturnStreamBuffers(const std::vector<StreamBuffer>& buffers);
230 
231   // Update imported buffer handle map for the requested buffers and update
232   // the buffer handle in requested buffers.
233   status_t UpdateRequestedBufferHandles(std::vector<StreamBuffer>* buffers);
234 
235   // Request buffers from stream buffer cache manager
236   status_t RequestBuffersFromStreamBufferCacheManager(
237       int32_t stream_id, uint32_t num_buffers,
238       std::vector<StreamBuffer>* buffers, uint32_t frame_number);
239 
240   // Register configured streams into stream buffer cache manager
241   status_t RegisterStreamsIntoCacheManagerLocked(
242       const StreamConfiguration& stream_config,
243       const std::vector<HalStream>& hal_stream);
244 
245   // Update the inflight requests/streams and notify SBC for flushing if the
246   // inflight requests/streams map is empty.
247   status_t UpdatePendingRequest(CaptureResult* result);
248 
249   // Process the notification returned from the HWL
250   void Notify(const NotifyMessage& result);
251 
252   // Process the capture result returned from the HWL
253   void ProcessCaptureResult(std::unique_ptr<CaptureResult> result);
254 
255   // Notify error message with error code for stream of frame[frame_number].
256   // Caller is responsible to make sure this function is called only once for any frame.
257   void NotifyErrorMessage(uint32_t frame_number, int32_t stream_id,
258                           ErrorCode error_code);
259 
260   // Notify buffer error for all output streams in request
261   void NotifyBufferError(const CaptureRequest& request);
262 
263   // Notify buffer error for stream_id in frame_number
264   void NotifyBufferError(uint32_t frame_number, int32_t stream_id,
265                          uint64_t buffer_id);
266 
267   // Try to check if result contains dummy buffer or dummy buffer from this
268   // result has been observed. If so, handle this result specifically. Set
269   // result_handled as true.
270   status_t TryHandleDummyResult(CaptureResult* result, bool* result_handled);
271 
272   // Check if all streams in the current session are active in SBC manager
273   status_t HandleInactiveStreams(const CaptureRequest& request,
274                                  bool* all_active);
275 
276   // Check the capture request before sending it to HWL. Only needed when HAL
277   // Buffer Management is supported. The SBC manager determines if it is
278   // necessasry to process the request still by checking if all streams are
279   // still active for buffer requests.
280   void CheckRequestForStreamBufferCacheManager(const CaptureRequest& request,
281                                                bool* need_to_process);
282 
283   // Return true if a request is valid. Must be exclusively protected by
284   // session_lock_.
285   status_t ValidateRequestLocked(const CaptureRequest& request);
286 
287   // Invoked when thermal status changes.
288   void NotifyThrottling(const Temperature& temperature);
289 
290   // Unregister thermal callback.
291   void UnregisterThermalCallback();
292 
293   // Load HAL external capture session libraries.
294   status_t LoadExternalCaptureSession(
295       std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries);
296 
297   void InitializeZoomRatioMapper(HalCameraMetadata* characteristics);
298 
299   uint32_t camera_id_ = 0;
300   std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl_;
301 
302   // Graphics buffer mapper used to import and free buffers.
303   sp<android::hardware::graphics::mapper::V2_0::IMapper> buffer_mapper_v2_;
304   sp<android::hardware::graphics::mapper::V3_0::IMapper> buffer_mapper_v3_;
305   sp<android::hardware::graphics::mapper::V4_0::IMapper> buffer_mapper_v4_;
306 
307   // Assuming callbacks to framework is thread-safe, the shared mutex is only
308   // used to protect member variable writing and reading.
309   std::shared_mutex session_callback_lock_;
310   // Session callback to the client. Protected by session_callback_lock_
311   CameraDeviceSessionCallback session_callback_;
312 
313   // Camera Device Session callback to the camera device session. Protected by
314   // session_callback_lock_
315   CameraDeviceSessionCallback camera_device_session_callback_;
316 
317   // Callback to get thermal information. Protected by session_callback_lock_.
318   ThermalCallback thermal_callback_;
319 
320   // Session callback from HWL session. Protected by session_callback_lock_
321   HwlSessionCallback hwl_session_callback_;
322 
323   // imported_buffer_handle_map_lock_ protects the following variables as noted.
324   std::mutex imported_buffer_handle_map_lock_;
325 
326   // Store the imported buffer handles from camera framework. Protected by
327   // imported_buffer_handle_map_lock.
328   std::unordered_map<BufferCache, buffer_handle_t, BufferCacheHashing>
329       imported_buffer_handle_map_;
330 
331   // session_lock_ protects the following variables as noted.
332   std::mutex session_lock_;
333 
334   // capture_session_lock_ protects the following variables as noted.
335   std::shared_mutex capture_session_lock_;
336 
337   std::unique_ptr<CaptureSession>
338       capture_session_;  // Protected by capture_session_lock_.
339 
340   // Map from a stream ID to the configured stream received from frameworks.
341   // Protected by session_lock_.
342   std::unordered_map<int32_t, Stream> configured_streams_map_;
343 
344   // Last valid settings in capture request. Must be protected by session_lock_.
345   std::unique_ptr<HalCameraMetadata> last_request_settings_;
346 
347   // If thermal status has become >= ThrottlingSeverity::Severe since stream
348   // configuration.
349   // Must be protected by session_lock_.
350   uint8_t thermal_throttling_ = false;
351 
352   // If device session has notified capture session about thermal throttling.
353   // Must be protected by session_lock_.
354   bool thermal_throttling_notified_ = false;
355 
356   // Predefined capture session entry points
357   static std::vector<CaptureSessionEntryFuncs> kCaptureSessionEntries;
358 
359   // External capture session entry points
360   std::vector<ExternalCaptureSessionFactory*> external_capture_session_entries_;
361 
362   // Opened library handles that should be closed on destruction
363   std::vector<void*> external_capture_session_lib_handles_;
364 
365   // hwl allocator
366   CameraBufferAllocatorHwl* camera_allocator_hwl_ = nullptr;
367 
368   // If buffer management API support.
369   bool buffer_management_supported_ = false;
370 
371   // Pending requests tracker used when buffer management API is enabled.
372   // Protected by session_lock_.
373   std::unique_ptr<PendingRequestsTracker> pending_requests_tracker_;
374 
375   // Stream buffer cache manager supports the HAL Buffer Management by caching
376   // buffers acquired from framework
377   std::unique_ptr<StreamBufferCacheManager> stream_buffer_cache_manager_;
378 
379   // If we receives valid settings since stream configuration.
380   // Protected by session_lock_.
381   bool has_valid_settings_ = false;
382 
383   // request_record_lock_ protects the following variables as noted
384   std::mutex request_record_lock_;
385 
386   // Map from frame number to a set of stream ids, which exist in
387   // request[frame number]
388   // Protected by request_record_lock_;
389   std::map<uint32_t, std::set<int32_t>> pending_request_streams_;
390 
391   // Set of requests that have been notified for ERROR_REQUEST during buffer
392   // request stage.
393   // Protected by request_record_lock_;
394   std::set<uint32_t> error_notified_requests_;
395 
396   // Set of dummy buffer observed
397   std::set<buffer_handle_t> dummy_buffer_observed_;
398 
399   // The last shutter timestamp in nanoseconds if systrace is enabled. Reset
400   // after stream configuration.
401   int64_t last_timestamp_ns_for_trace_ = 0;
402 
403   // Operation mode of stream configuration
404   StreamConfigurationMode operation_mode_ = StreamConfigurationMode::kNormal;
405 
406   // Flush is running or not
407   std::atomic<bool> is_flushing_ = false;
408 
409   // Zoom ratio mapper
410   ZoomRatioMapper zoom_ratio_mapper_;
411 
412   // Record the result metadata of pending request
413   // Protected by request_record_lock_;
414   std::set<uint32_t> pending_results_;
415 
416   static constexpr int32_t kInvalidStreamId = -1;
417 };
418 
419 }  // namespace google_camera_hal
420 }  // namespace android
421 
422 #endif  // HARDWARE_GOOGLE_CAMERA_HAL_GOOGLE_CAMERA_HAL_CAMERA_DEVICE__SESSION_H_
423