1/* 2 * Copyright (C) 2013 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 ANDROID_SERVERS_CAMERA3DEVICE_H 18#define ANDROID_SERVERS_CAMERA3DEVICE_H 19 20#include <utils/Condition.h> 21#include <utils/Errors.h> 22#include <utils/List.h> 23#include <utils/Mutex.h> 24#include <utils/Thread.h> 25#include <utils/KeyedVector.h> 26#include <hardware/camera3.h> 27 28#include "common/CameraDeviceBase.h" 29#include "device3/StatusTracker.h" 30 31/** 32 * Function pointer types with C calling convention to 33 * use for HAL callback functions. 34 */ 35extern "C" { 36 typedef void (callbacks_process_capture_result_t)( 37 const struct camera3_callback_ops *, 38 const camera3_capture_result_t *); 39 40 typedef void (callbacks_notify_t)( 41 const struct camera3_callback_ops *, 42 const camera3_notify_msg_t *); 43} 44 45namespace android { 46 47namespace camera3 { 48 49class Camera3Stream; 50class Camera3ZslStream; 51class Camera3OutputStreamInterface; 52class Camera3StreamInterface; 53 54} 55 56/** 57 * CameraDevice for HAL devices with version CAMERA_DEVICE_API_VERSION_3_0 58 */ 59class Camera3Device : 60 public CameraDeviceBase, 61 private camera3_callback_ops { 62 public: 63 Camera3Device(int id); 64 65 virtual ~Camera3Device(); 66 67 /** 68 * CameraDeviceBase interface 69 */ 70 71 virtual int getId() const; 72 73 // Transitions to idle state on success. 74 virtual status_t initialize(camera_module_t *module); 75 virtual status_t disconnect(); 76 virtual status_t dump(int fd, const Vector<String16> &args); 77 virtual const CameraMetadata& info() const; 78 79 // Capture and setStreamingRequest will configure streams if currently in 80 // idle state 81 virtual status_t capture(CameraMetadata &request); 82 virtual status_t setStreamingRequest(const CameraMetadata &request); 83 virtual status_t clearStreamingRequest(); 84 85 virtual status_t waitUntilRequestReceived(int32_t requestId, nsecs_t timeout); 86 87 // Actual stream creation/deletion is delayed until first request is submitted 88 // If adding streams while actively capturing, will pause device before adding 89 // stream, reconfiguring device, and unpausing. 90 virtual status_t createStream(sp<ANativeWindow> consumer, 91 uint32_t width, uint32_t height, int format, size_t size, 92 int *id); 93 virtual status_t createInputStream( 94 uint32_t width, uint32_t height, int format, 95 int *id); 96 virtual status_t createZslStream( 97 uint32_t width, uint32_t height, 98 int depth, 99 /*out*/ 100 int *id, 101 sp<camera3::Camera3ZslStream>* zslStream); 102 virtual status_t createReprocessStreamFromStream(int outputId, int *id); 103 104 virtual status_t getStreamInfo(int id, 105 uint32_t *width, uint32_t *height, uint32_t *format); 106 virtual status_t setStreamTransform(int id, int transform); 107 108 virtual status_t deleteStream(int id); 109 virtual status_t deleteReprocessStream(int id); 110 111 virtual status_t createDefaultRequest(int templateId, CameraMetadata *request); 112 113 // Transitions to the idle state on success 114 virtual status_t waitUntilDrained(); 115 116 virtual status_t setNotifyCallback(NotificationListener *listener); 117 virtual bool willNotify3A(); 118 virtual status_t waitForNextFrame(nsecs_t timeout); 119 virtual status_t getNextFrame(CameraMetadata *frame); 120 121 virtual status_t triggerAutofocus(uint32_t id); 122 virtual status_t triggerCancelAutofocus(uint32_t id); 123 virtual status_t triggerPrecaptureMetering(uint32_t id); 124 125 virtual status_t pushReprocessBuffer(int reprocessStreamId, 126 buffer_handle_t *buffer, wp<BufferReleasedListener> listener); 127 128 virtual status_t flush(); 129 130 // Methods called by subclasses 131 void notifyStatus(bool idle); // updates from StatusTracker 132 133 private: 134 static const size_t kDumpLockAttempts = 10; 135 static const size_t kDumpSleepDuration = 100000; // 0.10 sec 136 static const size_t kInFlightWarnLimit = 20; 137 static const nsecs_t kShutdownTimeout = 5000000000; // 5 sec 138 static const nsecs_t kActiveTimeout = 500000000; // 500 ms 139 struct RequestTrigger; 140 141 // A lock to enforce serialization on the input/configure side 142 // of the public interface. 143 // Only locked by public methods inherited from CameraDeviceBase. 144 // Not locked by methods guarded by mOutputLock, since they may act 145 // concurrently to the input/configure side of the interface. 146 // Must be locked before mLock if both will be locked by a method 147 Mutex mInterfaceLock; 148 149 // The main lock on internal state 150 Mutex mLock; 151 152 // Camera device ID 153 const int mId; 154 155 /**** Scope for mLock ****/ 156 157 camera3_device_t *mHal3Device; 158 159 CameraMetadata mDeviceInfo; 160 vendor_tag_query_ops_t mVendorTagOps; 161 162 enum Status { 163 STATUS_ERROR, 164 STATUS_UNINITIALIZED, 165 STATUS_UNCONFIGURED, 166 STATUS_CONFIGURED, 167 STATUS_ACTIVE 168 } mStatus; 169 Vector<Status> mRecentStatusUpdates; 170 Condition mStatusChanged; 171 172 // Tracking cause of fatal errors when in STATUS_ERROR 173 String8 mErrorCause; 174 175 // Mapping of stream IDs to stream instances 176 typedef KeyedVector<int, sp<camera3::Camera3OutputStreamInterface> > 177 StreamSet; 178 179 StreamSet mOutputStreams; 180 sp<camera3::Camera3Stream> mInputStream; 181 int mNextStreamId; 182 bool mNeedConfig; 183 184 // Whether to send state updates upstream 185 // Pause when doing transparent reconfiguration 186 bool mPauseStateNotify; 187 188 // Need to hold on to stream references until configure completes. 189 Vector<sp<camera3::Camera3StreamInterface> > mDeletedStreams; 190 191 /**** End scope for mLock ****/ 192 193 class CaptureRequest : public LightRefBase<CaptureRequest> { 194 public: 195 CameraMetadata mSettings; 196 sp<camera3::Camera3Stream> mInputStream; 197 Vector<sp<camera3::Camera3OutputStreamInterface> > 198 mOutputStreams; 199 }; 200 typedef List<sp<CaptureRequest> > RequestList; 201 202 /** 203 * Get the last request submitted to the hal by the request thread. 204 * 205 * Takes mLock. 206 */ 207 virtual CameraMetadata getLatestRequestLocked(); 208 209 /** 210 * Pause processing and flush everything, but don't tell the clients. 211 * This is for reconfiguring outputs transparently when according to the 212 * CameraDeviceBase interface we shouldn't need to. 213 * Must be called with mLock and mInterfaceLock both held. 214 */ 215 status_t internalPauseAndWaitLocked(); 216 217 /** 218 * Resume work after internalPauseAndWaitLocked() 219 * Must be called with mLock and mInterfaceLock both held. 220 */ 221 status_t internalResumeLocked(); 222 223 /** 224 * Wait until status tracker tells us we've transitioned to the target state 225 * set, which is either ACTIVE when active==true or IDLE (which is any 226 * non-ACTIVE state) when active==false. 227 * 228 * Needs to be called with mLock and mInterfaceLock held. This means there 229 * can ever only be one waiter at most. 230 * 231 * During the wait mLock is released. 232 * 233 */ 234 status_t waitUntilStateThenRelock(bool active, nsecs_t timeout); 235 236 /** 237 * Do common work for setting up a streaming or single capture request. 238 * On success, will transition to ACTIVE if in IDLE. 239 */ 240 sp<CaptureRequest> setUpRequestLocked(const CameraMetadata &request); 241 242 /** 243 * Build a CaptureRequest request from the CameraDeviceBase request 244 * settings. 245 */ 246 sp<CaptureRequest> createCaptureRequest(const CameraMetadata &request); 247 248 /** 249 * Take the currently-defined set of streams and configure the HAL to use 250 * them. This is a long-running operation (may be several hundered ms). 251 */ 252 status_t configureStreamsLocked(); 253 254 /** 255 * Set device into an error state due to some fatal failure, and set an 256 * error message to indicate why. Only the first call's message will be 257 * used. The message is also sent to the log. 258 */ 259 void setErrorState(const char *fmt, ...); 260 void setErrorStateV(const char *fmt, va_list args); 261 void setErrorStateLocked(const char *fmt, ...); 262 void setErrorStateLockedV(const char *fmt, va_list args); 263 264 /** 265 * Debugging trylock/spin method 266 * Try to acquire a lock a few times with sleeps between before giving up. 267 */ 268 bool tryLockSpinRightRound(Mutex& lock); 269 270 struct RequestTrigger { 271 // Metadata tag number, e.g. android.control.aePrecaptureTrigger 272 uint32_t metadataTag; 273 // Metadata value, e.g. 'START' or the trigger ID 274 int32_t entryValue; 275 276 // The last part of the fully qualified path, e.g. afTrigger 277 const char *getTagName() const { 278 return get_camera_metadata_tag_name(metadataTag) ?: "NULL"; 279 } 280 281 // e.g. TYPE_BYTE, TYPE_INT32, etc. 282 int getTagType() const { 283 return get_camera_metadata_tag_type(metadataTag); 284 } 285 }; 286 287 /** 288 * Thread for managing capture request submission to HAL device. 289 */ 290 class RequestThread : public Thread { 291 292 public: 293 294 RequestThread(wp<Camera3Device> parent, 295 sp<camera3::StatusTracker> statusTracker, 296 camera3_device_t *hal3Device); 297 298 /** 299 * Call after stream (re)-configuration is completed. 300 */ 301 void configurationComplete(); 302 303 /** 304 * Set or clear the list of repeating requests. Does not block 305 * on either. Use waitUntilPaused to wait until request queue 306 * has emptied out. 307 */ 308 status_t setRepeatingRequests(const RequestList& requests); 309 status_t clearRepeatingRequests(); 310 311 status_t queueRequest(sp<CaptureRequest> request); 312 313 /** 314 * Remove all queued and repeating requests, and pending triggers 315 */ 316 status_t clear(); 317 318 /** 319 * Queue a trigger to be dispatched with the next outgoing 320 * process_capture_request. The settings for that request only 321 * will be temporarily rewritten to add the trigger tag/value. 322 * Subsequent requests will not be rewritten (for this tag). 323 */ 324 status_t queueTrigger(RequestTrigger trigger[], size_t count); 325 326 /** 327 * Pause/unpause the capture thread. Doesn't block, so use 328 * waitUntilPaused to wait until the thread is paused. 329 */ 330 void setPaused(bool paused); 331 332 /** 333 * Wait until thread processes the capture request with settings' 334 * android.request.id == requestId. 335 * 336 * Returns TIMED_OUT in case the thread does not process the request 337 * within the timeout. 338 */ 339 status_t waitUntilRequestProcessed(int32_t requestId, nsecs_t timeout); 340 341 /** 342 * Shut down the thread. Shutdown is asynchronous, so thread may 343 * still be running once this method returns. 344 */ 345 virtual void requestExit(); 346 347 /** 348 * Get the latest request that was sent to the HAL 349 * with process_capture_request. 350 */ 351 CameraMetadata getLatestRequest() const; 352 353 protected: 354 355 virtual bool threadLoop(); 356 357 private: 358 static int getId(const wp<Camera3Device> &device); 359 360 status_t queueTriggerLocked(RequestTrigger trigger); 361 // Mix-in queued triggers into this request 362 int32_t insertTriggers(const sp<CaptureRequest> &request); 363 // Purge the queued triggers from this request, 364 // restoring the old field values for those tags. 365 status_t removeTriggers(const sp<CaptureRequest> &request); 366 367 // HAL workaround: Make sure a trigger ID always exists if 368 // a trigger does 369 status_t addDummyTriggerIds(const sp<CaptureRequest> &request); 370 371 static const nsecs_t kRequestTimeout = 50e6; // 50 ms 372 373 // Waits for a request, or returns NULL if times out. 374 sp<CaptureRequest> waitForNextRequest(); 375 376 // Return buffers, etc, for a request that couldn't be fully 377 // constructed. The buffers will be returned in the ERROR state 378 // to mark them as not having valid data. 379 // All arguments will be modified. 380 void cleanUpFailedRequest(camera3_capture_request_t &request, 381 sp<CaptureRequest> &nextRequest, 382 Vector<camera3_stream_buffer_t> &outputBuffers); 383 384 // Pause handling 385 bool waitIfPaused(); 386 void unpauseForNewRequests(); 387 388 // Relay error to parent device object setErrorState 389 void setErrorState(const char *fmt, ...); 390 391 wp<Camera3Device> mParent; 392 wp<camera3::StatusTracker> mStatusTracker; 393 camera3_device_t *mHal3Device; 394 395 const int mId; // The camera ID 396 int mStatusId; // The RequestThread's component ID for 397 // status tracking 398 399 Mutex mRequestLock; 400 Condition mRequestSignal; 401 RequestList mRequestQueue; 402 RequestList mRepeatingRequests; 403 404 bool mReconfigured; 405 406 // Used by waitIfPaused, waitForNextRequest, and waitUntilPaused 407 Mutex mPauseLock; 408 bool mDoPause; 409 Condition mDoPauseSignal; 410 bool mPaused; 411 Condition mPausedSignal; 412 413 sp<CaptureRequest> mPrevRequest; 414 int32_t mPrevTriggers; 415 416 uint32_t mFrameNumber; 417 418 mutable Mutex mLatestRequestMutex; 419 Condition mLatestRequestSignal; 420 // android.request.id for latest process_capture_request 421 int32_t mLatestRequestId; 422 CameraMetadata mLatestRequest; 423 424 typedef KeyedVector<uint32_t/*tag*/, RequestTrigger> TriggerMap; 425 Mutex mTriggerMutex; 426 TriggerMap mTriggerMap; 427 TriggerMap mTriggerRemovedMap; 428 TriggerMap mTriggerReplacedMap; 429 }; 430 sp<RequestThread> mRequestThread; 431 432 /** 433 * In-flight queue for tracking completion of capture requests. 434 */ 435 436 struct InFlightRequest { 437 // android.request.id for the request 438 int requestId; 439 // Set by notify() SHUTTER call. 440 nsecs_t captureTimestamp; 441 int requestStatus; 442 // Set by process_capture_result call with valid metadata 443 bool haveResultMetadata; 444 // Decremented by calls to process_capture_result with valid output 445 // buffers 446 int numBuffersLeft; 447 448 // Default constructor needed by KeyedVector 449 InFlightRequest() : 450 requestId(0), 451 captureTimestamp(0), 452 requestStatus(OK), 453 haveResultMetadata(false), 454 numBuffersLeft(0) { 455 } 456 457 InFlightRequest(int id, int numBuffers) : 458 requestId(id), 459 captureTimestamp(0), 460 requestStatus(OK), 461 haveResultMetadata(false), 462 numBuffersLeft(numBuffers) { 463 } 464 }; 465 // Map from frame number to the in-flight request state 466 typedef KeyedVector<uint32_t, InFlightRequest> InFlightMap; 467 468 Mutex mInFlightLock; // Protects mInFlightMap 469 InFlightMap mInFlightMap; 470 471 status_t registerInFlight(int32_t frameNumber, int32_t requestId, 472 int32_t numBuffers); 473 474 /** 475 * Tracking for idle detection 476 */ 477 sp<camera3::StatusTracker> mStatusTracker; 478 479 /** 480 * Output result queue and current HAL device 3A state 481 */ 482 483 // Lock for output side of device 484 Mutex mOutputLock; 485 486 /**** Scope for mOutputLock ****/ 487 488 uint32_t mNextResultFrameNumber; 489 uint32_t mNextShutterFrameNumber; 490 List<CameraMetadata> mResultQueue; 491 Condition mResultSignal; 492 NotificationListener *mListener; 493 494 /**** End scope for mOutputLock ****/ 495 496 /** 497 * Callback functions from HAL device 498 */ 499 void processCaptureResult(const camera3_capture_result *result); 500 501 void notify(const camera3_notify_msg *msg); 502 503 /** 504 * Static callback forwarding methods from HAL to instance 505 */ 506 static callbacks_process_capture_result_t sProcessCaptureResult; 507 508 static callbacks_notify_t sNotify; 509 510}; // class Camera3Device 511 512}; // namespace android 513 514#endif 515