• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <vector>
18 #include "system/window.h"
19 #define LOG_TAG "Camera3-Stream"
20 #define ATRACE_TAG ATRACE_TAG_CAMERA
21 //#define LOG_NDEBUG 0
22 
23 #include <utils/Log.h>
24 #include <utils/Trace.h>
25 #include <camera/StringUtils.h>
26 #include "device3/Camera3Stream.h"
27 #include "device3/StatusTracker.h"
28 #include "utils/TraceHFR.h"
29 #include "ui/GraphicBufferMapper.h"
30 
31 #include <cutils/properties.h>
32 
33 namespace android {
34 
35 namespace camera3 {
36 
~Camera3Stream()37 Camera3Stream::~Camera3Stream() {
38     sp<StatusTracker> statusTracker = mStatusTracker.promote();
39     if (statusTracker != 0 && mStatusId != StatusTracker::NO_STATUS_ID) {
40         statusTracker->removeComponent(mStatusId);
41     }
42 }
43 
cast(camera_stream * stream)44 Camera3Stream* Camera3Stream::cast(camera_stream *stream) {
45     return static_cast<Camera3Stream*>(stream);
46 }
47 
cast(const camera_stream * stream)48 const Camera3Stream* Camera3Stream::cast(const camera_stream *stream) {
49     return static_cast<const Camera3Stream*>(stream);
50 }
51 
Camera3Stream(int id,camera_stream_type type,uint32_t width,uint32_t height,size_t maxSize,int format,android_dataspace dataSpace,camera_stream_rotation_t rotation,const std::string & physicalCameraId,const std::unordered_set<int32_t> & sensorPixelModesUsed,int setId,bool isMultiResolution,int64_t dynamicRangeProfile,int64_t streamUseCase,bool deviceTimeBaseIsRealtime,int timestampBase,int32_t colorSpace)52 Camera3Stream::Camera3Stream(int id,
53         camera_stream_type type,
54         uint32_t width, uint32_t height, size_t maxSize, int format,
55         android_dataspace dataSpace, camera_stream_rotation_t rotation,
56         const std::string& physicalCameraId,
57         const std::unordered_set<int32_t> &sensorPixelModesUsed,
58         int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
59         int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
60         int32_t colorSpace) :
61     camera_stream(),
62     mId(id),
63     mSetId(setId),
64     mName(fmt::sprintf("Camera3Stream[%d]", id)),
65     mMaxSize(maxSize),
66     mState(STATE_CONSTRUCTED),
67     mStatusId(StatusTracker::NO_STATUS_ID),
68     mStreamUnpreparable(true),
69     mUsage(0),
70     mOldUsage(0),
71     mOldMaxBuffers(0),
72     mOldFormat(-1),
73     mOldDataSpace(HAL_DATASPACE_UNKNOWN),
74     mPrepared(false),
75     mPrepareBlockRequest(true),
76     mPreparedBufferIdx(0),
77     mLastMaxCount(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX),
78     mBufferLimitLatency(kBufferLimitLatencyBinSize),
79     mFormatOverridden(false),
80     mOriginalFormat(format),
81     mDataSpaceOverridden(false),
82     mOriginalDataSpace(dataSpace),
83     mPhysicalCameraId(physicalCameraId),
84     mLastTimestamp(0),
85     mIsMultiResolution(isMultiResolution),
86     mDeviceTimeBaseIsRealtime(deviceTimeBaseIsRealtime),
87     mTimestampBase(timestampBase) {
88 
89     camera_stream::stream_type = type;
90     camera_stream::width = width;
91     camera_stream::height = height;
92     camera_stream::format = format;
93     camera_stream::data_space = dataSpace;
94     camera_stream::rotation = rotation;
95     camera_stream::max_buffers = 0;
96     camera_stream::physical_camera_id = mPhysicalCameraId;
97     camera_stream::sensor_pixel_modes_used = sensorPixelModesUsed;
98     camera_stream::dynamic_range_profile = dynamicRangeProfile;
99     camera_stream::use_case = streamUseCase;
100     camera_stream::color_space = colorSpace;
101 
102     if ((format == HAL_PIXEL_FORMAT_BLOB || format == HAL_PIXEL_FORMAT_RAW_OPAQUE) &&
103             maxSize == 0) {
104         ALOGE("%s: BLOB or RAW_OPAQUE format with size == 0", __FUNCTION__);
105         mState = STATE_ERROR;
106     }
107 }
108 
getId() const109 int Camera3Stream::getId() const {
110     return mId;
111 }
112 
getStreamSetId() const113 int Camera3Stream::getStreamSetId() const {
114     return mSetId;
115 }
116 
getHalStreamGroupId() const117 int Camera3Stream::getHalStreamGroupId() const {
118     return mIsMultiResolution ? mSetId : -1;
119 }
120 
isMultiResolution() const121 bool Camera3Stream::isMultiResolution() const {
122     return mIsMultiResolution;
123 }
124 
getWidth() const125 uint32_t Camera3Stream::getWidth() const {
126     return camera_stream::width;
127 }
128 
getHeight() const129 uint32_t Camera3Stream::getHeight() const {
130     return camera_stream::height;
131 }
132 
getFormat() const133 int Camera3Stream::getFormat() const {
134     return camera_stream::format;
135 }
136 
getDataSpace() const137 android_dataspace Camera3Stream::getDataSpace() const {
138     return camera_stream::data_space;
139 }
140 
getColorSpace() const141 int32_t Camera3Stream::getColorSpace() const {
142     return camera_stream::color_space;
143 }
144 
getUsage() const145 uint64_t Camera3Stream::getUsage() const {
146     return mUsage;
147 }
148 
setUsage(uint64_t usage)149 void Camera3Stream::setUsage(uint64_t usage) {
150     mUsage = usage;
151 }
152 
setFormatOverride(bool formatOverridden)153 void Camera3Stream::setFormatOverride(bool formatOverridden) {
154     mFormatOverridden = formatOverridden;
155 }
156 
isFormatOverridden() const157 bool Camera3Stream::isFormatOverridden() const {
158     return mFormatOverridden;
159 }
160 
getOriginalFormat() const161 int Camera3Stream::getOriginalFormat() const {
162     return mOriginalFormat;
163 }
164 
getDynamicRangeProfile() const165 int64_t Camera3Stream::getDynamicRangeProfile() const {
166     return camera_stream::dynamic_range_profile;
167 }
168 
setDataSpaceOverride(bool dataSpaceOverridden)169 void Camera3Stream::setDataSpaceOverride(bool dataSpaceOverridden) {
170     mDataSpaceOverridden = dataSpaceOverridden;
171 }
172 
isDataSpaceOverridden() const173 bool Camera3Stream::isDataSpaceOverridden() const {
174     return mDataSpaceOverridden;
175 }
176 
getOriginalDataSpace() const177 android_dataspace Camera3Stream::getOriginalDataSpace() const {
178     return mOriginalDataSpace;
179 }
180 
physicalCameraId() const181 const std::string& Camera3Stream::physicalCameraId() const {
182     return mPhysicalCameraId;
183 }
184 
getMaxHalBuffers() const185 int Camera3Stream::getMaxHalBuffers() const {
186     return camera_stream::max_buffers;
187 }
188 
getStreamUseCase() const189 int64_t Camera3Stream::getStreamUseCase() const {
190     return camera_stream::use_case;
191 }
192 
getTimestampBase() const193 int Camera3Stream::getTimestampBase() const {
194     return mTimestampBase;
195 }
196 
isDeviceTimeBaseRealtime() const197 bool Camera3Stream::isDeviceTimeBaseRealtime() const {
198     return mDeviceTimeBaseIsRealtime;
199 }
200 
setOfflineProcessingSupport(bool support)201 void Camera3Stream::setOfflineProcessingSupport(bool support) {
202     mSupportOfflineProcessing = support;
203 }
204 
getOfflineProcessingSupport() const205 bool Camera3Stream::getOfflineProcessingSupport() const {
206     return mSupportOfflineProcessing;
207 }
208 
forceToIdle()209 status_t Camera3Stream::forceToIdle() {
210     ATRACE_CALL();
211     Mutex::Autolock l(mLock);
212     status_t res;
213 
214     switch (mState) {
215         case STATE_ERROR:
216         case STATE_CONSTRUCTED:
217         case STATE_IN_CONFIG:
218         case STATE_PREPARING:
219         case STATE_IN_RECONFIG:
220             ALOGE("%s: Invalid state: %d", __FUNCTION__, mState);
221             res = NO_INIT;
222             break;
223         case STATE_CONFIGURED:
224             if (hasOutstandingBuffersLocked()) {
225                 sp<StatusTracker> statusTracker = mStatusTracker.promote();
226                 if (statusTracker != 0) {
227                     statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
228                 }
229             }
230 
231             mState = STATE_IN_IDLE;
232             res = OK;
233 
234             break;
235         default:
236             ALOGE("%s: Unknown state %d", __FUNCTION__, mState);
237             res = NO_INIT;
238     }
239 
240     return res;
241 }
242 
restoreConfiguredState()243 status_t Camera3Stream::restoreConfiguredState() {
244     ATRACE_CALL();
245     Mutex::Autolock l(mLock);
246     status_t res;
247 
248     switch (mState) {
249         case STATE_ERROR:
250         case STATE_CONSTRUCTED:
251         case STATE_IN_CONFIG:
252         case STATE_PREPARING:
253         case STATE_IN_RECONFIG:
254         case STATE_CONFIGURED:
255             ALOGE("%s: Invalid state: %d", __FUNCTION__, mState);
256             res = NO_INIT;
257             break;
258         case STATE_IN_IDLE:
259             if (hasOutstandingBuffersLocked()) {
260                 sp<StatusTracker> statusTracker = mStatusTracker.promote();
261                 if (statusTracker != 0) {
262                     statusTracker->markComponentActive(mStatusId);
263                 }
264             }
265 
266             mState = STATE_CONFIGURED;
267             res = OK;
268 
269             break;
270         default:
271             ALOGE("%s: Unknown state %d", __FUNCTION__, mState);
272             res = NO_INIT;
273     }
274 
275     return res;
276 }
277 
startConfiguration()278 camera_stream* Camera3Stream::startConfiguration() {
279     ATRACE_CALL();
280     Mutex::Autolock l(mLock);
281     status_t res;
282 
283     switch (mState) {
284         case STATE_ERROR:
285             ALOGE("%s: In error state", __FUNCTION__);
286             return NULL;
287         case STATE_CONSTRUCTED:
288         case STATE_IN_IDLE:
289             // OK
290             break;
291         case STATE_IN_CONFIG:
292         case STATE_IN_RECONFIG:
293             // Can start config again with no trouble; but don't redo
294             // mOldUsage/mOldMaxBuffers
295             return this;
296         case STATE_CONFIGURED:
297             if (hasOutstandingBuffersLocked()) {
298                 ALOGE("%s: Cannot configure stream; has outstanding buffers",
299                         __FUNCTION__);
300                 return NULL;
301             }
302             break;
303         default:
304             ALOGE("%s: Unknown state %d", __FUNCTION__, mState);
305             return NULL;
306     }
307 
308     mOldUsage = mUsage;
309     mOldMaxBuffers = camera_stream::max_buffers;
310     mOldFormat = camera_stream::format;
311     mOldDataSpace = camera_stream::data_space;
312 
313     res = getEndpointUsage(&mUsage);
314     if (res != OK) {
315         ALOGE("%s: Cannot query consumer endpoint usage!",
316                 __FUNCTION__);
317         return NULL;
318     }
319 
320     if (mState == STATE_IN_IDLE) {
321         // Skip configuration.
322         return this;
323     }
324 
325     // Stop tracking if currently doing so
326     if (mStatusId != StatusTracker::NO_STATUS_ID) {
327         sp<StatusTracker> statusTracker = mStatusTracker.promote();
328         if (statusTracker != 0) {
329             statusTracker->removeComponent(mStatusId);
330         }
331         mStatusId = StatusTracker::NO_STATUS_ID;
332     }
333 
334     if (mState == STATE_CONSTRUCTED) {
335         mState = STATE_IN_CONFIG;
336     } else { // mState == STATE_CONFIGURED
337         LOG_ALWAYS_FATAL_IF(mState != STATE_CONFIGURED, "Invalid state: 0x%x", mState);
338         mState = STATE_IN_RECONFIG;
339     }
340 
341     return this;
342 }
343 
isConfiguring() const344 bool Camera3Stream::isConfiguring() const {
345     Mutex::Autolock l(mLock);
346     return (mState == STATE_IN_CONFIG) || (mState == STATE_IN_RECONFIG);
347 }
348 
finishConfiguration(bool * streamReconfigured)349 status_t Camera3Stream::finishConfiguration(/*out*/bool* streamReconfigured) {
350     ATRACE_CALL();
351     if (streamReconfigured != nullptr) {
352         *streamReconfigured = false;
353     }
354     Mutex::Autolock l(mLock);
355     switch (mState) {
356         case STATE_ERROR:
357             ALOGE("%s: In error state", __FUNCTION__);
358             return INVALID_OPERATION;
359         case STATE_IN_CONFIG:
360         case STATE_IN_RECONFIG:
361             // OK
362             break;
363         case STATE_CONSTRUCTED:
364         case STATE_CONFIGURED:
365             ALOGE("%s: Cannot finish configuration that hasn't been started",
366                     __FUNCTION__);
367             return INVALID_OPERATION;
368         case STATE_IN_IDLE:
369             //Skip configuration in this state
370             return OK;
371         default:
372             ALOGE("%s: Unknown state", __FUNCTION__);
373             return INVALID_OPERATION;
374     }
375 
376     // Register for idle tracking
377     sp<StatusTracker> statusTracker = mStatusTracker.promote();
378     if (statusTracker != 0 && mStatusId == StatusTracker::NO_STATUS_ID) {
379         std::string name = std::string("Stream ") + std::to_string(mId);
380         mStatusId = statusTracker->addComponent(name);
381     }
382 
383     // Check if the stream configuration is unchanged, and skip reallocation if
384     // so.
385     if (mState == STATE_IN_RECONFIG &&
386             mOldUsage == mUsage &&
387             mOldMaxBuffers == camera_stream::max_buffers &&
388             mOldDataSpace == camera_stream::data_space &&
389             mOldFormat == camera_stream::format) {
390         mState = STATE_CONFIGURED;
391         return OK;
392     }
393 
394     // Reset prepared state, since buffer config has changed, and existing
395     // allocations are no longer valid
396     mPrepared = false;
397     mPrepareBlockRequest = true;
398     mStreamUnpreparable = false;
399 
400     bool reconfiguring = (mState == STATE_IN_RECONFIG);
401     status_t res;
402     res = configureQueueLocked();
403     // configureQueueLocked could return error in case of abandoned surface.
404     // Treat as non-fatal error.
405     if (res == NO_INIT || res == DEAD_OBJECT) {
406         ALOGE("%s: Unable to configure stream %d queue (non-fatal): %s (%d)",
407                 __FUNCTION__, mId, strerror(-res), res);
408         mState = STATE_ABANDONED;
409         return res;
410     } else if (res != OK) {
411         ALOGE("%s: Unable to configure stream %d queue: %s (%d)",
412                 __FUNCTION__, mId, strerror(-res), res);
413         mState = STATE_ERROR;
414         return res;
415     }
416 
417     if (reconfiguring && streamReconfigured != nullptr) {
418         *streamReconfigured = true;
419     }
420     mState = STATE_CONFIGURED;
421 
422     return res;
423 }
424 
cancelConfiguration()425 status_t Camera3Stream::cancelConfiguration() {
426     ATRACE_CALL();
427     Mutex::Autolock l(mLock);
428     switch (mState) {
429         case STATE_ERROR:
430             ALOGE("%s: In error state", __FUNCTION__);
431             return INVALID_OPERATION;
432         case STATE_IN_CONFIG:
433         case STATE_IN_RECONFIG:
434         case STATE_IN_IDLE:
435             // OK
436             break;
437         case STATE_CONSTRUCTED:
438         case STATE_CONFIGURED:
439             ALOGE("%s: Cannot cancel configuration that hasn't been started",
440                     __FUNCTION__);
441             return INVALID_OPERATION;
442         default:
443             ALOGE("%s: Unknown state", __FUNCTION__);
444             return INVALID_OPERATION;
445     }
446 
447     mUsage = mOldUsage;
448     camera_stream::max_buffers = mOldMaxBuffers;
449 
450     mState = ((mState == STATE_IN_RECONFIG) || (mState == STATE_IN_IDLE)) ? STATE_CONFIGURED :
451             STATE_CONSTRUCTED;
452 
453     return OK;
454 }
455 
isUnpreparable()456 bool Camera3Stream::isUnpreparable() {
457     ATRACE_CALL();
458 
459     Mutex::Autolock l(mLock);
460     return mStreamUnpreparable;
461 }
462 
markUnpreparable()463 void Camera3Stream::markUnpreparable() {
464     ATRACE_CALL();
465 
466     Mutex::Autolock l(mLock);
467     mStreamUnpreparable = true;
468 }
469 
startPrepare(int maxCount,bool blockRequest)470 status_t Camera3Stream::startPrepare(int maxCount, bool blockRequest) {
471     ATRACE_CALL();
472 
473     Mutex::Autolock l(mLock);
474 
475     if (maxCount < 0) {
476         ALOGE("%s: Stream %d: Can't prepare stream if max buffer count (%d) is < 0",
477                 __FUNCTION__, mId, maxCount);
478         return BAD_VALUE;
479     }
480 
481     // This function should be only called when the stream is configured already.
482     if (mState != STATE_CONFIGURED) {
483         ALOGE("%s: Stream %d: Can't prepare stream if stream is not in CONFIGURED "
484                 "state %d", __FUNCTION__, mId, mState);
485         return INVALID_OPERATION;
486     }
487 
488     // This function can't be called if the stream has already received filled
489     // buffers
490     if (mStreamUnpreparable) {
491         ALOGE("%s: Stream %d: Can't prepare stream that's already in use",
492                 __FUNCTION__, mId);
493         return INVALID_OPERATION;
494     }
495 
496     if (getHandoutOutputBufferCountLocked() > 0) {
497         ALOGE("%s: Stream %d: Can't prepare stream that has outstanding buffers",
498                 __FUNCTION__, mId);
499         return INVALID_OPERATION;
500     }
501 
502     size_t pipelineMax = getBufferCountLocked();
503     size_t clampedCount = (pipelineMax < static_cast<size_t>(maxCount)) ?
504             pipelineMax : static_cast<size_t>(maxCount);
505     size_t bufferCount = (maxCount == Camera3StreamInterface::ALLOCATE_PIPELINE_MAX) ?
506             pipelineMax : clampedCount;
507 
508     mPrepared = bufferCount <= mLastMaxCount;
509     mPrepareBlockRequest = blockRequest;
510 
511     if (mPrepared) return OK;
512 
513     mLastMaxCount = bufferCount;
514 
515     mPreparedBuffers.insertAt(camera_stream_buffer_t(), /*index*/0, bufferCount);
516     mPreparedBufferIdx = 0;
517 
518     mState = STATE_PREPARING;
519 
520     return NOT_ENOUGH_DATA;
521 }
522 
isBlockedByPrepare() const523 bool Camera3Stream::isBlockedByPrepare() const {
524     Mutex::Autolock l(mLock);
525     return mState == STATE_PREPARING && mPrepareBlockRequest;
526 }
527 
isAbandoned() const528 bool Camera3Stream::isAbandoned() const {
529     Mutex::Autolock l(mLock);
530     return mState == STATE_ABANDONED;
531 }
532 
prepareNextBuffer()533 status_t Camera3Stream::prepareNextBuffer() {
534     ATRACE_CALL();
535 
536     Mutex::Autolock l(mLock);
537     status_t res = OK;
538 
539     // This function should be only called when the stream is preparing
540     if (mState != STATE_PREPARING) {
541         ALOGE("%s: Stream %d: Can't prepare buffer if stream is not in PREPARING "
542                 "state %d", __FUNCTION__, mId, mState);
543         return INVALID_OPERATION;
544     }
545 
546     // Get next buffer - this may allocate, and take a while for large buffers
547     res = getBufferLocked( &mPreparedBuffers.editItemAt(mPreparedBufferIdx) );
548     if (res != OK) {
549         ALOGE("%s: Stream %d: Unable to allocate buffer %zu during preparation",
550                 __FUNCTION__, mId, mPreparedBufferIdx);
551         return NO_INIT;
552     }
553 
554     mPreparedBufferIdx++;
555 
556     // Check if we still have buffers left to allocate
557     if (mPreparedBufferIdx < mPreparedBuffers.size()) {
558         return NOT_ENOUGH_DATA;
559     }
560 
561     // Done with prepare - mark stream as such, and return all buffers
562     // via cancelPrepare
563     mPrepared = true;
564 
565     return cancelPrepareLocked();
566 }
567 
cancelPrepare()568 status_t Camera3Stream::cancelPrepare() {
569     ATRACE_CALL();
570 
571     Mutex::Autolock l(mLock);
572 
573     return cancelPrepareLocked();
574 }
575 
cancelPrepareLocked()576 status_t Camera3Stream::cancelPrepareLocked() {
577     status_t res = OK;
578 
579     // This function should be only called when the stream is mid-preparing.
580     if (mState != STATE_PREPARING) {
581         ALOGE("%s: Stream %d: Can't cancel prepare stream if stream is not in "
582                 "PREPARING state %d", __FUNCTION__, mId, mState);
583         return INVALID_OPERATION;
584     }
585 
586     // Return all valid buffers to stream, in ERROR state to indicate
587     // they weren't filled.
588     for (size_t i = 0; i < mPreparedBufferIdx; i++) {
589         mPreparedBuffers.editItemAt(i).release_fence = -1;
590         mPreparedBuffers.editItemAt(i).status = CAMERA_BUFFER_STATUS_ERROR;
591         returnBufferLocked(mPreparedBuffers[i], /*timestamp*/0, /*readoutTimestamp*/0,
592                 /*transform*/ -1);
593     }
594     mPreparedBuffers.clear();
595     mPreparedBufferIdx = 0;
596 
597     mState = STATE_CONFIGURED;
598 
599     return res;
600 }
601 
tearDown()602 status_t Camera3Stream::tearDown() {
603     ATRACE_CALL();
604     Mutex::Autolock l(mLock);
605 
606     status_t res = OK;
607 
608     // This function should be only called when the stream is configured.
609     if (mState != STATE_CONFIGURED) {
610         ALOGE("%s: Stream %d: Can't tear down stream if stream is not in "
611                 "CONFIGURED state %d", __FUNCTION__, mId, mState);
612         return INVALID_OPERATION;
613     }
614 
615     // If any buffers have been handed to the HAL, the stream cannot be torn down.
616     if (getHandoutOutputBufferCountLocked() > 0) {
617         ALOGE("%s: Stream %d: Can't tear down a stream that has outstanding buffers",
618                 __FUNCTION__, mId);
619         return INVALID_OPERATION;
620     }
621 
622     // Free buffers by disconnecting and then reconnecting to the buffer queue
623     // Only unused buffers will be dropped immediately; buffers that have been filled
624     // and are waiting to be acquired by the consumer and buffers that are currently
625     // acquired will be freed once they are released by the consumer.
626 
627     res = disconnectLocked();
628     if (res != OK) {
629         if (res == -ENOTCONN) {
630             // queue has been disconnected, nothing left to do, so exit with success
631             return OK;
632         }
633         ALOGE("%s: Stream %d: Unable to disconnect to tear down buffers: %s (%d)",
634                 __FUNCTION__, mId, strerror(-res), res);
635         return res;
636     }
637 
638     mState = STATE_IN_CONFIG;
639 
640     res = configureQueueLocked();
641     if (res != OK) {
642         ALOGE("%s: Unable to configure stream %d queue: %s (%d)",
643                 __FUNCTION__, mId, strerror(-res), res);
644         mState = STATE_ERROR;
645         return res;
646     }
647 
648     // Reset prepared state, since we've reconnected to the queue and can prepare again.
649     mPrepared = false;
650     mStreamUnpreparable = false;
651 
652     mState = STATE_CONFIGURED;
653 
654     return OK;
655 }
656 
getBuffer(camera_stream_buffer * buffer,nsecs_t waitBufferTimeout,const std::vector<size_t> & surface_ids)657 status_t Camera3Stream::getBuffer(camera_stream_buffer *buffer,
658         nsecs_t waitBufferTimeout,
659         const std::vector<size_t>& surface_ids) {
660     ATRACE_HFR_CALL();
661     Mutex::Autolock l(mLock);
662     status_t res = OK;
663 
664     // This function should be only called when the stream is configured already.
665     if (mState != STATE_CONFIGURED) {
666         ALOGE("%s: Stream %d: Can't get buffers if stream is not in CONFIGURED state %d",
667                 __FUNCTION__, mId, mState);
668         if (mState == STATE_ABANDONED) {
669             return DEAD_OBJECT;
670         } else {
671             return INVALID_OPERATION;
672         }
673     }
674 
675     // Wait for new buffer returned back if we are running into the limit. There
676     // are 2 limits:
677     // 1. The number of HAL buffers is greater than max_buffers
678     // 2. The number of HAL buffers + cached buffers is greater than max_buffers
679     //    + maxCachedBuffers
680     size_t numOutstandingBuffers = getHandoutOutputBufferCountLocked();
681     size_t numCachedBuffers = getCachedOutputBufferCountLocked();
682     size_t maxNumCachedBuffers = getMaxCachedOutputBuffersLocked();
683     while (numOutstandingBuffers == camera_stream::max_buffers ||
684             numOutstandingBuffers + numCachedBuffers ==
685             camera_stream::max_buffers + maxNumCachedBuffers) {
686         ALOGV("%s: Already dequeued max output buffers (%d(+%zu)), wait for next returned one.",
687                         __FUNCTION__, camera_stream::max_buffers, maxNumCachedBuffers);
688         nsecs_t waitStart = systemTime(SYSTEM_TIME_MONOTONIC);
689         if (waitBufferTimeout < kWaitForBufferDuration) {
690             waitBufferTimeout = kWaitForBufferDuration;
691         }
692         res = mOutputBufferReturnedSignal.waitRelative(mLock, waitBufferTimeout);
693         nsecs_t waitEnd = systemTime(SYSTEM_TIME_MONOTONIC);
694         mBufferLimitLatency.add(waitStart, waitEnd);
695         if (res != OK) {
696             if (res == TIMED_OUT) {
697                 ALOGE("%s: wait for output buffer return timed out after %lldms (max_buffers %d)",
698                         __FUNCTION__, waitBufferTimeout / 1000000LL,
699                         camera_stream::max_buffers);
700             }
701             return res;
702         }
703 
704         size_t updatedNumOutstandingBuffers = getHandoutOutputBufferCountLocked();
705         size_t updatedNumCachedBuffers = getCachedOutputBufferCountLocked();
706         if (updatedNumOutstandingBuffers >= numOutstandingBuffers &&
707                 updatedNumCachedBuffers == numCachedBuffers) {
708             ALOGE("%s: outstanding buffer count goes from %zu to %zu, "
709                     "getBuffer(s) call must not run in parallel!", __FUNCTION__,
710                     numOutstandingBuffers, updatedNumOutstandingBuffers);
711             return INVALID_OPERATION;
712         }
713         numOutstandingBuffers = updatedNumOutstandingBuffers;
714         numCachedBuffers = updatedNumCachedBuffers;
715     }
716 
717     res = getBufferLocked(buffer, surface_ids);
718     if (res == OK) {
719         fireBufferListenersLocked(*buffer, /*acquired*/true, /*output*/true);
720         if (buffer->buffer) {
721             Mutex::Autolock l(mOutstandingBuffersLock);
722             mOutstandingBuffers.push_back(*buffer->buffer);
723         }
724     }
725 
726     return res;
727 }
728 
isOutstandingBuffer(const camera_stream_buffer & buffer) const729 bool Camera3Stream::isOutstandingBuffer(const camera_stream_buffer &buffer) const{
730     if (buffer.buffer == nullptr) {
731         return false;
732     }
733 
734     Mutex::Autolock l(mOutstandingBuffersLock);
735 
736     for (auto b : mOutstandingBuffers) {
737         if (b == *buffer.buffer) {
738             return true;
739         }
740     }
741     return false;
742 }
743 
removeOutstandingBuffer(const camera_stream_buffer & buffer)744 void Camera3Stream::removeOutstandingBuffer(const camera_stream_buffer &buffer) {
745     if (buffer.buffer == nullptr) {
746         return;
747     }
748 
749     Mutex::Autolock l(mOutstandingBuffersLock);
750 
751     for (auto b = mOutstandingBuffers.begin(); b != mOutstandingBuffers.end(); b++) {
752         if (*b == *buffer.buffer) {
753             mOutstandingBuffers.erase(b);
754             return;
755         }
756     }
757 }
758 
returnBuffer(const camera_stream_buffer & buffer,nsecs_t timestamp,nsecs_t readoutTimestamp,bool timestampIncreasing,const std::vector<size_t> & surface_ids,uint64_t frameNumber,int32_t transform)759 status_t Camera3Stream::returnBuffer(const camera_stream_buffer &buffer,
760         nsecs_t timestamp, nsecs_t readoutTimestamp, bool timestampIncreasing,
761          const std::vector<size_t>& surface_ids, uint64_t frameNumber, int32_t transform) {
762     ATRACE_HFR_CALL();
763     Mutex::Autolock l(mLock);
764 
765     // Check if this buffer is outstanding.
766     if (!isOutstandingBuffer(buffer)) {
767         ALOGE("%s: Stream %d: Returning an unknown buffer.", __FUNCTION__, mId);
768         return BAD_VALUE;
769     }
770 
771     removeOutstandingBuffer(buffer);
772 
773     // Buffer status may be changed, so make a copy of the stream_buffer struct.
774     camera_stream_buffer b = buffer;
775     if (timestampIncreasing && timestamp != 0 && timestamp <= mLastTimestamp
776             && b.status != CAMERA_BUFFER_STATUS_ERROR) {
777         ALOGE("%s: Stream %d: timestamp %" PRId64 " is not increasing. Prev timestamp %" PRId64,
778                 __FUNCTION__, mId, timestamp, mLastTimestamp);
779         b.status = CAMERA_BUFFER_STATUS_ERROR;
780     }
781     mLastTimestamp = timestamp;
782 
783     /**
784      * TODO: Check that the state is valid first.
785      *
786      * <HAL3.2 IN_CONFIG and IN_RECONFIG in addition to CONFIGURED.
787      * >= HAL3.2 CONFIGURED only
788      *
789      * Do this for getBuffer as well.
790      */
791     status_t res = returnBufferLocked(b, timestamp, readoutTimestamp, transform, surface_ids);
792     if (res == OK) {
793         fireBufferListenersLocked(b, /*acquired*/false, /*output*/true, timestamp, frameNumber);
794     }
795 
796     // Even if returning the buffer failed, we still want to signal whoever is waiting for the
797     // buffer to be returned.
798     mOutputBufferReturnedSignal.signal();
799 
800     return res;
801 }
802 
getInputBuffer(camera_stream_buffer * buffer,Size * size,bool respectHalLimit)803 status_t Camera3Stream::getInputBuffer(camera_stream_buffer *buffer,
804         Size* size, bool respectHalLimit) {
805     ATRACE_CALL();
806     Mutex::Autolock l(mLock);
807     status_t res = OK;
808 
809     if (size == nullptr) {
810         ALOGE("%s: size must not be null", __FUNCTION__);
811         return BAD_VALUE;
812     }
813     // This function should be only called when the stream is configured already.
814     if (mState != STATE_CONFIGURED) {
815         ALOGE("%s: Stream %d: Can't get input buffers if stream is not in CONFIGURED state %d",
816                 __FUNCTION__, mId, mState);
817         return INVALID_OPERATION;
818     }
819 
820     // Wait for new buffer returned back if we are running into the limit.
821     if (getHandoutInputBufferCountLocked() == camera_stream::max_buffers && respectHalLimit) {
822         ALOGV("%s: Already dequeued max input buffers (%d), wait for next returned one.",
823                 __FUNCTION__, camera_stream::max_buffers);
824         res = mInputBufferReturnedSignal.waitRelative(mLock, kWaitForBufferDuration);
825         if (res != OK) {
826             if (res == TIMED_OUT) {
827                 ALOGE("%s: wait for input buffer return timed out after %lldms", __FUNCTION__,
828                         kWaitForBufferDuration / 1000000LL);
829             }
830             return res;
831         }
832     }
833 
834     res = getInputBufferLocked(buffer, size);
835     if (res == OK) {
836         fireBufferListenersLocked(*buffer, /*acquired*/true, /*output*/false);
837         if (buffer->buffer) {
838             Mutex::Autolock l(mOutstandingBuffersLock);
839             mOutstandingBuffers.push_back(*buffer->buffer);
840         }
841     }
842 
843     return res;
844 }
845 
returnInputBuffer(const camera_stream_buffer & buffer)846 status_t Camera3Stream::returnInputBuffer(const camera_stream_buffer &buffer) {
847     ATRACE_CALL();
848     Mutex::Autolock l(mLock);
849 
850     // Check if this buffer is outstanding.
851     if (!isOutstandingBuffer(buffer)) {
852         ALOGE("%s: Stream %d: Returning an unknown buffer.", __FUNCTION__, mId);
853         return BAD_VALUE;
854     }
855 
856     removeOutstandingBuffer(buffer);
857 
858     status_t res = returnInputBufferLocked(buffer);
859     if (res == OK) {
860         fireBufferListenersLocked(buffer, /*acquired*/false, /*output*/false);
861         mInputBufferReturnedSignal.signal();
862     }
863 
864     return res;
865 }
866 
getInputBufferProducer(sp<IGraphicBufferProducer> * producer)867 status_t Camera3Stream::getInputBufferProducer(sp<IGraphicBufferProducer> *producer) {
868     ATRACE_CALL();
869     Mutex::Autolock l(mLock);
870 
871     return getInputBufferProducerLocked(producer);
872 }
873 
fireBufferRequestForFrameNumber(uint64_t frameNumber,const CameraMetadata & settings)874 void Camera3Stream::fireBufferRequestForFrameNumber(uint64_t frameNumber,
875         const CameraMetadata& settings) {
876     ATRACE_CALL();
877     Mutex::Autolock l(mLock);
878 
879     for (auto &it : mBufferListenerList) {
880         sp<Camera3StreamBufferListener> listener = it.promote();
881         if (listener.get() != nullptr) {
882             listener->onBufferRequestForFrameNumber(frameNumber, getId(), settings);
883         }
884     }
885 }
886 
fireBufferListenersLocked(const camera_stream_buffer & buffer,bool acquired,bool output,nsecs_t timestamp,uint64_t frameNumber)887 void Camera3Stream::fireBufferListenersLocked(
888         const camera_stream_buffer& buffer, bool acquired, bool output, nsecs_t timestamp,
889         uint64_t frameNumber) {
890     List<wp<Camera3StreamBufferListener> >::iterator it, end;
891 
892     // TODO: finish implementing
893 
894     Camera3StreamBufferListener::BufferInfo info =
895         Camera3StreamBufferListener::BufferInfo();
896     info.mOutput = output;
897     info.mError = (buffer.status == CAMERA_BUFFER_STATUS_ERROR);
898     info.mFrameNumber = frameNumber;
899     info.mTimestamp = timestamp;
900     info.mStreamId = getId();
901 
902     // TODO: rest of fields
903 
904     for (it = mBufferListenerList.begin(), end = mBufferListenerList.end();
905          it != end;
906          ++it) {
907 
908         sp<Camera3StreamBufferListener> listener = it->promote();
909         if (listener != 0) {
910             if (acquired) {
911                 listener->onBufferAcquired(info);
912             } else {
913                 listener->onBufferReleased(info);
914             }
915         }
916     }
917 }
918 
hasOutstandingBuffers() const919 bool Camera3Stream::hasOutstandingBuffers() const {
920     ATRACE_CALL();
921     Mutex::Autolock l(mLock);
922     return hasOutstandingBuffersLocked();
923 }
924 
getOutstandingBuffersCount() const925 size_t Camera3Stream::getOutstandingBuffersCount() const {
926     ATRACE_CALL();
927     Mutex::Autolock l(mLock);
928     return getHandoutOutputBufferCountLocked();
929 }
930 
setStatusTracker(sp<StatusTracker> statusTracker)931 status_t Camera3Stream::setStatusTracker(sp<StatusTracker> statusTracker) {
932     Mutex::Autolock l(mLock);
933     sp<StatusTracker> oldTracker = mStatusTracker.promote();
934     if (oldTracker != 0 && mStatusId != StatusTracker::NO_STATUS_ID) {
935         oldTracker->removeComponent(mStatusId);
936     }
937     mStatusId = StatusTracker::NO_STATUS_ID;
938     mStatusTracker = statusTracker;
939 
940     return OK;
941 }
942 
disconnect()943 status_t Camera3Stream::disconnect() {
944     ATRACE_CALL();
945     Mutex::Autolock l(mLock);
946     ALOGV("%s: Stream %d: Disconnecting...", __FUNCTION__, mId);
947     status_t res = disconnectLocked();
948 
949     mBufferLimitLatency.log("Stream %d latency histogram for wait on max_buffers", mId);
950     mBufferLimitLatency.reset();
951 
952     if (res == -ENOTCONN) {
953         // "Already disconnected" -- not an error
954         return OK;
955     } else {
956         return res;
957     }
958 }
959 
dump(int fd,const Vector<String16> & args)960 void Camera3Stream::dump(int fd, [[maybe_unused]] const Vector<String16> &args)
961 {
962     mBufferLimitLatency.dump(fd,
963             "      Latency histogram for wait on max_buffers");
964 }
965 
getBufferLocked(camera_stream_buffer *,const std::vector<size_t> &)966 status_t Camera3Stream::getBufferLocked(camera_stream_buffer *,
967         const std::vector<size_t>&) {
968     ALOGE("%s: This type of stream does not support output", __FUNCTION__);
969     return INVALID_OPERATION;
970 }
971 
returnBufferLocked(const camera_stream_buffer &,nsecs_t,nsecs_t,int32_t,const std::vector<size_t> &)972 status_t Camera3Stream::returnBufferLocked(const camera_stream_buffer &,
973                                            nsecs_t, nsecs_t, int32_t, const std::vector<size_t>&) {
974     ALOGE("%s: This type of stream does not support output", __FUNCTION__);
975     return INVALID_OPERATION;
976 }
getInputBufferLocked(camera_stream_buffer *,Size *)977 status_t Camera3Stream::getInputBufferLocked(camera_stream_buffer *, Size *) {
978     ALOGE("%s: This type of stream does not support input", __FUNCTION__);
979     return INVALID_OPERATION;
980 }
returnInputBufferLocked(const camera_stream_buffer &)981 status_t Camera3Stream::returnInputBufferLocked(
982         const camera_stream_buffer &) {
983     ALOGE("%s: This type of stream does not support input", __FUNCTION__);
984     return INVALID_OPERATION;
985 }
getInputBufferProducerLocked(sp<IGraphicBufferProducer> *)986 status_t Camera3Stream::getInputBufferProducerLocked(sp<IGraphicBufferProducer>*) {
987     ALOGE("%s: This type of stream does not support input", __FUNCTION__);
988     return INVALID_OPERATION;
989 }
990 
addBufferListener(wp<Camera3StreamBufferListener> listener)991 void Camera3Stream::addBufferListener(
992         wp<Camera3StreamBufferListener> listener) {
993     Mutex::Autolock l(mLock);
994 
995     List<wp<Camera3StreamBufferListener> >::iterator it, end;
996     for (it = mBufferListenerList.begin(), end = mBufferListenerList.end();
997          it != end;
998          ) {
999         if (*it == listener) {
1000             ALOGE("%s: Try to add the same listener twice, ignoring...", __FUNCTION__);
1001             return;
1002         }
1003         it++;
1004     }
1005 
1006     mBufferListenerList.push_back(listener);
1007 }
1008 
removeBufferListener(const sp<Camera3StreamBufferListener> & listener)1009 void Camera3Stream::removeBufferListener(
1010         const sp<Camera3StreamBufferListener>& listener) {
1011     Mutex::Autolock l(mLock);
1012 
1013     bool erased = true;
1014     List<wp<Camera3StreamBufferListener> >::iterator it, end;
1015     for (it = mBufferListenerList.begin(), end = mBufferListenerList.end();
1016          it != end;
1017          ) {
1018 
1019         if (*it == listener) {
1020             it = mBufferListenerList.erase(it);
1021             erased = true;
1022         } else {
1023             ++it;
1024         }
1025     }
1026 
1027     if (!erased) {
1028         ALOGW("%s: Could not find listener to remove, already removed",
1029               __FUNCTION__);
1030     }
1031 }
1032 
setBufferFreedListener(wp<Camera3StreamBufferFreedListener> listener)1033 void Camera3Stream::setBufferFreedListener(
1034         wp<Camera3StreamBufferFreedListener> listener) {
1035     Mutex::Autolock l(mLock);
1036     // Only allow set listener during stream configuration because stream is guaranteed to be IDLE
1037     // at this state, so setBufferFreedListener won't collide with onBufferFreed callbacks
1038     if (mState != STATE_IN_CONFIG && mState != STATE_IN_RECONFIG) {
1039         ALOGE("%s: listener must be set during stream configuration!",__FUNCTION__);
1040         return;
1041     }
1042     mBufferFreedListener = listener;
1043 }
1044 
queueHDRMetadata(buffer_handle_t buffer,sp<ANativeWindow> & anw,int64_t dynamicRangeProfile)1045 void Camera3Stream::queueHDRMetadata(buffer_handle_t buffer, sp<ANativeWindow>& anw,
1046         int64_t dynamicRangeProfile) {
1047     auto& mapper = GraphicBufferMapper::get();
1048     switch (dynamicRangeProfile) {
1049         case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10: {
1050             std::optional<ui::Smpte2086> smpte2086;
1051             auto res = mapper.getSmpte2086(buffer, &smpte2086);
1052             if ((res == OK) && smpte2086.has_value()) {
1053                 const auto& metaValue = smpte2086.value();
1054                 android_smpte2086_metadata meta = {
1055                     .displayPrimaryRed.x = metaValue.primaryRed.x,
1056                     .displayPrimaryRed.y = metaValue.primaryRed.y,
1057                     .displayPrimaryGreen.x = metaValue.primaryGreen.x,
1058                     .displayPrimaryGreen.y = metaValue.primaryGreen.y,
1059                     .displayPrimaryBlue.x = metaValue.primaryBlue.x,
1060                     .displayPrimaryBlue.y = metaValue.primaryBlue.y,
1061                     .whitePoint.x = metaValue.whitePoint.x,
1062                     .whitePoint.y = metaValue.whitePoint.y,
1063                     .maxLuminance = metaValue.maxLuminance,
1064                     .minLuminance = metaValue.minLuminance};
1065                 native_window_set_buffers_smpte2086_metadata(anw.get(), &meta);
1066             } else {
1067                 ALOGE("%s Couldn't retrieve Smpte2086 metadata %s (%d)",
1068                         __FUNCTION__, strerror(-res), res);
1069             }
1070             break;
1071         }
1072         case ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_HDR10_PLUS: {
1073             std::optional<std::vector<uint8_t>> smpte2094_40;
1074             auto res = mapper.getSmpte2094_40(buffer, &smpte2094_40);
1075             if ((res == OK) && smpte2094_40.has_value()) {
1076                 native_window_set_buffers_hdr10_plus_metadata(anw.get(),
1077                         smpte2094_40.value().size(), smpte2094_40.value().data());
1078             } else {
1079                 ALOGE("%s Couldn't retrieve Smpte2094_40 metadata %s (%d)",
1080                         __FUNCTION__, strerror(-res), res);
1081             }
1082             break;
1083         }
1084         default:
1085             // No-op
1086             break;
1087     }
1088 }
1089 
1090 
1091 }; // namespace camera3
1092 
1093 }; // namespace android
1094