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