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 24 #include <memory> 25 #include <set> 26 #include <shared_mutex> 27 #include <vector> 28 29 #include "camera_buffer_allocator_hwl.h" 30 #include "camera_device_session_hwl.h" 31 #include "capture_session.h" 32 #include "capture_session_utils.h" 33 #include "hal_camera_metadata.h" 34 #include "hal_types.h" 35 #include "hwl_types.h" 36 #include "pending_requests_tracker.h" 37 #include "stream_buffer_cache_manager.h" 38 #include "thermal_types.h" 39 #include "zoom_ratio_mapper.h" 40 41 namespace android { 42 namespace google_camera_hal { 43 44 // Defines callbacks to be invoked by a CameraDeviceSession. 45 struct CameraDeviceSessionCallback { 46 // Callback to notify when a camera device produces a capture result. 47 ProcessCaptureResultFunc process_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 // hal_configured_streams is filled by this method with configured stream. 104 status_t ConfigureStreams(const StreamConfiguration& stream_config, 105 std::vector<HalStream>* hal_configured_streams); 106 107 // Process a capture request. 108 // num_processed_requests is filled by this method with the number of 109 // processed requests. 110 status_t ProcessCaptureRequest(const std::vector<CaptureRequest>& requests, 111 uint32_t* num_processed_requests); 112 113 // Remove the buffer caches kept in the camera device session. 114 void RemoveBufferCache(const std::vector<BufferCache>& buffer_caches); 115 116 // Flush all pending requests. 117 status_t Flush(); 118 119 // Check reconfiguration is required or not 120 // old_session is old session parameter 121 // new_session is new session parameter 122 // If reconfiguration is required, set reconfiguration_required to true 123 // If reconfiguration is not required, set reconfiguration_required to false 124 status_t IsReconfigurationRequired(const HalCameraMetadata* old_session, 125 const HalCameraMetadata* new_session, 126 bool* reconfiguration_required); 127 128 std::unique_ptr<google::camera_common::Profiler> GetProfiler(uint32_t camere_id, 129 int option); 130 131 protected: 132 CameraDeviceSession() = default; 133 134 private: 135 // Define buffer cache hashing in order to use BufferCache as a key of an 136 // unordered map. 137 struct BufferCacheHashing { operatorBufferCacheHashing138 unsigned long operator()(const BufferCache& buffer_cache) const { 139 std::string s = "s" + std::to_string(buffer_cache.stream_id) + "b" + 140 std::to_string(buffer_cache.buffer_id); 141 return std::hash<std::string>{}(s); 142 } 143 }; 144 145 status_t Initialize( 146 std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl, 147 CameraBufferAllocatorHwl* camera_allocator_hwl, 148 std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries); 149 150 // Initialize the latest available gralloc buffer mapper. 151 status_t InitializeBufferMapper(); 152 153 // Initialize callbacks from HWL and callbacks to the client. 154 void InitializeCallbacks(); 155 156 // Initialize buffer management support. 157 status_t InitializeBufferManagement(HalCameraMetadata* characteristics); 158 159 // Update all buffer handles in buffers with the imported buffer handles. 160 // Must be protected by imported_buffer_handle_map_lock_. 161 status_t UpdateBufferHandlesLocked(std::vector<StreamBuffer>* buffers); 162 163 // Import the buffer handles in the request. 164 status_t ImportRequestBufferHandles(const CaptureRequest& request); 165 166 // Import the buffer handles of buffers. 167 status_t ImportBufferHandles(const std::vector<StreamBuffer>& buffers); 168 169 // Import the buffer handle of a buffer. 170 // Must be protected by imported_buffer_handle_map_lock_. 171 template <class T, class U> 172 status_t ImportBufferHandleLocked(const sp<T> buffer_mapper, 173 const StreamBuffer& buffer); 174 175 // Create a request with updated buffer handles and modified settings. 176 // Must be protected by session_lock_. 177 status_t CreateCaptureRequestLocked(const CaptureRequest& request, 178 CaptureRequest* updated_request); 179 180 // Add a buffer handle to the imported buffer handle map. If the buffer cache 181 // is already in the map but the buffer handle doesn't match, it will 182 // return BAD_VALUE. 183 // Must be protected by imported_buffer_handle_map_lock_. 184 status_t AddImportedBufferHandlesLocked(const BufferCache& buffer_cache, 185 buffer_handle_t buffer_handle); 186 187 // Return if the buffer handle for a certain buffer ID is imported. 188 // Must be protected by imported_buffer_handle_map_lock_. 189 bool IsBufferImportedLocked(int32_t stream_id, uint32_t buffer_id); 190 191 // Free all imported buffer handles belonging to the stream id. 192 // Must be protected by imported_buffer_handle_map_lock_. 193 template <class T> 194 void FreeBufferHandlesLocked(const sp<T> buffer_mapper, int32_t stream_id); 195 196 template <class T> 197 void FreeImportedBufferHandles(const sp<T> buffer_mapper); 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 // Notify error message with error code for stream of frame[frame_number]. 243 // Caller is responsible to make sure this function is called only once for any frame. 244 void NotifyErrorMessage(uint32_t frame_number, int32_t stream_id, 245 ErrorCode error_code); 246 247 // Notify buffer error for all output streams in request 248 void NotifyBufferError(const CaptureRequest& request); 249 250 // Notify buffer error for stream_id in frame_number 251 void NotifyBufferError(uint32_t frame_number, int32_t stream_id, 252 uint64_t buffer_id); 253 254 // Try to check if result contains dummy buffer or dummy buffer from this 255 // result has been observed. If so, handle this result specifically. Set 256 // result_handled as true. 257 status_t TryHandleDummyResult(CaptureResult* result, bool* result_handled); 258 259 // Check if all streams in the current session are active in SBC manager 260 status_t HandleInactiveStreams(const CaptureRequest& request, 261 bool* all_active); 262 263 // Check the capture request before sending it to HWL. Only needed when HAL 264 // Buffer Management is supported. The SBC manager determines if it is 265 // necessasry to process the request still by checking if all streams are 266 // still active for buffer requests. 267 void CheckRequestForStreamBufferCacheManager(const CaptureRequest& request, 268 bool* need_to_process); 269 270 // Return true if a request is valid. Must be exclusively protected by 271 // session_lock_. 272 status_t ValidateRequestLocked(const CaptureRequest& request); 273 274 // Invoked when thermal status changes. 275 void NotifyThrottling(const Temperature& temperature); 276 277 // Unregister thermal callback. 278 void UnregisterThermalCallback(); 279 280 // Load HAL external capture session libraries. 281 status_t LoadExternalCaptureSession( 282 std::vector<GetCaptureSessionFactoryFunc> external_session_factory_entries); 283 284 void InitializeZoomRatioMapper(HalCameraMetadata* characteristics); 285 286 // For all the stream ID groups, derive the mapping between all stream IDs 287 // within that group to one single stream ID for easier tracking. 288 void DeriveGroupedStreamIdMap(); 289 290 uint32_t camera_id_ = 0; 291 std::unique_ptr<CameraDeviceSessionHwl> device_session_hwl_; 292 293 // Graphics buffer mapper used to import and free buffers. 294 sp<android::hardware::graphics::mapper::V2_0::IMapper> buffer_mapper_v2_; 295 sp<android::hardware::graphics::mapper::V3_0::IMapper> buffer_mapper_v3_; 296 sp<android::hardware::graphics::mapper::V4_0::IMapper> buffer_mapper_v4_; 297 298 // Assuming callbacks to framework is thread-safe, the shared mutex is only 299 // used to protect member variable writing and reading. 300 std::shared_mutex session_callback_lock_; 301 // Session callback to the client. Protected by session_callback_lock_ 302 CameraDeviceSessionCallback session_callback_; 303 304 // Camera Device Session callback to the camera device session. Protected by 305 // session_callback_lock_ 306 CameraDeviceSessionCallback camera_device_session_callback_; 307 308 // Callback to get thermal information. Protected by session_callback_lock_. 309 ThermalCallback thermal_callback_; 310 311 // Session callback from HWL session. Protected by session_callback_lock_ 312 HwlSessionCallback hwl_session_callback_; 313 314 // imported_buffer_handle_map_lock_ protects the following variables as noted. 315 std::mutex imported_buffer_handle_map_lock_; 316 317 // Store the imported buffer handles from camera framework. Protected by 318 // imported_buffer_handle_map_lock. 319 std::unordered_map<BufferCache, buffer_handle_t, BufferCacheHashing> 320 imported_buffer_handle_map_; 321 322 // session_lock_ protects the following variables as noted. 323 std::mutex session_lock_; 324 325 // capture_session_lock_ protects the following variables as noted. 326 std::shared_mutex capture_session_lock_; 327 328 std::unique_ptr<CaptureSession> 329 capture_session_; // Protected by capture_session_lock_. 330 331 // Map from a stream ID to the configured stream received from frameworks. 332 // Protected by session_lock_. 333 std::unordered_map<int32_t, Stream> configured_streams_map_; 334 335 // Map from all stream IDs within a stream group to one single stream ID for 336 // easier request/buffer tracking. For example, if a stream group contains 3 337 // streams: {1, 2, 3}, The mapping could be {2->1, 3->1}. All requests and 338 // buffers for stream 2 and stream 3 will be mapped to stream 1 for tracking. 339 std::unordered_map<int32_t, int32_t> grouped_stream_id_map_; 340 341 // Last valid settings in capture request. Must be protected by session_lock_. 342 std::unique_ptr<HalCameraMetadata> last_request_settings_; 343 344 // If thermal status has become >= ThrottlingSeverity::Severe since stream 345 // configuration. 346 // Must be protected by session_lock_. 347 uint8_t thermal_throttling_ = false; 348 349 // If device session has notified capture session about thermal throttling. 350 // Must be protected by session_lock_. 351 bool thermal_throttling_notified_ = false; 352 353 // Predefined wrapper capture session entry points 354 static std::vector<WrapperCaptureSessionEntryFuncs> kWrapperCaptureSessionEntries; 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 // If the previous output intent had a stream with video encoder usage. 384 bool prev_output_intent_has_video_ = false; 385 386 // request_record_lock_ protects the following variables as noted 387 std::mutex request_record_lock_; 388 389 // Map from frame number to a set of stream ids, which exist in 390 // request[frame number] 391 // Protected by request_record_lock_; 392 std::map<uint32_t, std::set<int32_t>> pending_request_streams_; 393 394 // Set of requests that have been notified for ERROR_REQUEST during buffer 395 // request stage. 396 // Protected by request_record_lock_; 397 std::set<uint32_t> error_notified_requests_; 398 399 // Set of dummy buffer observed 400 std::set<buffer_handle_t> dummy_buffer_observed_; 401 402 // The last shutter timestamp in nanoseconds if systrace is enabled. Reset 403 // after stream configuration. 404 int64_t last_timestamp_ns_for_trace_ = 0; 405 406 // Operation mode of stream configuration 407 StreamConfigurationMode operation_mode_ = StreamConfigurationMode::kNormal; 408 409 // Whether this stream configuration is a multi-res reprocessing configuration 410 bool multi_res_reprocess_ = false; 411 412 // Flush is running or not 413 std::atomic<bool> is_flushing_ = false; 414 415 // Zoom ratio mapper 416 ZoomRatioMapper zoom_ratio_mapper_; 417 418 // Record the result metadata of pending request 419 // Protected by request_record_lock_; 420 std::set<uint32_t> pending_results_; 421 422 // Record the shutters need to ignore for error result case 423 // Protected by request_record_lock_; 424 std::set<uint32_t> ignore_shutters_; 425 426 static constexpr int32_t kInvalidStreamId = -1; 427 428 // Whether measure the time of buffer allocation 429 bool measure_buffer_allocation_time_ = false; 430 }; 431 432 } // namespace google_camera_hal 433 } // namespace android 434 435 #endif // HARDWARE_GOOGLE_CAMERA_HAL_GOOGLE_CAMERA_HAL_CAMERA_DEVICE__SESSION_H_ 436