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