blob: 7185895bb88ea271982227ca5ea79c00a086a433 [file] [log] [blame]
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08003 *
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#define LOG_TAG "Camera3-OutputStream"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20
Shuzhen Wang34a5e282022-06-17 14:48:35 -070021#include <algorithm>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080022#include <ctime>
23#include <fstream>
24
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000025#include <aidl/android/hardware/camera/device/CameraBlob.h>
26#include <aidl/android/hardware/camera/device/CameraBlobId.h>
Emilian Peeve579d8b2023-02-28 14:16:08 -080027#include "aidl/android/hardware/graphics/common/Dataspace.h"
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000028
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080029#include <android-base/unique_fd.h>
Shuzhen Wange4adddb2021-09-21 15:24:44 -070030#include <cutils/properties.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080031#include <ui/GraphicBuffer.h>
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080032#include <utils/Log.h>
33#include <utils/Trace.h>
Austin Borger1c1bee02023-06-01 16:51:35 -070034#include <camera/StringUtils.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080035
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000036#include <common/CameraDeviceBase.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080037#include "api1/client2/JpegProcessor.h"
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080038#include "Camera3OutputStream.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070039#include "utils/TraceHFR.h"
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080040
41#ifndef container_of
42#define container_of(ptr, type, member) \
43 (type *)((char*)(ptr) - offsetof(type, member))
44#endif
45
46namespace android {
47
48namespace camera3 {
49
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000050using aidl::android::hardware::camera::device::CameraBlob;
51using aidl::android::hardware::camera::device::CameraBlobId;
52
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080053Camera3OutputStream::Camera3OutputStream(int id,
Eino-Ville Talvala727d1722015-06-09 13:44:19 -070054 sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -080055 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -070056 android_dataspace dataSpace, camera_stream_rotation_t rotation,
Austin Borger1c1bee02023-06-01 16:51:35 -070057 nsecs_t timestampOffset, const std::string& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000058 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -080059 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -080060 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +000061 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -070062 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -080063 /*maxSize*/0, format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -080064 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -080065 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -070066 timestampBase, colorSpace),
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080067 mConsumer(consumer),
Ruchit Sharmae0711f22014-08-18 13:48:24 -040068 mTransform(0),
Zhijun He125684a2015-12-26 15:07:30 -080069 mTraceFirstBuffer(true),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080070 mUseBufferManager(false),
Zhijun He5d677d12016-05-29 16:52:39 -070071 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +000072 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -070073 mConsumerUsage(0),
Chien-Yu Chena936ac22017-10-23 15:59:49 -070074 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -080075 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000076 mDequeueBufferLatency(kDequeueLatencyBinSize),
77 mIPCTransport(transport) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080078
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080079 if (mConsumer == NULL) {
80 ALOGE("%s: Consumer is NULL!", __FUNCTION__);
81 mState = STATE_ERROR;
82 }
Zhijun He125684a2015-12-26 15:07:30 -080083
Shuzhen Wang0160ddd2019-08-15 09:11:56 -070084 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
85 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080086}
87
88Camera3OutputStream::Camera3OutputStream(int id,
Eino-Ville Talvala727d1722015-06-09 13:44:19 -070089 sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -080090 uint32_t width, uint32_t height, size_t maxSize, int format,
Emilian Peevf4816702020-04-03 15:44:51 -070091 android_dataspace dataSpace, camera_stream_rotation_t rotation,
Austin Borger1c1bee02023-06-01 16:51:35 -070092 nsecs_t timestampOffset, const std::string& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000093 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -080094 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -080095 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +000096 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -070097 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height, maxSize,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080098 format, dataSpace, rotation, physicalCameraId, sensorPixelModesUsed,
Shuzhen Wange4208922022-02-01 16:52:48 -080099 setId, isMultiResolution, dynamicRangeProfile, streamUseCase,
Austin Borger9e2b27c2022-07-15 11:27:24 -0700100 deviceTimeBaseIsRealtime, timestampBase, colorSpace),
Igor Murashkina55b5452013-04-02 16:36:33 -0700101 mConsumer(consumer),
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400102 mTransform(0),
Zhijun He125684a2015-12-26 15:07:30 -0800103 mTraceFirstBuffer(true),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800104 mUseBufferManager(false),
Zhijun He5d677d12016-05-29 16:52:39 -0700105 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000106 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700107 mConsumerUsage(0),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700108 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800109 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000110 mDequeueBufferLatency(kDequeueLatencyBinSize),
111 mIPCTransport(transport) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800112
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800113 if (format != HAL_PIXEL_FORMAT_BLOB && format != HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800114 ALOGE("%s: Bad format for size-only stream: %d", __FUNCTION__,
115 format);
116 mState = STATE_ERROR;
117 }
118
119 if (mConsumer == NULL) {
120 ALOGE("%s: Consumer is NULL!", __FUNCTION__);
121 mState = STATE_ERROR;
122 }
Zhijun He125684a2015-12-26 15:07:30 -0800123
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700124 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
125 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800126}
127
Zhijun He5d677d12016-05-29 16:52:39 -0700128Camera3OutputStream::Camera3OutputStream(int id,
129 uint32_t width, uint32_t height, int format,
Emilian Peev050f5dc2017-05-18 14:43:56 +0100130 uint64_t consumerUsage, android_dataspace dataSpace,
Emilian Peevf4816702020-04-03 15:44:51 -0700131 camera_stream_rotation_t rotation, nsecs_t timestampOffset,
Austin Borger1c1bee02023-06-01 16:51:35 -0700132 const std::string& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000133 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -0800134 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800135 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000136 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -0700137 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800138 /*maxSize*/0, format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -0800139 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -0800140 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -0700141 timestampBase, colorSpace),
Zhijun He5d677d12016-05-29 16:52:39 -0700142 mConsumer(nullptr),
143 mTransform(0),
144 mTraceFirstBuffer(true),
145 mUseBufferManager(false),
146 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000147 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700148 mConsumerUsage(consumerUsage),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700149 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800150 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000151 mDequeueBufferLatency(kDequeueLatencyBinSize),
152 mIPCTransport(transport) {
Zhijun He5d677d12016-05-29 16:52:39 -0700153 // Deferred consumer only support preview surface format now.
154 if (format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
155 ALOGE("%s: Deferred consumer only supports IMPLEMENTATION_DEFINED format now!",
156 __FUNCTION__);
157 mState = STATE_ERROR;
158 }
159
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400160 // Validation check for the consumer usage flag.
Zhijun He5d677d12016-05-29 16:52:39 -0700161 if ((consumerUsage & GraphicBuffer::USAGE_HW_TEXTURE) == 0 &&
162 (consumerUsage & GraphicBuffer::USAGE_HW_COMPOSER) == 0) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100163 ALOGE("%s: Deferred consumer usage flag is illegal %" PRIu64 "!",
164 __FUNCTION__, consumerUsage);
Zhijun He5d677d12016-05-29 16:52:39 -0700165 mState = STATE_ERROR;
166 }
167
Austin Borger1c1bee02023-06-01 16:51:35 -0700168 mConsumerName = "Deferred";
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700169 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
170 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Zhijun He5d677d12016-05-29 16:52:39 -0700171}
172
Emilian Peevf4816702020-04-03 15:44:51 -0700173Camera3OutputStream::Camera3OutputStream(int id, camera_stream_type_t type,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700174 uint32_t width, uint32_t height,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800175 int format,
Yin-Chia Yehb97babb2015-03-12 13:42:44 -0700176 android_dataspace dataSpace,
Emilian Peevf4816702020-04-03 15:44:51 -0700177 camera_stream_rotation_t rotation,
Austin Borger1c1bee02023-06-01 16:51:35 -0700178 const std::string& physicalCameraId,
Shuzhen Wange4208922022-02-01 16:52:48 -0800179 const std::unordered_set<int32_t> &sensorPixelModesUsed,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000180 IPCTransport transport,
Emilian Peev050f5dc2017-05-18 14:43:56 +0100181 uint64_t consumerUsage, nsecs_t timestampOffset,
Emilian Peev2295df72021-11-12 18:14:10 -0800182 int setId, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800183 int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800184 bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000185 int mirrorMode, int32_t colorSpace,
186 bool useReadoutTimestamp) :
Igor Murashkine3a9f962013-05-08 18:03:15 -0700187 Camera3IOStreamBase(id, type, width, height,
188 /*maxSize*/0,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800189 format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -0800190 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -0800191 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -0700192 timestampBase, colorSpace),
Zhijun He125684a2015-12-26 15:07:30 -0800193 mTransform(0),
194 mTraceFirstBuffer(true),
Zhijun He5d677d12016-05-29 16:52:39 -0700195 mUseBufferManager(false),
Shuzhen Wang0129d522016-10-30 22:43:41 -0700196 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000197 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700198 mConsumerUsage(consumerUsage),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700199 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800200 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000201 mDequeueBufferLatency(kDequeueLatencyBinSize),
202 mIPCTransport(transport) {
Zhijun He125684a2015-12-26 15:07:30 -0800203
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700204 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
205 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Igor Murashkine3a9f962013-05-08 18:03:15 -0700206
207 // Subclasses expected to initialize mConsumer themselves
208}
209
210
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800211Camera3OutputStream::~Camera3OutputStream() {
212 disconnectLocked();
213}
214
Emilian Peevf4816702020-04-03 15:44:51 -0700215status_t Camera3OutputStream::getBufferLocked(camera_stream_buffer *buffer,
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800216 const std::vector<size_t>&) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700217 ATRACE_HFR_CALL();
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800218
219 ANativeWindowBuffer* anb;
Zhijun He125684a2015-12-26 15:07:30 -0800220 int fenceFd = -1;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700221
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800222 status_t res;
223 res = getBufferLockedCommon(&anb, &fenceFd);
224 if (res != OK) {
225 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800226 }
227
Igor Murashkine3a9f962013-05-08 18:03:15 -0700228 /**
229 * FenceFD now owned by HAL except in case of error,
230 * in which case we reassign it to acquire_fence
231 */
232 handoutBufferLocked(*buffer, &(anb->handle), /*acquireFence*/fenceFd,
Emilian Peevf4816702020-04-03 15:44:51 -0700233 /*releaseFence*/-1, CAMERA_BUFFER_STATUS_OK, /*output*/true);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800234
235 return OK;
236}
237
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800238status_t Camera3OutputStream::getBuffersLocked(std::vector<OutstandingBuffer>* outBuffers) {
239 status_t res;
240
241 if ((res = getBufferPreconditionCheckLocked()) != OK) {
242 return res;
243 }
244
245 if (mUseBufferManager) {
246 ALOGE("%s: stream %d is managed by buffer manager and does not support batch operation",
247 __FUNCTION__, mId);
248 return INVALID_OPERATION;
249 }
250
251 sp<Surface> consumer = mConsumer;
252 /**
253 * Release the lock briefly to avoid deadlock for below scenario:
254 * Thread 1: StreamingProcessor::startStream -> Camera3Stream::isConfiguring().
255 * This thread acquired StreamingProcessor lock and try to lock Camera3Stream lock.
256 * Thread 2: Camera3Stream::returnBuffer->StreamingProcessor::onFrameAvailable().
257 * This thread acquired Camera3Stream lock and bufferQueue lock, and try to lock
258 * StreamingProcessor lock.
259 * Thread 3: Camera3Stream::getBuffer(). This thread acquired Camera3Stream lock
260 * and try to lock bufferQueue lock.
261 * Then there is circular locking dependency.
262 */
263 mLock.unlock();
264
265 size_t numBuffersRequested = outBuffers->size();
266 std::vector<Surface::BatchBuffer> buffers(numBuffersRequested);
267
268 nsecs_t dequeueStart = systemTime(SYSTEM_TIME_MONOTONIC);
269 res = consumer->dequeueBuffers(&buffers);
270 nsecs_t dequeueEnd = systemTime(SYSTEM_TIME_MONOTONIC);
271 mDequeueBufferLatency.add(dequeueStart, dequeueEnd);
272
273 mLock.lock();
274
275 if (res != OK) {
276 if (shouldLogError(res, mState)) {
277 ALOGE("%s: Stream %d: Can't dequeue %zu output buffers: %s (%d)",
278 __FUNCTION__, mId, numBuffersRequested, strerror(-res), res);
279 }
280 checkRetAndSetAbandonedLocked(res);
281 return res;
282 }
283 checkRemovedBuffersLocked();
284
285 /**
286 * FenceFD now owned by HAL except in case of error,
287 * in which case we reassign it to acquire_fence
288 */
289 for (size_t i = 0; i < numBuffersRequested; i++) {
290 handoutBufferLocked(*(outBuffers->at(i).outBuffer),
291 &(buffers[i].buffer->handle), /*acquireFence*/buffers[i].fenceFd,
292 /*releaseFence*/-1, CAMERA_BUFFER_STATUS_OK, /*output*/true);
293 }
294 return OK;
295}
296
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800297status_t Camera3OutputStream::queueBufferToConsumer(sp<ANativeWindow>& consumer,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700298 ANativeWindowBuffer* buffer, int anwReleaseFence,
299 const std::vector<size_t>&) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800300 return consumer->queueBuffer(consumer.get(), buffer, anwReleaseFence);
301}
302
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800303status_t Camera3OutputStream::returnBufferLocked(
Emilian Peevf4816702020-04-03 15:44:51 -0700304 const camera_stream_buffer &buffer,
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700305 nsecs_t timestamp, nsecs_t readoutTimestamp,
306 int32_t transform, const std::vector<size_t>& surface_ids) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700307 ATRACE_HFR_CALL();
Igor Murashkine3a9f962013-05-08 18:03:15 -0700308
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800309 if (mHandoutTotalBufferCount == 1) {
310 returnPrefetchedBuffersLocked();
311 }
312
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700313 status_t res = returnAnyBufferLocked(buffer, timestamp, readoutTimestamp,
314 /*output*/true, transform, surface_ids);
Igor Murashkine3a9f962013-05-08 18:03:15 -0700315
316 if (res != OK) {
317 return res;
318 }
319
320 mLastTimestamp = timestamp;
Eino-Ville Talvalac31dc7e2017-01-31 17:35:41 -0800321 mFrameCount++;
Igor Murashkine3a9f962013-05-08 18:03:15 -0700322
323 return OK;
324}
325
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000326status_t Camera3OutputStream::fixUpHidlJpegBlobHeader(ANativeWindowBuffer* anwBuffer, int fence) {
327 // Lock the JPEG buffer for CPU read
328 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(anwBuffer);
329 void* mapped = nullptr;
330 base::unique_fd fenceFd(dup(fence));
331 // Use USAGE_SW_WRITE_RARELY since we're going to re-write the CameraBlob
332 // header.
333 GraphicBufferLocker gbLocker(graphicBuffer);
334 status_t res =
335 gbLocker.lockAsync(
336 GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_RARELY,
Emilian Peev293bd972022-08-05 17:28:06 -0700337 &mapped, fenceFd.release());
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000338 if (res != OK) {
339 ALOGE("%s: Failed to lock the buffer: %s (%d)", __FUNCTION__, strerror(-res), res);
340 return res;
341 }
342
343 uint8_t *hidlHeaderStart =
344 static_cast<uint8_t*>(mapped) + graphicBuffer->getWidth() - sizeof(camera_jpeg_blob_t);
345 // Check that the jpeg buffer is big enough to contain HIDL camera blob
346 if (hidlHeaderStart < static_cast<uint8_t *>(mapped)) {
347 ALOGE("%s, jpeg buffer not large enough to fit HIDL camera blob %" PRIu32, __FUNCTION__,
348 graphicBuffer->getWidth());
349 return BAD_VALUE;
350 }
351 camera_jpeg_blob_t *hidlBlobHeader = reinterpret_cast<camera_jpeg_blob_t *>(hidlHeaderStart);
352
353 // Check that the blob is indeed the jpeg blob id.
354 if (hidlBlobHeader->jpeg_blob_id != CAMERA_JPEG_BLOB_ID) {
355 ALOGE("%s, jpeg blob id %d is not correct", __FUNCTION__, hidlBlobHeader->jpeg_blob_id);
356 return BAD_VALUE;
357 }
358
359 // Retrieve id and blob size
360 CameraBlobId blobId = static_cast<CameraBlobId>(hidlBlobHeader->jpeg_blob_id);
361 uint32_t blobSizeBytes = hidlBlobHeader->jpeg_size;
362
363 if (blobSizeBytes > (graphicBuffer->getWidth() - sizeof(camera_jpeg_blob_t))) {
364 ALOGE("%s, blobSize in HIDL jpeg blob : %d is corrupt, buffer size %" PRIu32, __FUNCTION__,
365 blobSizeBytes, graphicBuffer->getWidth());
366 }
367
368 uint8_t *aidlHeaderStart =
369 static_cast<uint8_t*>(mapped) + graphicBuffer->getWidth() - sizeof(CameraBlob);
370
371 // Check that the jpeg buffer is big enough to contain AIDL camera blob
372 if (aidlHeaderStart < static_cast<uint8_t *>(mapped)) {
373 ALOGE("%s, jpeg buffer not large enough to fit AIDL camera blob %" PRIu32, __FUNCTION__,
374 graphicBuffer->getWidth());
375 return BAD_VALUE;
376 }
377
378 if (static_cast<uint8_t*>(mapped) + blobSizeBytes > aidlHeaderStart) {
379 ALOGE("%s, jpeg blob with size %d , buffer size %" PRIu32 " not large enough to fit"
380 " AIDL camera blob without corrupting jpeg", __FUNCTION__, blobSizeBytes,
381 graphicBuffer->getWidth());
382 return BAD_VALUE;
383 }
384
385 // Fill in JPEG header
Avichal Rakesh51af0702022-05-26 22:58:03 +0000386 CameraBlob aidlHeader = {
387 .blobId = blobId,
388 .blobSizeBytes = static_cast<int32_t>(blobSizeBytes)
389 };
390 memcpy(aidlHeaderStart, &aidlHeader, sizeof(CameraBlob));
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000391 graphicBuffer->unlock();
392 return OK;
393}
394
Igor Murashkine3a9f962013-05-08 18:03:15 -0700395status_t Camera3OutputStream::returnBufferCheckedLocked(
Emilian Peevf4816702020-04-03 15:44:51 -0700396 const camera_stream_buffer &buffer,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700397 nsecs_t timestamp,
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700398 nsecs_t readoutTimestamp,
Jing Mikec7f9b132023-03-12 11:12:04 +0800399 [[maybe_unused]] bool output,
Emilian Peev5104fe92021-10-21 14:27:09 -0700400 int32_t transform,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700401 const std::vector<size_t>& surface_ids,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700402 /*out*/
403 sp<Fence> *releaseFenceOut) {
404
Igor Murashkine3a9f962013-05-08 18:03:15 -0700405 ALOG_ASSERT(output, "Expected output to be true");
406
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800407 status_t res;
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700408
Yin-Chia Yeh4c9736f2015-03-05 15:01:36 -0800409 // Fence management - always honor release fence from HAL
410 sp<Fence> releaseFence = new Fence(buffer.release_fence);
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700411 int anwReleaseFence = releaseFence->dup();
412
413 /**
Zhijun He124ccf42013-05-22 14:01:30 -0700414 * Release the lock briefly to avoid deadlock with
415 * StreamingProcessor::startStream -> Camera3Stream::isConfiguring (this
416 * thread will go into StreamingProcessor::onFrameAvailable) during
417 * queueBuffer
418 */
419 sp<ANativeWindow> currentConsumer = mConsumer;
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700420 StreamState state = mState;
Zhijun He124ccf42013-05-22 14:01:30 -0700421 mLock.unlock();
422
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800423 ANativeWindowBuffer *anwBuffer = container_of(buffer.buffer, ANativeWindowBuffer, handle);
Shuzhen Wangc2352702022-09-06 18:36:31 -0700424 bool bufferDeferred = false;
Zhijun He124ccf42013-05-22 14:01:30 -0700425 /**
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700426 * Return buffer back to ANativeWindow
427 */
Emilian Peevf4816702020-04-03 15:44:51 -0700428 if (buffer.status == CAMERA_BUFFER_STATUS_ERROR || mDropBuffers || timestamp == 0) {
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700429 // Cancel buffer
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700430 if (mDropBuffers) {
431 ALOGV("%s: Dropping a frame for stream %d.", __FUNCTION__, mId);
Emilian Peevf4816702020-04-03 15:44:51 -0700432 } else if (buffer.status == CAMERA_BUFFER_STATUS_ERROR) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700433 ALOGV("%s: A frame is dropped for stream %d due to buffer error.", __FUNCTION__, mId);
Shuzhen Wangf0c4a6b2018-09-05 09:36:14 -0700434 } else {
435 ALOGE("%s: Stream %d: timestamp shouldn't be 0", __FUNCTION__, mId);
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700436 }
437
Zhijun He124ccf42013-05-22 14:01:30 -0700438 res = currentConsumer->cancelBuffer(currentConsumer.get(),
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800439 anwBuffer,
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700440 anwReleaseFence);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700441 if (shouldLogError(res, state)) {
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700442 ALOGE("%s: Stream %d: Error cancelling buffer to native window:"
Igor Murashkine3a9f962013-05-08 18:03:15 -0700443 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700444 }
Zhijun He1ff811b2016-01-26 14:39:51 -0800445
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800446 notifyBufferReleased(anwBuffer);
Zhijun He1ff811b2016-01-26 14:39:51 -0800447 if (mUseBufferManager) {
448 // Return this buffer back to buffer manager.
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700449 mBufferProducerListener->onBufferReleased();
Zhijun He1ff811b2016-01-26 14:39:51 -0800450 }
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700451 } else {
Emilian Peevf4816702020-04-03 15:44:51 -0700452 if (mTraceFirstBuffer && (stream_type == CAMERA_STREAM_OUTPUT)) {
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400453 {
454 char traceLog[48];
455 snprintf(traceLog, sizeof(traceLog), "Stream %d: first full buffer\n", mId);
456 ATRACE_NAME(traceLog);
457 }
458 mTraceFirstBuffer = false;
459 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000460 // Fix CameraBlob id type discrepancy between HIDL and AIDL, details : http://b/229688810
Emilian Peeve579d8b2023-02-28 14:16:08 -0800461 if (getFormat() == HAL_PIXEL_FORMAT_BLOB && (getDataSpace() == HAL_DATASPACE_V0_JFIF ||
462 (getDataSpace() ==
463 static_cast<android_dataspace_t>(
464 aidl::android::hardware::graphics::common::Dataspace::JPEG_R)))) {
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000465 if (mIPCTransport == IPCTransport::HIDL) {
466 fixUpHidlJpegBlobHeader(anwBuffer, anwReleaseFence);
467 }
468 // If this is a JPEG output, and image dump mask is set, save image to
469 // disk.
470 if (mImageDumpMask) {
471 dumpImageToDisk(timestamp, anwBuffer, anwReleaseFence);
472 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -0800473 }
Yin-Chia Yeh4c9736f2015-03-05 15:01:36 -0800474
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000475 nsecs_t captureTime = ((mUseReadoutTime || mSyncToDisplay) && readoutTimestamp != 0 ?
Shuzhen Wangffc4c012022-04-20 15:55:46 -0700476 readoutTimestamp : timestamp) - mTimestampOffset;
Shuzhen Wangba92d772022-04-11 11:47:24 -0700477 if (mPreviewFrameSpacer != nullptr) {
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700478 nsecs_t readoutTime = (readoutTimestamp != 0 ? readoutTimestamp : timestamp)
479 - mTimestampOffset;
480 res = mPreviewFrameSpacer->queuePreviewBuffer(captureTime, readoutTime,
481 transform, anwBuffer, anwReleaseFence);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700482 if (res != OK) {
483 ALOGE("%s: Stream %d: Error queuing buffer to preview buffer spacer: %s (%d)",
484 __FUNCTION__, mId, strerror(-res), res);
485 return res;
486 }
Shuzhen Wangc2352702022-09-06 18:36:31 -0700487 bufferDeferred = true;
Shuzhen Wangba92d772022-04-11 11:47:24 -0700488 } else {
Shuzhen Wangba92d772022-04-11 11:47:24 -0700489 nsecs_t presentTime = mSyncToDisplay ?
Shuzhen Wang0897d592023-04-07 12:48:05 -0700490 syncTimestampToDisplayLocked(captureTime, releaseFence->dup()) : captureTime;
Emilian Peev2295df72021-11-12 18:14:10 -0800491
Shuzhen Wangba92d772022-04-11 11:47:24 -0700492 setTransform(transform, true/*mayChangeMirror*/);
493 res = native_window_set_buffers_timestamp(mConsumer.get(), presentTime);
494 if (res != OK) {
495 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
496 __FUNCTION__, mId, strerror(-res), res);
497 return res;
498 }
Emilian Peev2295df72021-11-12 18:14:10 -0800499
Shuzhen Wangba92d772022-04-11 11:47:24 -0700500 queueHDRMetadata(anwBuffer->handle, currentConsumer, dynamic_range_profile);
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800501
Shuzhen Wangba92d772022-04-11 11:47:24 -0700502 res = queueBufferToConsumer(currentConsumer, anwBuffer, anwReleaseFence, surface_ids);
503 if (shouldLogError(res, state)) {
504 ALOGE("%s: Stream %d: Error queueing buffer to native window:"
505 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
506 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800507 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800508 }
Zhijun He124ccf42013-05-22 14:01:30 -0700509 mLock.lock();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700510
Shuzhen Wangc2352702022-09-06 18:36:31 -0700511 if (bufferDeferred) {
512 mCachedOutputBufferCount++;
513 }
514
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700515 // Once a valid buffer has been returned to the queue, can no longer
516 // dequeue all buffers for preallocation.
Emilian Peevf4816702020-04-03 15:44:51 -0700517 if (buffer.status != CAMERA_BUFFER_STATUS_ERROR) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700518 mStreamUnpreparable = true;
519 }
520
Igor Murashkine3a9f962013-05-08 18:03:15 -0700521 *releaseFenceOut = releaseFence;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800522
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700523 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800524}
525
Jing Mikec7f9b132023-03-12 11:12:04 +0800526void Camera3OutputStream::dump(int fd, [[maybe_unused]] const Vector<String16> &args) const {
Austin Borger1c1bee02023-06-01 16:51:35 -0700527 std::string lines;
528 lines += fmt::sprintf(" Stream[%d]: Output\n", mId);
529 lines += fmt::sprintf(" Consumer name: %s\n", mConsumerName);
530 write(fd, lines.c_str(), lines.size());
Igor Murashkine3a9f962013-05-08 18:03:15 -0700531
532 Camera3IOStreamBase::dump(fd, args);
Shuzhen Wang686f6442017-06-20 16:16:04 -0700533
534 mDequeueBufferLatency.dump(fd,
535 " DequeueBuffer latency histogram:");
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800536}
537
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800538status_t Camera3OutputStream::setTransform(int transform, bool mayChangeMirror) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800539 ATRACE_CALL();
540 Mutex::Autolock l(mLock);
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800541 if (mMirrorMode != OutputConfiguration::MIRROR_MODE_AUTO && mayChangeMirror) {
542 // If the mirroring mode is not AUTO, do not allow transform update
543 // which may change mirror.
544 return OK;
545 }
546
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800547 return setTransformLocked(transform);
548}
549
550status_t Camera3OutputStream::setTransformLocked(int transform) {
551 status_t res = OK;
Shuzhen Wange4adddb2021-09-21 15:24:44 -0700552
553 if (transform == -1) return res;
554
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800555 if (mState == STATE_ERROR) {
556 ALOGE("%s: Stream in error state", __FUNCTION__);
557 return INVALID_OPERATION;
558 }
559
560 mTransform = transform;
561 if (mState == STATE_CONFIGURED) {
562 res = native_window_set_buffers_transform(mConsumer.get(),
563 transform);
564 if (res != OK) {
565 ALOGE("%s: Unable to configure stream transform to %x: %s (%d)",
566 __FUNCTION__, transform, strerror(-res), res);
567 }
568 }
569 return res;
570}
571
572status_t Camera3OutputStream::configureQueueLocked() {
573 status_t res;
574
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400575 mTraceFirstBuffer = true;
Igor Murashkine3a9f962013-05-08 18:03:15 -0700576 if ((res = Camera3IOStreamBase::configureQueueLocked()) != OK) {
577 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800578 }
579
Shuzhen Wangba92d772022-04-11 11:47:24 -0700580 if ((res = configureConsumerQueueLocked(true /*allowPreviewRespace*/)) != OK) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700581 return res;
582 }
583
584 // Set dequeueBuffer/attachBuffer timeout if the consumer is not hw composer or hw texture.
585 // We need skip these cases as timeout will disable the non-blocking (async) mode.
586 if (!(isConsumedByHWComposer() || isConsumedByHWTexture())) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800587 if (mUseBufferManager) {
588 // When buffer manager is handling the buffer, we should have available buffers in
589 // buffer queue before we calls into dequeueBuffer because buffer manager is tracking
590 // free buffers.
591 // There are however some consumer side feature (ImageReader::discardFreeBuffers) that
592 // can discard free buffers without notifying buffer manager. We want the timeout to
593 // happen immediately here so buffer manager can try to update its internal state and
594 // try to allocate a buffer instead of waiting.
595 mConsumer->setDequeueTimeout(0);
596 } else {
597 mConsumer->setDequeueTimeout(kDequeueBufferTimeout);
598 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700599 }
600
601 return OK;
602}
603
Shuzhen Wangba92d772022-04-11 11:47:24 -0700604status_t Camera3OutputStream::configureConsumerQueueLocked(bool allowPreviewRespace) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700605 status_t res;
606
607 mTraceFirstBuffer = true;
608
Igor Murashkine3a9f962013-05-08 18:03:15 -0700609 ALOG_ASSERT(mConsumer != 0, "mConsumer should never be NULL");
610
Zhijun He125684a2015-12-26 15:07:30 -0800611 // Configure consumer-side ANativeWindow interface. The listener may be used
612 // to notify buffer manager (if it is used) of the returned buffers.
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700613 res = mConsumer->connect(NATIVE_WINDOW_API_CAMERA,
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700614 /*reportBufferRemoval*/true,
615 /*listener*/mBufferProducerListener);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800616 if (res != OK) {
617 ALOGE("%s: Unable to connect to native window for stream %d",
618 __FUNCTION__, mId);
619 return res;
620 }
621
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700622 mConsumerName = mConsumer->getConsumerName();
623
Emilian Peev050f5dc2017-05-18 14:43:56 +0100624 res = native_window_set_usage(mConsumer.get(), mUsage);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800625 if (res != OK) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100626 ALOGE("%s: Unable to configure usage %" PRIu64 " for stream %d",
627 __FUNCTION__, mUsage, mId);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800628 return res;
629 }
630
631 res = native_window_set_scaling_mode(mConsumer.get(),
632 NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
633 if (res != OK) {
634 ALOGE("%s: Unable to configure stream scaling: %s (%d)",
635 __FUNCTION__, strerror(-res), res);
636 return res;
637 }
638
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800639 if (mMaxSize == 0) {
640 // For buffers of known size
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700641 res = native_window_set_buffers_dimensions(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700642 camera_stream::width, camera_stream::height);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800643 } else {
644 // For buffers with bounded size
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700645 res = native_window_set_buffers_dimensions(mConsumer.get(),
646 mMaxSize, 1);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800647 }
648 if (res != OK) {
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700649 ALOGE("%s: Unable to configure stream buffer dimensions"
650 " %d x %d (maxSize %zu) for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700651 __FUNCTION__, camera_stream::width, camera_stream::height,
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700652 mMaxSize, mId);
653 return res;
654 }
655 res = native_window_set_buffers_format(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700656 camera_stream::format);
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700657 if (res != OK) {
658 ALOGE("%s: Unable to configure stream buffer format %#x for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700659 __FUNCTION__, camera_stream::format, mId);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800660 return res;
661 }
662
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800663 res = native_window_set_buffers_data_space(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700664 camera_stream::data_space);
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800665 if (res != OK) {
666 ALOGE("%s: Unable to configure stream dataspace %#x for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700667 __FUNCTION__, camera_stream::data_space, mId);
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800668 return res;
669 }
670
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800671 int maxConsumerBuffers;
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700672 res = static_cast<ANativeWindow*>(mConsumer.get())->query(
673 mConsumer.get(),
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800674 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
675 if (res != OK) {
676 ALOGE("%s: Unable to query consumer undequeued"
677 " buffer count for stream %d", __FUNCTION__, mId);
678 return res;
679 }
680
Alex Ray20cb3002013-05-28 20:18:22 -0700681 ALOGV("%s: Consumer wants %d buffers, HAL wants %d", __FUNCTION__,
Emilian Peevf4816702020-04-03 15:44:51 -0700682 maxConsumerBuffers, camera_stream::max_buffers);
683 if (camera_stream::max_buffers == 0) {
Zhijun He2ab500c2013-07-23 08:02:53 -0700684 ALOGE("%s: Camera HAL requested max_buffer count: %d, requires at least 1",
Emilian Peevf4816702020-04-03 15:44:51 -0700685 __FUNCTION__, camera_stream::max_buffers);
Alex Ray20cb3002013-05-28 20:18:22 -0700686 return INVALID_OPERATION;
687 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800688
Emilian Peevf4816702020-04-03 15:44:51 -0700689 mTotalBufferCount = maxConsumerBuffers + camera_stream::max_buffers;
Shuzhen Wange4208922022-02-01 16:52:48 -0800690
691 int timestampBase = getTimestampBase();
692 bool isDefaultTimeBase = (timestampBase ==
693 OutputConfiguration::TIMESTAMP_BASE_DEFAULT);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700694 if (allowPreviewRespace) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800695 bool forceChoreographer = (timestampBase ==
696 OutputConfiguration::TIMESTAMP_BASE_CHOREOGRAPHER_SYNCED);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700697 bool defaultToChoreographer = (isDefaultTimeBase &&
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700698 isConsumedByHWComposer());
699 bool defaultToSpacer = (isDefaultTimeBase &&
700 isConsumedByHWTexture() &&
701 !isConsumedByCPU() &&
702 !isVideoStream());
Shuzhen Wange4208922022-02-01 16:52:48 -0800703 if (forceChoreographer || defaultToChoreographer) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800704 mSyncToDisplay = true;
Shuzhen Wangc2352702022-09-06 18:36:31 -0700705 // For choreographer synced stream, extra buffers aren't kept by
706 // camera service. So no need to update mMaxCachedBufferCount.
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800707 mTotalBufferCount += kDisplaySyncExtraBuffer;
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700708 } else if (defaultToSpacer) {
Shuzhen Wangdc9aa822022-05-16 10:04:17 -0700709 mPreviewFrameSpacer = new PreviewFrameSpacer(this, mConsumer);
Shuzhen Wangc2352702022-09-06 18:36:31 -0700710 // For preview frame spacer, the extra buffer is kept by camera
711 // service. So update mMaxCachedBufferCount.
712 mMaxCachedBufferCount = 1;
713 mTotalBufferCount += mMaxCachedBufferCount;
Austin Borger1c1bee02023-06-01 16:51:35 -0700714 res = mPreviewFrameSpacer->run((std::string("PreviewSpacer-")
715 + std::to_string(mId)).c_str());
Shuzhen Wangba92d772022-04-11 11:47:24 -0700716 if (res != OK) {
Austin Borger7b129542022-06-09 13:23:06 -0700717 ALOGE("%s: Unable to start preview spacer: %s (%d)", __FUNCTION__,
718 strerror(-res), res);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700719 return res;
720 }
Shuzhen Wange4adddb2021-09-21 15:24:44 -0700721 }
722 }
Zhijun He6adc9cc2014-04-15 14:09:55 -0700723 mHandoutTotalBufferCount = 0;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800724 mFrameCount = 0;
725 mLastTimestamp = 0;
Shuzhen Wange4208922022-02-01 16:52:48 -0800726
727 if (isDeviceTimeBaseRealtime()) {
728 if (isDefaultTimeBase && !isConsumedByHWComposer() && !isVideoStream()) {
729 // Default time base, but not hardware composer or video encoder
730 mTimestampOffset = 0;
731 } else if (timestampBase == OutputConfiguration::TIMESTAMP_BASE_REALTIME ||
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000732 timestampBase == OutputConfiguration::TIMESTAMP_BASE_SENSOR) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800733 mTimestampOffset = 0;
734 }
735 // If timestampBase is CHOREOGRAPHER SYNCED or MONOTONIC, leave
736 // timestamp offset as bootTime - monotonicTime.
737 } else {
738 if (timestampBase == OutputConfiguration::TIMESTAMP_BASE_REALTIME) {
739 // Reverse offset for monotonicTime -> bootTime
740 mTimestampOffset = -mTimestampOffset;
741 } else {
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000742 // If timestampBase is DEFAULT, MONOTONIC, SENSOR or
Shuzhen Wange4208922022-02-01 16:52:48 -0800743 // CHOREOGRAPHER_SYNCED, timestamp offset is 0.
744 mTimestampOffset = 0;
745 }
746 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800747
748 res = native_window_set_buffer_count(mConsumer.get(),
749 mTotalBufferCount);
750 if (res != OK) {
751 ALOGE("%s: Unable to set buffer count for stream %d",
752 __FUNCTION__, mId);
753 return res;
754 }
755
756 res = native_window_set_buffers_transform(mConsumer.get(),
757 mTransform);
758 if (res != OK) {
759 ALOGE("%s: Unable to configure stream transform to %x: %s (%d)",
760 __FUNCTION__, mTransform, strerror(-res), res);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700761 return res;
Zhijun Hef0645c12016-08-02 00:58:11 -0700762 }
763
Zhijun He125684a2015-12-26 15:07:30 -0800764 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -0800765 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs requires
Zhijun He125684a2015-12-26 15:07:30 -0800766 * buffers to be statically allocated for internal static buffer registration, while the
767 * buffers provided by buffer manager are really dynamically allocated. Camera3Device only
Zhijun Heedd41ae2016-02-03 14:45:53 -0800768 * sets the mBufferManager if device version is > HAL3.2, which guarantees that the buffer
769 * manager setup is skipped in below code. Note that HAL3.2 is also excluded here, as some
770 * HAL3.2 devices may not support the dynamic buffer registeration.
Yin-Chia Yehb6578902019-04-16 13:36:16 -0700771 * Also Camera3BufferManager does not support display/texture streams as they have its own
772 * buffer management logic.
Zhijun He125684a2015-12-26 15:07:30 -0800773 */
Yin-Chia Yehb6578902019-04-16 13:36:16 -0700774 if (mBufferManager != 0 && mSetId > CAMERA3_STREAM_SET_ID_INVALID &&
775 !(isConsumedByHWComposer() || isConsumedByHWTexture())) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100776 uint64_t consumerUsage = 0;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700777 getEndpointUsage(&consumerUsage);
Shuzhen Wang83bff122020-11-20 15:51:39 -0800778 uint32_t width = (mMaxSize == 0) ? getWidth() : mMaxSize;
779 uint32_t height = (mMaxSize == 0) ? getHeight() : 1;
Zhijun He125684a2015-12-26 15:07:30 -0800780 StreamInfo streamInfo(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800781 getId(), getStreamSetId(), width, height, getFormat(), getDataSpace(),
Emilian Peev050f5dc2017-05-18 14:43:56 +0100782 mUsage | consumerUsage, mTotalBufferCount,
Shuzhen Wang83bff122020-11-20 15:51:39 -0800783 /*isConfigured*/true, isMultiResolution());
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700784 wp<Camera3OutputStream> weakThis(this);
785 res = mBufferManager->registerStream(weakThis,
786 streamInfo);
Zhijun He125684a2015-12-26 15:07:30 -0800787 if (res == OK) {
788 // Disable buffer allocation for this BufferQueue, buffer manager will take over
789 // the buffer allocation responsibility.
790 mConsumer->getIGraphicBufferProducer()->allowAllocation(false);
791 mUseBufferManager = true;
792 } else {
793 ALOGE("%s: Unable to register stream %d to camera3 buffer manager, "
794 "(error %d %s), fall back to BufferQueue for buffer management!",
795 __FUNCTION__, mId, res, strerror(-res));
796 }
797 }
798
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800799 return OK;
800}
801
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800802status_t Camera3OutputStream::getBufferLockedCommon(ANativeWindowBuffer** anb, int* fenceFd) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700803 ATRACE_HFR_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800804 status_t res;
805
806 if ((res = getBufferPreconditionCheckLocked()) != OK) {
807 return res;
808 }
809
810 bool gotBufferFromManager = false;
811
812 if (mUseBufferManager) {
813 sp<GraphicBuffer> gb;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800814 res = mBufferManager->getBufferForStream(getId(), getStreamSetId(),
815 isMultiResolution(), &gb, fenceFd);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800816 if (res == OK) {
817 // Attach this buffer to the bufferQueue: the buffer will be in dequeue state after a
818 // successful return.
819 *anb = gb.get();
820 res = mConsumer->attachBuffer(*anb);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700821 if (shouldLogError(res, mState)) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800822 ALOGE("%s: Stream %d: Can't attach the output buffer to this surface: %s (%d)",
823 __FUNCTION__, mId, strerror(-res), res);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700824 }
825 if (res != OK) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800826 checkRetAndSetAbandonedLocked(res);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800827 return res;
828 }
829 gotBufferFromManager = true;
830 ALOGV("Stream %d: Attached new buffer", getId());
831 } else if (res == ALREADY_EXISTS) {
832 // Have sufficient free buffers already attached, can just
833 // dequeue from buffer queue
834 ALOGV("Stream %d: Reusing attached buffer", getId());
835 gotBufferFromManager = false;
836 } else if (res != OK) {
837 ALOGE("%s: Stream %d: Can't get next output buffer from buffer manager: %s (%d)",
838 __FUNCTION__, mId, strerror(-res), res);
839 return res;
840 }
841 }
842 if (!gotBufferFromManager) {
843 /**
844 * Release the lock briefly to avoid deadlock for below scenario:
845 * Thread 1: StreamingProcessor::startStream -> Camera3Stream::isConfiguring().
846 * This thread acquired StreamingProcessor lock and try to lock Camera3Stream lock.
847 * Thread 2: Camera3Stream::returnBuffer->StreamingProcessor::onFrameAvailable().
848 * This thread acquired Camera3Stream lock and bufferQueue lock, and try to lock
849 * StreamingProcessor lock.
850 * Thread 3: Camera3Stream::getBuffer(). This thread acquired Camera3Stream lock
851 * and try to lock bufferQueue lock.
852 * Then there is circular locking dependency.
853 */
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800854 sp<Surface> consumer = mConsumer;
Shuzhen Wang6c14e312021-07-05 16:20:33 -0700855 size_t remainingBuffers = (mState == STATE_PREPARING ? mTotalBufferCount :
856 camera_stream::max_buffers) - mHandoutTotalBufferCount;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800857 mLock.unlock();
858
Shuzhen Wang686f6442017-06-20 16:16:04 -0700859 nsecs_t dequeueStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800860
Shuzhen Wangc7629462021-07-12 15:02:58 -0700861 size_t batchSize = mBatchSize.load();
862 if (batchSize == 1) {
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800863 sp<ANativeWindow> anw = consumer;
864 res = anw->dequeueBuffer(anw.get(), anb, fenceFd);
865 } else {
Shuzhen Wangc7629462021-07-12 15:02:58 -0700866 std::unique_lock<std::mutex> batchLock(mBatchLock);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800867 res = OK;
868 if (mBatchedBuffers.size() == 0) {
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800869 if (remainingBuffers == 0) {
870 ALOGE("%s: cannot get buffer while all buffers are handed out", __FUNCTION__);
871 return INVALID_OPERATION;
872 }
873 if (batchSize > remainingBuffers) {
874 batchSize = remainingBuffers;
875 }
Shuzhen Wangc7629462021-07-12 15:02:58 -0700876 batchLock.unlock();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800877 // Refill batched buffers
Shuzhen Wangc7629462021-07-12 15:02:58 -0700878 std::vector<Surface::BatchBuffer> batchedBuffers;
879 batchedBuffers.resize(batchSize);
880 res = consumer->dequeueBuffers(&batchedBuffers);
881 batchLock.lock();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800882 if (res != OK) {
883 ALOGE("%s: batch dequeueBuffers call failed! %s (%d)",
884 __FUNCTION__, strerror(-res), res);
Shuzhen Wangc7629462021-07-12 15:02:58 -0700885 } else {
886 mBatchedBuffers = std::move(batchedBuffers);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800887 }
888 }
889
890 if (res == OK) {
891 // Dispatch batch buffers
892 *anb = mBatchedBuffers.back().buffer;
893 *fenceFd = mBatchedBuffers.back().fenceFd;
894 mBatchedBuffers.pop_back();
895 }
896 }
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800897
Shuzhen Wang686f6442017-06-20 16:16:04 -0700898 nsecs_t dequeueEnd = systemTime(SYSTEM_TIME_MONOTONIC);
899 mDequeueBufferLatency.add(dequeueStart, dequeueEnd);
900
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800901 mLock.lock();
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800902
903 if (mUseBufferManager && res == TIMED_OUT) {
904 checkRemovedBuffersLocked();
905
906 sp<GraphicBuffer> gb;
907 res = mBufferManager->getBufferForStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800908 getId(), getStreamSetId(), isMultiResolution(),
909 &gb, fenceFd, /*noFreeBuffer*/true);
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800910
911 if (res == OK) {
912 // Attach this buffer to the bufferQueue: the buffer will be in dequeue state after
913 // a successful return.
914 *anb = gb.get();
915 res = mConsumer->attachBuffer(*anb);
916 gotBufferFromManager = true;
917 ALOGV("Stream %d: Attached new buffer", getId());
918
919 if (res != OK) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700920 if (shouldLogError(res, mState)) {
921 ALOGE("%s: Stream %d: Can't attach the output buffer to this surface:"
922 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
923 }
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800924 checkRetAndSetAbandonedLocked(res);
925 return res;
926 }
927 } else {
928 ALOGE("%s: Stream %d: Can't get next output buffer from buffer manager:"
929 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
930 return res;
931 }
932 } else if (res != OK) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700933 if (shouldLogError(res, mState)) {
934 ALOGE("%s: Stream %d: Can't dequeue next output buffer: %s (%d)",
935 __FUNCTION__, mId, strerror(-res), res);
936 }
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800937 checkRetAndSetAbandonedLocked(res);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800938 return res;
939 }
940 }
941
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700942 if (res == OK) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800943 checkRemovedBuffersLocked();
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700944 }
945
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800946 return res;
947}
948
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800949void Camera3OutputStream::checkRemovedBuffersLocked(bool notifyBufferManager) {
950 std::vector<sp<GraphicBuffer>> removedBuffers;
951 status_t res = mConsumer->getAndFlushRemovedBuffers(&removedBuffers);
952 if (res == OK) {
953 onBuffersRemovedLocked(removedBuffers);
954
955 if (notifyBufferManager && mUseBufferManager && removedBuffers.size() > 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800956 mBufferManager->onBuffersRemoved(getId(), getStreamSetId(), isMultiResolution(),
957 removedBuffers.size());
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800958 }
959 }
960}
961
962void Camera3OutputStream::checkRetAndSetAbandonedLocked(status_t res) {
963 // Only transition to STATE_ABANDONED from STATE_CONFIGURED. (If it is
964 // STATE_PREPARING, let prepareNextBuffer handle the error.)
965 if ((res == NO_INIT || res == DEAD_OBJECT) && mState == STATE_CONFIGURED) {
966 mState = STATE_ABANDONED;
967 }
968}
969
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700970bool Camera3OutputStream::shouldLogError(status_t res, StreamState state) {
971 if (res == OK) {
972 return false;
973 }
974 if ((res == DEAD_OBJECT || res == NO_INIT) && state == STATE_ABANDONED) {
975 return false;
976 }
977 return true;
978}
979
Shuzhen Wangc2352702022-09-06 18:36:31 -0700980void Camera3OutputStream::onCachedBufferQueued() {
981 Mutex::Autolock l(mLock);
982 mCachedOutputBufferCount--;
983 // Signal whoever is waiting for the buffer to be returned to the buffer
984 // queue.
985 mOutputBufferReturnedSignal.signal();
986}
987
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800988status_t Camera3OutputStream::disconnectLocked() {
989 status_t res;
990
Igor Murashkine3a9f962013-05-08 18:03:15 -0700991 if ((res = Camera3IOStreamBase::disconnectLocked()) != OK) {
992 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800993 }
994
Zhijun He5d677d12016-05-29 16:52:39 -0700995 // Stream configuration was not finished (can only be in STATE_IN_CONFIG or STATE_CONSTRUCTED
996 // state), don't need change the stream state, return OK.
997 if (mConsumer == nullptr) {
998 return OK;
999 }
1000
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001001 returnPrefetchedBuffersLocked();
1002
Shuzhen Wangdc9aa822022-05-16 10:04:17 -07001003 if (mPreviewFrameSpacer != nullptr) {
1004 mPreviewFrameSpacer->requestExit();
1005 }
1006
Zhijun He125684a2015-12-26 15:07:30 -08001007 ALOGV("%s: disconnecting stream %d from native window", __FUNCTION__, getId());
1008
Igor Murashkine3a9f962013-05-08 18:03:15 -07001009 res = native_window_api_disconnect(mConsumer.get(),
1010 NATIVE_WINDOW_API_CAMERA);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001011 /**
1012 * This is not an error. if client calling process dies, the window will
1013 * also die and all calls to it will return DEAD_OBJECT, thus it's already
1014 * "disconnected"
1015 */
1016 if (res == DEAD_OBJECT) {
1017 ALOGW("%s: While disconnecting stream %d from native window, the"
1018 " native window died from under us", __FUNCTION__, mId);
1019 }
1020 else if (res != OK) {
Igor Murashkine3a9f962013-05-08 18:03:15 -07001021 ALOGE("%s: Unable to disconnect stream %d from native window "
1022 "(error %d %s)",
1023 __FUNCTION__, mId, res, strerror(-res));
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001024 mState = STATE_ERROR;
1025 return res;
1026 }
1027
Zhijun He125684a2015-12-26 15:07:30 -08001028 // Since device is already idle, there is no getBuffer call to buffer manager, unregister the
1029 // stream at this point should be safe.
1030 if (mUseBufferManager) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08001031 res = mBufferManager->unregisterStream(getId(), getStreamSetId(), isMultiResolution());
Zhijun He125684a2015-12-26 15:07:30 -08001032 if (res != OK) {
1033 ALOGE("%s: Unable to unregister stream %d from buffer manager "
1034 "(error %d %s)", __FUNCTION__, mId, res, strerror(-res));
1035 mState = STATE_ERROR;
1036 return res;
1037 }
1038 // Note that, to make prepare/teardown case work, we must not mBufferManager.clear(), as
1039 // the stream is still in usable state after this call.
1040 mUseBufferManager = false;
1041 }
1042
Igor Murashkine3a9f962013-05-08 18:03:15 -07001043 mState = (mState == STATE_IN_RECONFIG) ? STATE_IN_CONFIG
1044 : STATE_CONSTRUCTED;
Shuzhen Wang686f6442017-06-20 16:16:04 -07001045
1046 mDequeueBufferLatency.log("Stream %d dequeueBuffer latency histogram", mId);
1047 mDequeueBufferLatency.reset();
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001048 return OK;
1049}
1050
Emilian Peev050f5dc2017-05-18 14:43:56 +01001051status_t Camera3OutputStream::getEndpointUsage(uint64_t *usage) const {
Eino-Ville Talvalab2f5b192013-07-30 14:36:03 -07001052
1053 status_t res;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001054
Zhijun He5d677d12016-05-29 16:52:39 -07001055 if (mConsumer == nullptr) {
1056 // mConsumerUsage was sanitized before the Camera3OutputStream was constructed.
1057 *usage = mConsumerUsage;
1058 return OK;
1059 }
1060
Shuzhen Wang0129d522016-10-30 22:43:41 -07001061 res = getEndpointUsageForSurface(usage, mConsumer);
1062
1063 return res;
1064}
1065
Emilian Peev35ae8262018-11-08 13:11:32 +00001066void Camera3OutputStream::applyZSLUsageQuirk(int format, uint64_t *consumerUsage /*inout*/) {
1067 if (consumerUsage == nullptr) {
1068 return;
1069 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001070
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001071 // If an opaque output stream's endpoint is ImageReader, add
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07001072 // GRALLOC_USAGE_HW_CAMERA_ZSL to the usage so HAL knows it will be used
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001073 // for the ZSL use case.
1074 // Assume it's for ImageReader if the consumer usage doesn't have any of these bits set:
1075 // 1. GRALLOC_USAGE_HW_TEXTURE
1076 // 2. GRALLOC_USAGE_HW_RENDER
1077 // 3. GRALLOC_USAGE_HW_COMPOSER
1078 // 4. GRALLOC_USAGE_HW_VIDEO_ENCODER
Emilian Peev35ae8262018-11-08 13:11:32 +00001079 if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
1080 (*consumerUsage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
Shuzhen Wang0129d522016-10-30 22:43:41 -07001081 GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_VIDEO_ENCODER)) == 0) {
Emilian Peev35ae8262018-11-08 13:11:32 +00001082 *consumerUsage |= GRALLOC_USAGE_HW_CAMERA_ZSL;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001083 }
Emilian Peev35ae8262018-11-08 13:11:32 +00001084}
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001085
Emilian Peev35ae8262018-11-08 13:11:32 +00001086status_t Camera3OutputStream::getEndpointUsageForSurface(uint64_t *usage,
1087 const sp<Surface>& surface) const {
1088 status_t res;
1089 uint64_t u = 0;
1090
1091 res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(surface.get()), &u);
Emilian Peevf4816702020-04-03 15:44:51 -07001092 applyZSLUsageQuirk(camera_stream::format, &u);
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001093 *usage = u;
Eino-Ville Talvalab2f5b192013-07-30 14:36:03 -07001094 return res;
1095}
1096
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001097bool Camera3OutputStream::isVideoStream() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001098 uint64_t usage = 0;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001099 status_t res = getEndpointUsage(&usage);
1100 if (res != OK) {
1101 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1102 return false;
1103 }
1104
1105 return (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0;
1106}
1107
Zhijun He125684a2015-12-26 15:07:30 -08001108status_t Camera3OutputStream::setBufferManager(sp<Camera3BufferManager> bufferManager) {
1109 Mutex::Autolock l(mLock);
1110 if (mState != STATE_CONSTRUCTED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001111 ALOGE("%s: this method can only be called when stream in CONSTRUCTED state.",
Zhijun He125684a2015-12-26 15:07:30 -08001112 __FUNCTION__);
1113 return INVALID_OPERATION;
1114 }
1115 mBufferManager = bufferManager;
1116
1117 return OK;
1118}
1119
Emilian Peev40ead602017-09-26 15:46:36 +01001120status_t Camera3OutputStream::updateStream(const std::vector<sp<Surface>> &/*outputSurfaces*/,
1121 const std::vector<OutputStreamInfo> &/*outputInfo*/,
1122 const std::vector<size_t> &/*removedSurfaceIds*/,
1123 KeyedVector<sp<Surface>, size_t> * /*outputMapo*/) {
1124 ALOGE("%s: this method is not supported!", __FUNCTION__);
1125 return INVALID_OPERATION;
1126}
1127
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001128void Camera3OutputStream::BufferProducerListener::onBufferReleased() {
Zhijun He125684a2015-12-26 15:07:30 -08001129 sp<Camera3OutputStream> stream = mParent.promote();
1130 if (stream == nullptr) {
1131 ALOGV("%s: Parent camera3 output stream was destroyed", __FUNCTION__);
1132 return;
1133 }
1134
1135 Mutex::Autolock l(stream->mLock);
1136 if (!(stream->mUseBufferManager)) {
1137 return;
1138 }
1139
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001140 ALOGV("Stream %d: Buffer released", stream->getId());
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001141 bool shouldFreeBuffer = false;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001142 status_t res = stream->mBufferManager->onBufferReleased(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001143 stream->getId(), stream->getStreamSetId(), stream->isMultiResolution(),
1144 &shouldFreeBuffer);
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001145 if (res != OK) {
1146 ALOGE("%s: signaling buffer release to buffer manager failed: %s (%d).", __FUNCTION__,
1147 strerror(-res), res);
1148 stream->mState = STATE_ERROR;
1149 }
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001150
1151 if (shouldFreeBuffer) {
1152 sp<GraphicBuffer> buffer;
1153 // Detach and free a buffer (when buffer goes out of scope)
1154 stream->detachBufferLocked(&buffer, /*fenceFd*/ nullptr);
1155 if (buffer.get() != nullptr) {
1156 stream->mBufferManager->notifyBufferRemoved(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001157 stream->getId(), stream->getStreamSetId(), stream->isMultiResolution());
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001158 }
1159 }
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001160}
1161
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001162void Camera3OutputStream::BufferProducerListener::onBuffersDiscarded(
1163 const std::vector<sp<GraphicBuffer>>& buffers) {
1164 sp<Camera3OutputStream> stream = mParent.promote();
1165 if (stream == nullptr) {
1166 ALOGV("%s: Parent camera3 output stream was destroyed", __FUNCTION__);
1167 return;
1168 }
1169
1170 if (buffers.size() > 0) {
1171 Mutex::Autolock l(stream->mLock);
1172 stream->onBuffersRemovedLocked(buffers);
1173 if (stream->mUseBufferManager) {
1174 stream->mBufferManager->onBuffersRemoved(stream->getId(),
Shuzhen Wang83bff122020-11-20 15:51:39 -08001175 stream->getStreamSetId(), stream->isMultiResolution(), buffers.size());
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001176 }
1177 ALOGV("Stream %d: %zu Buffers discarded.", stream->getId(), buffers.size());
1178 }
1179}
1180
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001181void Camera3OutputStream::onBuffersRemovedLocked(
1182 const std::vector<sp<GraphicBuffer>>& removedBuffers) {
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07001183 sp<Camera3StreamBufferFreedListener> callback = mBufferFreedListener.promote();
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001184 if (callback != nullptr) {
Chih-Hung Hsieh48fc6192017-08-04 14:37:31 -07001185 for (const auto& gb : removedBuffers) {
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001186 callback->onBufferFreed(mId, gb->handle);
1187 }
1188 }
1189}
1190
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001191status_t Camera3OutputStream::detachBuffer(sp<GraphicBuffer>* buffer, int* fenceFd) {
1192 Mutex::Autolock l(mLock);
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001193 return detachBufferLocked(buffer, fenceFd);
1194}
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001195
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001196status_t Camera3OutputStream::detachBufferLocked(sp<GraphicBuffer>* buffer, int* fenceFd) {
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001197 ALOGV("Stream %d: detachBuffer", getId());
1198 if (buffer == nullptr) {
1199 return BAD_VALUE;
1200 }
1201
Zhijun He125684a2015-12-26 15:07:30 -08001202 sp<Fence> fence;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001203 status_t res = mConsumer->detachNextBuffer(buffer, &fence);
Zhijun He125684a2015-12-26 15:07:30 -08001204 if (res == NO_MEMORY) {
1205 // This may rarely happen, which indicates that the released buffer was freed by other
1206 // call (e.g., attachBuffer, dequeueBuffer etc.) before reaching here. We should notify the
1207 // buffer manager that this buffer has been freed. It's not fatal, but should be avoided,
1208 // therefore log a warning.
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001209 *buffer = 0;
Zhijun He125684a2015-12-26 15:07:30 -08001210 ALOGW("%s: the released buffer has already been freed by the buffer queue!", __FUNCTION__);
1211 } else if (res != OK) {
Eino-Ville Talvalaff51b472016-06-28 15:26:19 -07001212 // Treat other errors as abandonment
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001213 if (shouldLogError(res, mState)) {
1214 ALOGE("%s: detach next buffer failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1215 }
Eino-Ville Talvalaff51b472016-06-28 15:26:19 -07001216 mState = STATE_ABANDONED;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001217 return res;
Zhijun He125684a2015-12-26 15:07:30 -08001218 }
1219
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001220 if (fenceFd != nullptr) {
1221 if (fence!= 0 && fence->isValid()) {
1222 *fenceFd = fence->dup();
1223 } else {
1224 *fenceFd = -1;
1225 }
Zhijun He125684a2015-12-26 15:07:30 -08001226 }
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001227
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -08001228 // Here we assume detachBuffer is called by buffer manager so it doesn't need to be notified
1229 checkRemovedBuffersLocked(/*notifyBufferManager*/false);
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001230 return res;
Zhijun He125684a2015-12-26 15:07:30 -08001231}
Shuzhen Wang13a69632016-01-26 09:51:07 -08001232
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001233status_t Camera3OutputStream::dropBuffers(bool dropping) {
1234 Mutex::Autolock l(mLock);
1235 mDropBuffers = dropping;
1236 return OK;
1237}
1238
Austin Borger1c1bee02023-06-01 16:51:35 -07001239const std::string& Camera3OutputStream::getPhysicalCameraId() const {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001240 Mutex::Autolock l(mLock);
1241 return physicalCameraId();
1242}
1243
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08001244status_t Camera3OutputStream::notifyBufferReleased(ANativeWindowBuffer* /*anwBuffer*/) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001245 return OK;
1246}
1247
1248bool Camera3OutputStream::isConsumerConfigurationDeferred(size_t surface_id) const {
Zhijun He5d677d12016-05-29 16:52:39 -07001249 Mutex::Autolock l(mLock);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001250
1251 if (surface_id != 0) {
Shuzhen Wang758c2152017-01-10 18:26:18 -08001252 ALOGE("%s: surface_id %zu for Camera3OutputStream should be 0!", __FUNCTION__, surface_id);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001253 }
Zhijun He5d677d12016-05-29 16:52:39 -07001254 return mConsumer == nullptr;
1255}
1256
Shuzhen Wang758c2152017-01-10 18:26:18 -08001257status_t Camera3OutputStream::setConsumers(const std::vector<sp<Surface>>& consumers) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08001258 Mutex::Autolock l(mLock);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001259 if (consumers.size() != 1) {
1260 ALOGE("%s: it's illegal to set %zu consumer surfaces!",
1261 __FUNCTION__, consumers.size());
1262 return INVALID_OPERATION;
1263 }
1264 if (consumers[0] == nullptr) {
1265 ALOGE("%s: it's illegal to set null consumer surface!", __FUNCTION__);
Zhijun He5d677d12016-05-29 16:52:39 -07001266 return INVALID_OPERATION;
1267 }
1268
1269 if (mConsumer != nullptr) {
1270 ALOGE("%s: consumer surface was already set!", __FUNCTION__);
1271 return INVALID_OPERATION;
1272 }
1273
Shuzhen Wang758c2152017-01-10 18:26:18 -08001274 mConsumer = consumers[0];
Zhijun He5d677d12016-05-29 16:52:39 -07001275 return OK;
1276}
1277
Shuzhen Wang13a69632016-01-26 09:51:07 -08001278bool Camera3OutputStream::isConsumedByHWComposer() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001279 uint64_t usage = 0;
Shuzhen Wang13a69632016-01-26 09:51:07 -08001280 status_t res = getEndpointUsage(&usage);
1281 if (res != OK) {
1282 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1283 return false;
1284 }
1285
1286 return (usage & GRALLOC_USAGE_HW_COMPOSER) != 0;
1287}
1288
Zhijun Hef0645c12016-08-02 00:58:11 -07001289bool Camera3OutputStream::isConsumedByHWTexture() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001290 uint64_t usage = 0;
Zhijun Hef0645c12016-08-02 00:58:11 -07001291 status_t res = getEndpointUsage(&usage);
1292 if (res != OK) {
1293 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1294 return false;
1295 }
1296
1297 return (usage & GRALLOC_USAGE_HW_TEXTURE) != 0;
1298}
1299
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -07001300bool Camera3OutputStream::isConsumedByCPU() const {
1301 uint64_t usage = 0;
1302 status_t res = getEndpointUsage(&usage);
1303 if (res != OK) {
1304 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1305 return false;
1306 }
1307
1308 return (usage & GRALLOC_USAGE_SW_READ_MASK) != 0;
1309}
1310
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001311void Camera3OutputStream::dumpImageToDisk(nsecs_t timestamp,
1312 ANativeWindowBuffer* anwBuffer, int fence) {
1313 // Deriver output file name
1314 std::string fileExtension = "jpg";
1315 char imageFileName[64];
1316 time_t now = time(0);
1317 tm *localTime = localtime(&now);
1318 snprintf(imageFileName, sizeof(imageFileName), "IMG_%4d%02d%02d_%02d%02d%02d_%" PRId64 ".%s",
Shuzhen Wang6a8237f2021-07-13 14:42:57 -07001319 1900 + localTime->tm_year, localTime->tm_mon + 1, localTime->tm_mday,
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001320 localTime->tm_hour, localTime->tm_min, localTime->tm_sec,
1321 timestamp, fileExtension.c_str());
1322
1323 // Lock the image for CPU read
1324 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(anwBuffer);
1325 void* mapped = nullptr;
1326 base::unique_fd fenceFd(dup(fence));
1327 status_t res = graphicBuffer->lockAsync(GraphicBuffer::USAGE_SW_READ_OFTEN, &mapped,
Emilian Peev293bd972022-08-05 17:28:06 -07001328 fenceFd.release());
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001329 if (res != OK) {
1330 ALOGE("%s: Failed to lock the buffer: %s (%d)", __FUNCTION__, strerror(-res), res);
1331 return;
1332 }
1333
1334 // Figure out actual file size
1335 auto actualJpegSize = android::camera2::JpegProcessor::findJpegSize((uint8_t*)mapped, mMaxSize);
1336 if (actualJpegSize == 0) {
1337 actualJpegSize = mMaxSize;
1338 }
1339
1340 // Output image data to file
1341 std::string filePath = "/data/misc/cameraserver/";
1342 filePath += imageFileName;
Austin Borger1c1bee02023-06-01 16:51:35 -07001343 std::ofstream imageFile(filePath, std::ofstream::binary);
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001344 if (!imageFile.is_open()) {
1345 ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
1346 graphicBuffer->unlock();
1347 return;
1348 }
1349 imageFile.write((const char*)mapped, actualJpegSize);
1350
1351 graphicBuffer->unlock();
1352}
1353
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001354status_t Camera3OutputStream::setBatchSize(size_t batchSize) {
1355 Mutex::Autolock l(mLock);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001356 if (batchSize == 0) {
1357 ALOGE("%s: invalid batch size 0", __FUNCTION__);
1358 return BAD_VALUE;
1359 }
1360
1361 if (mUseBufferManager) {
1362 ALOGE("%s: batch operation is not supported with buffer manager", __FUNCTION__);
1363 return INVALID_OPERATION;
1364 }
1365
1366 if (!isVideoStream()) {
1367 ALOGE("%s: batch operation is not supported with non-video stream", __FUNCTION__);
1368 return INVALID_OPERATION;
1369 }
1370
Shuzhen Wangc7629462021-07-12 15:02:58 -07001371 if (camera_stream::max_buffers < batchSize) {
1372 ALOGW("%s: batch size is capped by max_buffers %d", __FUNCTION__,
1373 camera_stream::max_buffers);
1374 batchSize = camera_stream::max_buffers;
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001375 }
Shuzhen Wangc7629462021-07-12 15:02:58 -07001376
1377 size_t defaultBatchSize = 1;
1378 if (!mBatchSize.compare_exchange_strong(defaultBatchSize, batchSize)) {
1379 ALOGE("%s: change batch size from %zu to %zu dynamically is not supported",
1380 __FUNCTION__, defaultBatchSize, batchSize);
1381 return INVALID_OPERATION;
1382 }
1383
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001384 return OK;
1385}
1386
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001387void Camera3OutputStream::onMinDurationChanged(nsecs_t duration, bool fixedFps) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001388 Mutex::Autolock l(mLock);
1389 mMinExpectedDuration = duration;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001390 mFixedFps = fixedFps;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001391}
1392
Shuzhen Wang16610a62022-12-15 22:38:07 -08001393void Camera3OutputStream::setStreamUseCase(int64_t streamUseCase) {
1394 Mutex::Autolock l(mLock);
1395 camera_stream::use_case = streamUseCase;
1396}
1397
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001398void Camera3OutputStream::returnPrefetchedBuffersLocked() {
Shuzhen Wangc7629462021-07-12 15:02:58 -07001399 std::vector<Surface::BatchBuffer> batchedBuffers;
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001400
Shuzhen Wangc7629462021-07-12 15:02:58 -07001401 {
1402 std::lock_guard<std::mutex> batchLock(mBatchLock);
1403 if (mBatchedBuffers.size() != 0) {
1404 ALOGW("%s: %zu extra prefetched buffers detected. Returning",
1405 __FUNCTION__, mBatchedBuffers.size());
1406 batchedBuffers = std::move(mBatchedBuffers);
1407 }
1408 }
1409
1410 if (batchedBuffers.size() > 0) {
1411 mConsumer->cancelBuffers(batchedBuffers);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001412 }
1413}
1414
Shuzhen Wang0897d592023-04-07 12:48:05 -07001415nsecs_t Camera3OutputStream::syncTimestampToDisplayLocked(nsecs_t t, int releaseFence) {
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001416 nsecs_t currentTime = systemTime();
1417 if (!mFixedFps) {
1418 mLastCaptureTime = t;
1419 mLastPresentTime = currentTime;
1420 return t;
1421 }
1422
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001423 ParcelableVsyncEventData parcelableVsyncEventData;
1424 auto res = mDisplayEventReceiver.getLatestVsyncEventData(&parcelableVsyncEventData);
1425 if (res != OK) {
1426 ALOGE("%s: Stream %d: Error getting latest vsync event data: %s (%d)",
1427 __FUNCTION__, mId, strerror(-res), res);
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001428 mLastCaptureTime = t;
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001429 mLastPresentTime = currentTime;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001430 return t;
1431 }
1432
1433 const VsyncEventData& vsyncEventData = parcelableVsyncEventData.vsync;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001434 nsecs_t minPresentT = mLastPresentTime + vsyncEventData.frameInterval / 2;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001435
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001436 // Find the best presentation time without worrying about previous frame's
1437 // presentation time if capture interval is more than kSpacingResetIntervalNs.
1438 //
1439 // When frame interval is more than 50 ms apart (3 vsyncs for 60hz refresh rate),
1440 // there is little risk in starting over and finding the earliest vsync to latch onto.
1441 // - Update captureToPresentTime offset to be used for later frames.
1442 // - Example use cases:
1443 // - when frame rate drops down to below 20 fps, or
1444 // - A new streaming session starts (stopPreview followed by
1445 // startPreview)
1446 //
Shuzhen Wang34a5e282022-06-17 14:48:35 -07001447 nsecs_t captureInterval = t - mLastCaptureTime;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001448 if (captureInterval > kSpacingResetIntervalNs) {
Rachel Lee86d90eb2023-04-25 14:37:34 -07001449 for (size_t i = 0; i < vsyncEventData.frameTimelinesLength; i++) {
Shuzhen Wang34a5e282022-06-17 14:48:35 -07001450 const auto& timeline = vsyncEventData.frameTimelines[i];
1451 if (timeline.deadlineTimestamp >= currentTime &&
1452 timeline.expectedPresentationTime > minPresentT) {
1453 nsecs_t presentT = vsyncEventData.frameTimelines[i].expectedPresentationTime;
1454 mCaptureToPresentOffset = presentT - t;
1455 mLastCaptureTime = t;
1456 mLastPresentTime = presentT;
1457
Shuzhen Wang0897d592023-04-07 12:48:05 -07001458 // If releaseFence is available, store the fence to check signal
1459 // time later.
1460 mRefVsyncData = vsyncEventData;
1461 mReferenceCaptureTime = t;
1462 mReferenceArrivalTime = currentTime;
1463 if (releaseFence != -1) {
1464 mReferenceFrameFence = new Fence(releaseFence);
1465 } else {
1466 mFenceSignalOffset = 0;
1467 }
1468
Shuzhen Wang34a5e282022-06-17 14:48:35 -07001469 // Move the expected presentation time back by 1/3 of frame interval to
1470 // mitigate the time drift. Due to time drift, if we directly use the
1471 // expected presentation time, often times 2 expected presentation time
1472 // falls into the same VSYNC interval.
1473 return presentT - vsyncEventData.frameInterval/3;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001474 }
1475 }
1476 }
1477
Shuzhen Wang0897d592023-04-07 12:48:05 -07001478 // If there is a reference frame release fence, get the signal time and
1479 // update the captureToPresentOffset.
1480 if (mReferenceFrameFence != nullptr) {
1481 mFenceSignalOffset = 0;
1482 nsecs_t signalTime = mReferenceFrameFence->getSignalTime();
1483 // Now that the fence has signaled, recalculate the offsets based on
1484 // the timeline which was actually latched
1485 if (signalTime != INT64_MAX) {
1486 for (size_t i = 0; i < mRefVsyncData.frameTimelinesLength; i++) {
1487 const auto& timeline = mRefVsyncData.frameTimelines[i];
1488 if (timeline.deadlineTimestamp >= signalTime) {
1489 nsecs_t originalOffset = mCaptureToPresentOffset;
1490 mCaptureToPresentOffset = timeline.expectedPresentationTime
1491 - mReferenceCaptureTime;
1492 mLastPresentTime = timeline.expectedPresentationTime;
1493 mFenceSignalOffset = signalTime > mReferenceArrivalTime ?
1494 signalTime - mReferenceArrivalTime : 0;
1495
1496 ALOGV("%s: Last deadline %" PRId64 " signalTime %" PRId64
1497 " original offset %" PRId64 " new offset %" PRId64
1498 " fencesignal offset %" PRId64, __FUNCTION__,
1499 timeline.deadlineTimestamp, signalTime, originalOffset,
1500 mCaptureToPresentOffset, mFenceSignalOffset);
1501 break;
1502 }
1503 }
1504 mReferenceFrameFence.clear();
1505 }
1506 }
1507
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001508 nsecs_t idealPresentT = t + mCaptureToPresentOffset;
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001509 nsecs_t expectedPresentT = mLastPresentTime;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001510 nsecs_t minDiff = INT64_MAX;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001511
1512 // In fixed FPS case, when frame durations are close to multiples of display refresh
1513 // rate, derive minimum intervals between presentation times based on minimal
Shuzhen Wang661b34f2022-05-18 22:00:19 -07001514 // expected duration. The minimum number of Vsyncs is:
1515 // - 0 if minFrameDuration in (0, 1.5] * vSyncInterval,
1516 // - 1 if minFrameDuration in (1.5, 2.5] * vSyncInterval,
1517 // - and so on.
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001518 //
1519 // This spaces out the displaying of the frames so that the frame
1520 // presentations are roughly in sync with frame captures.
Shuzhen Wang661b34f2022-05-18 22:00:19 -07001521 int minVsyncs = (mMinExpectedDuration - vsyncEventData.frameInterval / 2) /
1522 vsyncEventData.frameInterval;
1523 if (minVsyncs < 0) minVsyncs = 0;
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001524 nsecs_t minInterval = minVsyncs * vsyncEventData.frameInterval;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001525
1526 // In fixed FPS case, if the frame duration deviates from multiples of
1527 // display refresh rate, find the closest Vsync without requiring a minimum
1528 // number of Vsync.
1529 //
1530 // Example: (24fps camera, 60hz refresh):
1531 // capture readout: | t1 | t1 | .. | t1 | .. | t1 | .. | t1 |
1532 // display VSYNC: | t2 | t2 | ... | t2 | ... | t2 | ... | t2 |
1533 // | : 1 frame
1534 // t1 : 41.67ms
1535 // t2 : 16.67ms
1536 // t1/t2 = 2.5
1537 //
1538 // 24fps is a commonly used video frame rate. Because the capture
1539 // interval is 2.5 times of display refresh interval, the minVsyncs
1540 // calculation will directly fall at the boundary condition. In this case,
1541 // we should fall back to the basic logic of finding closest vsync
1542 // timestamp without worrying about minVsyncs.
1543 float captureToVsyncIntervalRatio = 1.0f * mMinExpectedDuration / vsyncEventData.frameInterval;
1544 float ratioDeviation = std::fabs(
1545 captureToVsyncIntervalRatio - std::roundf(captureToVsyncIntervalRatio));
1546 bool captureDeviateFromVsync = ratioDeviation >= kMaxIntervalRatioDeviation;
1547 bool cameraDisplayInSync = (mFixedFps && !captureDeviateFromVsync);
1548
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001549 // Find best timestamp in the vsync timelines:
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001550 // - Only use at most kMaxTimelines timelines to avoid long latency
Shuzhen Wang0897d592023-04-07 12:48:05 -07001551 // - Add an extra timeline if display fence is used
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001552 // - closest to the ideal presentation time,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001553 // - deadline timestamp is greater than the current time, and
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001554 // - For fixed FPS, if the capture interval doesn't deviate too much from refresh interval,
1555 // the candidate presentation time is at least minInterval in the future compared to last
1556 // presentation time.
1557 // - For variable FPS, or if the capture interval deviates from refresh
1558 // interval for more than 5%, find a presentation time closest to the
1559 // (lastPresentationTime + captureToPresentOffset) instead.
Shuzhen Wang0897d592023-04-07 12:48:05 -07001560 int fenceAdjustment = (mFenceSignalOffset > 0) ? 1 : 0;
1561 int maxTimelines = std::min(kMaxTimelines + fenceAdjustment,
1562 (int)vsyncEventData.frameTimelinesLength);
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001563 float biasForShortDelay = 1.0f;
1564 for (int i = 0; i < maxTimelines; i ++) {
1565 const auto& vsyncTime = vsyncEventData.frameTimelines[i];
1566 if (minVsyncs > 0) {
1567 // Bias towards using smaller timeline index:
1568 // i = 0: bias = 1
1569 // i = maxTimelines-1: bias = -1
1570 biasForShortDelay = 1.0 - 2.0 * i / (maxTimelines - 1);
1571 }
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001572 if (std::abs(vsyncTime.expectedPresentationTime - idealPresentT) < minDiff &&
Shuzhen Wang0897d592023-04-07 12:48:05 -07001573 vsyncTime.deadlineTimestamp >= currentTime + mFenceSignalOffset &&
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001574 ((!cameraDisplayInSync && vsyncTime.expectedPresentationTime > minPresentT) ||
1575 (cameraDisplayInSync && vsyncTime.expectedPresentationTime >
Kwangkyu Park1c0042b2022-12-20 00:03:17 +09001576 mLastPresentTime + minInterval +
1577 static_cast<nsecs_t>(biasForShortDelay * kTimelineThresholdNs)))) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001578 expectedPresentT = vsyncTime.expectedPresentationTime;
1579 minDiff = std::abs(vsyncTime.expectedPresentationTime - idealPresentT);
1580 }
1581 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001582
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001583 if (expectedPresentT == mLastPresentTime && expectedPresentT <
1584 vsyncEventData.frameTimelines[maxTimelines-1].expectedPresentationTime) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001585 // Couldn't find a reasonable presentation time. Using last frame's
1586 // presentation time would cause a frame drop. The best option now
1587 // is to use the next VSync as long as the last presentation time
1588 // doesn't already has the maximum latency, in which case dropping the
1589 // buffer is more desired than increasing latency.
1590 //
1591 // Example: (60fps camera, 59.9hz refresh):
1592 // capture readout: | t1 | t1 | .. | t1 | .. | t1 | .. | t1 |
1593 // \ \ \ \ \ \ \ \ \
1594 // queue to BQ: | | | | | | | | |
1595 // \ \ \ \ \ \ \ \ \
1596 // display VSYNC: | t2 | t2 | ... | t2 | ... | t2 | ... | t2 |
1597 //
1598 // |: 1 frame
1599 // t1 : 16.67ms
1600 // t2 : 16.69ms
1601 //
1602 // It takes 833 frames for capture readout count and display VSYNC count to be off
1603 // by 1.
1604 // - At frames [0, 832], presentationTime is set to timeline[0]
1605 // - At frames [833, 833*2-1], presentationTime is set to timeline[1]
1606 // - At frames [833*2, 833*3-1] presentationTime is set to timeline[2]
1607 // - At frame 833*3, no presentation time is found because we only
1608 // search for timeline[0..2].
1609 // - Drop one buffer is better than further extend the presentation
1610 // time.
1611 //
1612 // However, if frame 833*2 arrives 16.67ms early (right after frame
1613 // 833*2-1), no presentation time can be found because
1614 // getLatestVsyncEventData is called early. In that case, it's better to
1615 // set presentation time by offseting last presentation time.
1616 expectedPresentT += vsyncEventData.frameInterval;
1617 }
1618
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001619 mLastCaptureTime = t;
1620 mLastPresentTime = expectedPresentT;
1621
1622 // Move the expected presentation time back by 1/3 of frame interval to
1623 // mitigate the time drift. Due to time drift, if we directly use the
1624 // expected presentation time, often times 2 expected presentation time
1625 // falls into the same VSYNC interval.
1626 return expectedPresentT - vsyncEventData.frameInterval/3;
Shuzhen Wange4adddb2021-09-21 15:24:44 -07001627}
1628
Shuzhen Wangba92d772022-04-11 11:47:24 -07001629bool Camera3OutputStream::shouldLogError(status_t res) {
1630 Mutex::Autolock l(mLock);
1631 return shouldLogError(res, mState);
1632}
1633
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001634}; // namespace camera3
1635
1636}; // namespace android