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