1 /* 2 * Copyright (C) 2013-2018 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_CAMERA3_STREAM_H 18 #define ANDROID_SERVERS_CAMERA3_STREAM_H 19 20 #include <gui/Surface.h> 21 #include <utils/RefBase.h> 22 #include <utils/String16.h> 23 #include <utils/List.h> 24 25 #include "utils/LatencyHistogram.h" 26 #include "Camera3StreamBufferListener.h" 27 #include "Camera3StreamInterface.h" 28 29 namespace android { 30 31 namespace camera3 { 32 33 /** 34 * A class for managing a single stream of input or output data from the camera 35 * device. 36 * 37 * The stream has an internal state machine to track whether it's 38 * connected/configured/etc. 39 * 40 * States: 41 * 42 * STATE_ERROR: A serious error has occurred, stream is unusable. Outstanding 43 * buffers may still be returned. 44 * 45 * STATE_CONSTRUCTED: The stream is ready for configuration, but buffers cannot 46 * be gotten yet. Not connected to any endpoint, no buffers are registered 47 * with the HAL. 48 * 49 * STATE_IN_CONFIG: Configuration has started, but not yet concluded. During this 50 * time, the usage, max_buffers, and priv fields of camera_stream returned by 51 * startConfiguration() may be modified. 52 * 53 * STATE_IN_RE_CONFIG: Configuration has started, and the stream has been 54 * configured before. Need to track separately from IN_CONFIG to avoid 55 * re-registering buffers with HAL. 56 * 57 * STATE_CONFIGURED: Stream is configured, and has registered buffers with the 58 * HAL (if necessary). The stream's getBuffer/returnBuffer work. The priv 59 * pointer may still be modified. 60 * 61 * STATE_PREPARING: The stream's buffers are being pre-allocated for use. On 62 * older HALs, this is done as part of configuration, but in newer HALs 63 * buffers may be allocated at time of first use. But some use cases require 64 * buffer allocation upfront, to minmize disruption due to lengthy allocation 65 * duration. In this state, only prepareNextBuffer() and cancelPrepare() 66 * may be called. 67 * 68 * STATE_IN_IDLE: This is a temporary state only intended to be used for input 69 * streams and only for the case where we need to re-configure the camera device 70 * while the input stream has an outstanding buffer. All other streams should not 71 * be able to switch to this state. For them this is invalid and should be handled 72 * as an unknown state. 73 * 74 * Transition table: 75 * 76 * <none> => STATE_CONSTRUCTED: 77 * When constructed with valid arguments 78 * <none> => STATE_ERROR: 79 * When constructed with invalid arguments 80 * STATE_CONSTRUCTED => STATE_IN_CONFIG: 81 * When startConfiguration() is called 82 * STATE_IN_CONFIG => STATE_CONFIGURED: 83 * When finishConfiguration() is called 84 * STATE_IN_CONFIG => STATE_ERROR: 85 * When finishConfiguration() fails to allocate or register buffers. 86 * STATE_CONFIGURED => STATE_IN_RE_CONFIG: * 87 * When startConfiguration() is called again, after making sure stream is 88 * idle with waitUntilIdle(). 89 * STATE_IN_RE_CONFIG => STATE_CONFIGURED: 90 * When finishConfiguration() is called. 91 * STATE_IN_RE_CONFIG => STATE_ERROR: 92 * When finishConfiguration() fails to allocate or register buffers. 93 * STATE_CONFIGURED => STATE_CONSTRUCTED: 94 * When disconnect() is called after making sure stream is idle with 95 * waitUntilIdle(). 96 * STATE_CONFIGURED => STATE_PREPARING: 97 * When startPrepare is called before the stream has a buffer 98 * queued back into it for the first time. 99 * STATE_PREPARING => STATE_CONFIGURED: 100 * When sufficient prepareNextBuffer calls have been made to allocate 101 * all stream buffers, or cancelPrepare is called. 102 * STATE_CONFIGURED => STATE_ABANDONED: 103 * When the buffer queue of the stream is abandoned. 104 * STATE_CONFIGURED => STATE_IN_IDLE: 105 * Only for an input stream which has an outstanding buffer. 106 * STATE_IN_IDLE => STATE_CONFIGURED: 107 * After the internal re-configuration, the input should revert back to 108 * the configured state. 109 * 110 * Status Tracking: 111 * Each stream is tracked by StatusTracker as a separate component, 112 * depending on the handed out buffer count. The state must be STATE_CONFIGURED 113 * in order for the component to be marked. 114 * 115 * It's marked in one of two ways: 116 * 117 * - ACTIVE: One or more buffers have been handed out (with #getBuffer). 118 * - IDLE: All buffers have been returned (with #returnBuffer), and their 119 * respective release_fence(s) have been signaled. The only exception to this 120 * rule is an input stream that moves to "STATE_IN_IDLE" during internal 121 * re-configuration. 122 * 123 * A typical use case is output streams. When the HAL has any buffers 124 * dequeued, the stream is marked ACTIVE. When the HAL returns all buffers 125 * (e.g. if no capture requests are active), the stream is marked IDLE. 126 * In this use case, the app consumer does not affect the component status. 127 * 128 */ 129 class Camera3Stream : 130 protected camera_stream, 131 public virtual Camera3StreamInterface, 132 public virtual RefBase { 133 public: 134 135 virtual ~Camera3Stream(); 136 137 static Camera3Stream* cast(camera_stream *stream); 138 static const Camera3Stream* cast(const camera_stream *stream); 139 140 // Queue corresponding HDR metadata to given native window. 141 static void queueHDRMetadata(buffer_handle_t buffer, sp<ANativeWindow>& anw, 142 int64_t dynamicRangeProfile); 143 144 /** 145 * Get the stream's ID 146 */ 147 int getId() const; 148 149 /** 150 * Get the output stream set id. 151 */ 152 int getStreamSetId() const; 153 /** 154 * Is this stream part of a multi-resolution stream set 155 */ 156 bool isMultiResolution() const; 157 /** 158 * Get the HAL stream group id for a multi-resolution stream set 159 */ 160 int getHalStreamGroupId() const; 161 162 /** 163 * Get the stream's dimensions and format 164 */ 165 uint32_t getWidth() const; 166 uint32_t getHeight() const; 167 int getFormat() const; 168 android_dataspace getDataSpace() const; 169 int32_t getColorSpace() const; 170 uint64_t getUsage() const; 171 void setUsage(uint64_t usage); 172 void setFormatOverride(bool formatOverridden); 173 bool isFormatOverridden() const; 174 int getOriginalFormat() const; 175 int64_t getDynamicRangeProfile() const; 176 void setDataSpaceOverride(bool dataSpaceOverridden); 177 bool isDataSpaceOverridden() const; 178 android_dataspace getOriginalDataSpace() const; 179 int getMaxHalBuffers() const; 180 const std::string& physicalCameraId() const; 181 int64_t getStreamUseCase() const; 182 int getTimestampBase() const; 183 bool isDeviceTimeBaseRealtime() const; 184 185 void setOfflineProcessingSupport(bool) override; 186 bool getOfflineProcessingSupport() const override; 187 asHalStream()188 camera_stream* asHalStream() override { 189 return this; 190 } 191 192 /** 193 * Start the stream configuration process. Returns a handle to the stream's 194 * information to be passed into the HAL device's configure_streams call. 195 * 196 * Until finishConfiguration() is called, no other methods on the stream may be 197 * called. The usage and max_buffers fields of camera_stream may be modified 198 * between start/finishConfiguration, but may not be changed after that. 199 * 200 * Returns NULL in case of error starting configuration. 201 */ 202 camera_stream* startConfiguration(); 203 204 /** 205 * Check if the stream is mid-configuration (start has been called, but not 206 * finish). Used for lazy completion of configuration. 207 */ 208 bool isConfiguring() const; 209 210 /** 211 * Completes the stream configuration process. The stream information 212 * structure returned by startConfiguration() may no longer be modified 213 * after this call, but can still be read until the destruction of the 214 * stream. 215 * 216 * streamReconfigured: set to true when a stream is being reconfigured. 217 * 218 * Returns: 219 * OK on a successful configuration 220 * NO_INIT in case of a serious error from the HAL device 221 * NO_MEMORY in case of an error registering buffers 222 * INVALID_OPERATION in case connecting to the consumer failed or consumer 223 * doesn't exist yet. 224 */ 225 status_t finishConfiguration(/*out*/bool* streamReconfigured = nullptr); 226 227 /** 228 * Cancels the stream configuration process. This returns the stream to the 229 * initial state, allowing it to be configured again later. 230 * This is done if the HAL rejects the proposed combined stream configuration 231 */ 232 status_t cancelConfiguration(); 233 234 /** 235 * Determine whether the stream has already become in-use (has received 236 * a valid filled buffer), which determines if a stream can still have 237 * prepareNextBuffer called on it. 238 */ 239 bool isUnpreparable(); 240 241 /** 242 * Mark the stream as unpreparable. 243 */ 244 void markUnpreparable() override; 245 246 /** 247 * Start stream preparation. May only be called in the CONFIGURED state, 248 * when no valid buffers have yet been returned to this stream. Prepares 249 * up to maxCount buffers, or the maximum number of buffers needed by the 250 * pipeline if maxCount is ALLOCATE_PIPELINE_MAX. 251 * 252 * If no prepartion is necessary, returns OK and does not transition to 253 * PREPARING state. Otherwise, returns NOT_ENOUGH_DATA and transitions 254 * to PREPARING. 255 * 256 * This call performs no allocation, so is quick to call. 257 * 258 * blockRequest specifies whether prepare will block upcoming capture 259 * request. This flag should only be set to false if the caller guarantees 260 * the whole buffer preparation process is done before capture request 261 * comes in. 262 * 263 * Returns: 264 * OK if no more buffers need to be preallocated 265 * NOT_ENOUGH_DATA if calls to prepareNextBuffer are needed to finish 266 * buffer pre-allocation, and transitions to the PREPARING state. 267 * NO_INIT in case of a serious error from the HAL device 268 * INVALID_OPERATION if called when not in CONFIGURED state, or a 269 * valid buffer has already been returned to this stream. 270 */ 271 status_t startPrepare(int maxCount, bool blockRequest); 272 273 /** 274 * Check if the request on a stream is blocked by prepare. 275 */ 276 bool isBlockedByPrepare() const; 277 278 /** 279 * Continue stream buffer preparation by allocating the next 280 * buffer for this stream. May only be called in the PREPARED state. 281 * 282 * Returns OK and transitions to the CONFIGURED state if all buffers 283 * are allocated after the call concludes. Otherwise returns NOT_ENOUGH_DATA. 284 * 285 * This call allocates one buffer, which may take several milliseconds for 286 * large buffers. 287 * 288 * Returns: 289 * OK if no more buffers need to be preallocated, and transitions 290 * to the CONFIGURED state. 291 * NOT_ENOUGH_DATA if more calls to prepareNextBuffer are needed to finish 292 * buffer pre-allocation. 293 * NO_INIT in case of a serious error from the HAL device 294 * INVALID_OPERATION if called when not in CONFIGURED state, or a 295 * valid buffer has already been returned to this stream. 296 */ 297 status_t prepareNextBuffer(); 298 299 /** 300 * Cancel stream preparation early. In case allocation needs to be 301 * stopped, this method transitions the stream back to the CONFIGURED state. 302 * Buffers that have been allocated with prepareNextBuffer remain that way, 303 * but a later use of prepareNextBuffer will require just as many 304 * calls as if the earlier prepare attempt had not existed. 305 * 306 * Returns: 307 * OK if cancellation succeeded, and transitions to the CONFIGURED state 308 * INVALID_OPERATION if not in the PREPARING state 309 * NO_INIT in case of a serious error from the HAL device 310 */ 311 status_t cancelPrepare(); 312 313 /** 314 * Tear down memory for this stream. This frees all unused gralloc buffers 315 * allocated for this stream, but leaves it ready for operation afterward. 316 * 317 * May only be called in the CONFIGURED state, and keeps the stream in 318 * the CONFIGURED state. 319 * 320 * Returns: 321 * OK if teardown succeeded. 322 * INVALID_OPERATION if not in the CONFIGURED state 323 * NO_INIT in case of a serious error from the HAL device 324 */ 325 status_t tearDown(); 326 327 /** 328 * Fill in the camera_stream_buffer with the next valid buffer for this 329 * stream, to hand over to the HAL. 330 * 331 * Multiple surfaces could share the same HAL stream, but a request may 332 * be only for a subset of surfaces. In this case, the 333 * Camera3StreamInterface object needs the surface ID information to acquire 334 * buffers for those surfaces. 335 * 336 * This method may only be called once finishConfiguration has been called. 337 * For bidirectional streams, this method applies to the output-side 338 * buffers. 339 * 340 */ 341 status_t getBuffer(camera_stream_buffer *buffer, 342 nsecs_t waitBufferTimeout, 343 const std::vector<size_t>& surface_ids = std::vector<size_t>()); 344 345 /** 346 * Return a buffer to the stream after use by the HAL. 347 * 348 * Multiple surfaces could share the same HAL stream, but a request may 349 * be only for a subset of surfaces. In this case, the 350 * Camera3StreamInterface object needs the surface ID information to attach 351 * buffers for those surfaces. 352 * 353 * This method may only be called for buffers provided by getBuffer(). 354 * For bidirectional streams, this method applies to the output-side buffers 355 */ 356 status_t returnBuffer(const camera_stream_buffer &buffer, 357 nsecs_t timestamp, nsecs_t readoutTimestamp, bool timestampIncreasing, 358 const std::vector<size_t>& surface_ids = std::vector<size_t>(), 359 uint64_t frameNumber = 0, int32_t transform = -1); 360 361 /** 362 * Fill in the camera_stream_buffer with the next valid buffer for this 363 * stream, to hand over to the HAL. 364 * 365 * This method may only be called once finishConfiguration has been called. 366 * For bidirectional streams, this method applies to the input-side 367 * buffers. 368 * 369 * This method also returns the size of the returned input buffer. 370 * 371 * Normally this call will block until the handed out buffer count is less than the stream 372 * max buffer count; if respectHalLimit is set to false, this is ignored. 373 */ 374 status_t getInputBuffer(camera_stream_buffer *buffer, 375 Size* size, bool respectHalLimit = true); 376 377 /** 378 * Return a buffer to the stream after use by the HAL. 379 * 380 * This method may only be called for buffers provided by getBuffer(). 381 * For bidirectional streams, this method applies to the input-side buffers 382 */ 383 status_t returnInputBuffer(const camera_stream_buffer &buffer); 384 385 // get the buffer producer of the input buffer queue. 386 // only apply to input streams. 387 status_t getInputBufferProducer(sp<IGraphicBufferProducer> *producer); 388 389 /** 390 * Whether any of the stream's buffers are currently in use by the HAL, 391 * including buffers that have been returned but not yet had their 392 * release fence signaled. 393 */ 394 bool hasOutstandingBuffers() const; 395 396 /** 397 * Get number of buffers currently handed out to HAL 398 */ 399 size_t getOutstandingBuffersCount() const; 400 401 enum { 402 TIMEOUT_NEVER = -1 403 }; 404 405 /** 406 * Set the status tracker to notify about idle transitions 407 */ 408 virtual status_t setStatusTracker(sp<StatusTracker> statusTracker); 409 410 /** 411 * Toggle the state of hal buffer manager 412 */ setHalBufferManager(bool)413 virtual void setHalBufferManager(bool /*enabled*/) {/* No-op */ } 414 415 /** 416 * Disconnect stream from its non-HAL endpoint. After this, 417 * start/finishConfiguration must be called before the stream can be used 418 * again. This cannot be called if the stream has outstanding dequeued 419 * buffers. 420 */ 421 status_t disconnect(); 422 423 /** 424 * Debug dump of the stream's state. 425 */ 426 virtual void dump(int fd, const Vector<String16> &args); 427 428 /** 429 * Add a camera3 buffer listener. Adding the same listener twice has 430 * no effect. 431 */ 432 void addBufferListener( 433 wp<Camera3StreamBufferListener> listener); 434 435 /** 436 * Remove a camera3 buffer listener. Removing the same listener twice 437 * or the listener that was never added has no effect. 438 */ 439 void removeBufferListener( 440 const sp<Camera3StreamBufferListener>& listener); 441 442 443 // Setting listener will remove previous listener (if exists) 444 virtual void setBufferFreedListener( 445 wp<Camera3StreamBufferFreedListener> listener) override; 446 447 /** 448 * Return if the buffer queue of the stream is abandoned. 449 */ 450 bool isAbandoned() const; 451 452 /** 453 * Switch a configured stream with possibly outstanding buffers in idle 454 * state. Configuration for such streams will be skipped assuming there 455 * are no changes to the stream parameters. 456 */ 457 status_t forceToIdle(); 458 459 /** 460 * Restore a forced idle stream to configured state, marking it active 461 * in case it contains outstanding buffers. 462 */ 463 status_t restoreConfiguredState(); 464 465 /** 466 * Notify buffer stream listeners about incoming request with particular frame number. 467 */ 468 void fireBufferRequestForFrameNumber(uint64_t frameNumber, 469 const CameraMetadata& settings) override; 470 471 protected: 472 const int mId; 473 /** 474 * Stream set id, used to indicate which group of this stream belongs to for buffer sharing 475 * across multiple streams. 476 * 477 * The default value is set to CAMERA3_STREAM_SET_ID_INVALID, which indicates that this stream 478 * doesn't intend to share buffers with any other streams, and this stream will fall back to 479 * the existing BufferQueue mechanism to manage the buffer allocations and buffer circulation. 480 * When a valid stream set id is set, this stream intends to use the Camera3BufferManager to 481 * manage the buffer allocations; the BufferQueue will only handle the buffer transaction 482 * between the producer and consumer. For this case, upon successfully registration, the streams 483 * with the same stream set id will potentially share the buffers allocated by 484 * Camera3BufferManager. 485 */ 486 const int mSetId; 487 488 const std::string mName; 489 // Zero for formats with fixed buffer size for given dimensions. 490 const size_t mMaxSize; 491 492 enum StreamState { 493 STATE_ERROR, 494 STATE_CONSTRUCTED, 495 STATE_IN_CONFIG, 496 STATE_IN_RECONFIG, 497 STATE_CONFIGURED, 498 STATE_PREPARING, 499 STATE_ABANDONED, 500 STATE_IN_IDLE 501 } mState; 502 503 mutable Mutex mLock; 504 505 Camera3Stream(int id, camera_stream_type type, 506 uint32_t width, uint32_t height, size_t maxSize, int format, 507 android_dataspace dataSpace, camera_stream_rotation_t rotation, 508 const std::string& physicalCameraId, 509 const std::unordered_set<int32_t> &sensorPixelModesUsed, 510 int setId, bool isMultiResolution, int64_t dynamicRangeProfile, 511 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase, 512 int32_t colorSpace); 513 514 wp<Camera3StreamBufferFreedListener> mBufferFreedListener; 515 516 /** 517 * Interface to be implemented by derived classes 518 */ 519 520 // getBuffer / returnBuffer implementations 521 522 // Since camera_stream_buffer includes a raw pointer to the stream, 523 // cast to camera_stream*, implementations must increment the 524 // refcount of the stream manually in getBufferLocked, and decrement it in 525 // returnBufferLocked. 526 virtual status_t getBufferLocked(camera_stream_buffer *buffer, 527 const std::vector<size_t>& surface_ids = std::vector<size_t>()); 528 virtual status_t returnBufferLocked(const camera_stream_buffer &buffer, 529 nsecs_t timestamp, nsecs_t readoutTimestamp, int32_t transform, 530 const std::vector<size_t>& surface_ids = std::vector<size_t>()); 531 532 virtual status_t getInputBufferLocked(camera_stream_buffer *buffer, Size* size); 533 534 virtual status_t returnInputBufferLocked( 535 const camera_stream_buffer &buffer); 536 virtual bool hasOutstandingBuffersLocked() const = 0; 537 // Get the buffer producer of the input buffer queue. Only apply to input streams. 538 virtual status_t getInputBufferProducerLocked(sp<IGraphicBufferProducer> *producer); 539 540 // Can return -ENOTCONN when we are already disconnected (not an error) 541 virtual status_t disconnectLocked() = 0; 542 543 // Configure the buffer queue interface to the other end of the stream, 544 // after the HAL has provided usage and max_buffers values. After this call, 545 // the stream must be ready to produce all buffers for registration with 546 // HAL. 547 // Returns NO_INIT or DEAD_OBJECT if the queue has been abandoned. 548 virtual status_t configureQueueLocked() = 0; 549 550 // Get the total number of buffers in the queue 551 virtual size_t getBufferCountLocked() = 0; 552 553 // Get handout output buffer count. 554 virtual size_t getHandoutOutputBufferCountLocked() const = 0; 555 556 // Get handout input buffer count. 557 virtual size_t getHandoutInputBufferCountLocked() = 0; 558 559 // Get cached output buffer count. 560 virtual size_t getCachedOutputBufferCountLocked() const = 0; 561 virtual size_t getMaxCachedOutputBuffersLocked() const = 0; 562 563 // Get the usage flags for the other endpoint, or return 564 // INVALID_OPERATION if they cannot be obtained. 565 virtual status_t getEndpointUsage(uint64_t *usage) = 0; 566 567 // Return whether the buffer is in the list of outstanding buffers. 568 bool isOutstandingBuffer(const camera_stream_buffer& buffer) const; 569 570 // Tracking for idle state 571 wp<StatusTracker> mStatusTracker; 572 // Status tracker component ID 573 int mStatusId; 574 575 // Tracking for stream prepare - whether this stream can still have 576 // prepareNextBuffer called on it. 577 bool mStreamUnpreparable; 578 579 uint64_t mUsage; 580 581 Condition mOutputBufferReturnedSignal; 582 583 private: 584 // Previously configured stream properties (post HAL override) 585 uint64_t mOldUsage; 586 uint32_t mOldMaxBuffers; 587 int mOldFormat; 588 android_dataspace mOldDataSpace; 589 590 Condition mInputBufferReturnedSignal; 591 static const nsecs_t kWaitForBufferDuration = 3000000000LL; // 3000 ms 592 593 void fireBufferListenersLocked(const camera_stream_buffer& buffer, 594 bool acquired, bool output, nsecs_t timestamp = 0, uint64_t frameNumber = 0); 595 List<wp<Camera3StreamBufferListener> > mBufferListenerList; 596 597 status_t cancelPrepareLocked(); 598 599 // Remove the buffer from the list of outstanding buffers. 600 void removeOutstandingBuffer(const camera_stream_buffer& buffer); 601 602 // Tracking for PREPARING state 603 604 // State of buffer preallocation. Only true if either prepareNextBuffer 605 // has been called sufficient number of times, or stream configuration 606 // had to register buffers with the HAL 607 bool mPrepared; 608 bool mPrepareBlockRequest; 609 610 Vector<camera_stream_buffer_t> mPreparedBuffers; 611 size_t mPreparedBufferIdx; 612 613 // Number of buffers allocated on last prepare call. 614 size_t mLastMaxCount; 615 616 mutable Mutex mOutstandingBuffersLock; 617 // Outstanding buffers dequeued from the stream's buffer queue. 618 List<buffer_handle_t> mOutstandingBuffers; 619 620 // Latency histogram of the wait time for handout buffer count to drop below 621 // max_buffers. 622 static const int32_t kBufferLimitLatencyBinSize = 33; //in ms 623 CameraLatencyHistogram mBufferLimitLatency; 624 625 //Keep track of original format when the stream is created in case it gets overridden 626 bool mFormatOverridden; 627 const int mOriginalFormat; 628 629 //Keep track of original dataSpace in case it gets overridden 630 bool mDataSpaceOverridden; 631 const android_dataspace mOriginalDataSpace; 632 633 std::string mPhysicalCameraId; 634 nsecs_t mLastTimestamp; 635 636 bool mIsMultiResolution = false; 637 bool mSupportOfflineProcessing = false; 638 639 bool mDeviceTimeBaseIsRealtime; 640 int mTimestampBase; 641 }; // class Camera3Stream 642 643 }; // namespace camera3 644 645 }; // namespace android 646 647 #endif 648