blob: 88075d629c686a012b12c118348822c4b743f624 [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>
27
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080028#include <android-base/unique_fd.h>
Shuzhen Wange4adddb2021-09-21 15:24:44 -070029#include <cutils/properties.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080030#include <ui/GraphicBuffer.h>
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080031#include <utils/Log.h>
32#include <utils/Trace.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080033
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000034#include <common/CameraDeviceBase.h>
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -080035#include "api1/client2/JpegProcessor.h"
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080036#include "Camera3OutputStream.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070037#include "utils/TraceHFR.h"
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080038
39#ifndef container_of
40#define container_of(ptr, type, member) \
41 (type *)((char*)(ptr) - offsetof(type, member))
42#endif
43
44namespace android {
45
46namespace camera3 {
47
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000048using aidl::android::hardware::camera::device::CameraBlob;
49using aidl::android::hardware::camera::device::CameraBlobId;
50
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080051Camera3OutputStream::Camera3OutputStream(int id,
Eino-Ville Talvala727d1722015-06-09 13:44:19 -070052 sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -080053 uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -070054 android_dataspace dataSpace, camera_stream_rotation_t rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -080055 nsecs_t timestampOffset, const String8& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000056 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -080057 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -080058 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +000059 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -070060 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -080061 /*maxSize*/0, format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -080062 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -080063 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -070064 timestampBase, colorSpace),
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080065 mConsumer(consumer),
Ruchit Sharmae0711f22014-08-18 13:48:24 -040066 mTransform(0),
Zhijun He125684a2015-12-26 15:07:30 -080067 mTraceFirstBuffer(true),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080068 mUseBufferManager(false),
Zhijun He5d677d12016-05-29 16:52:39 -070069 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +000070 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -070071 mConsumerUsage(0),
Chien-Yu Chena936ac22017-10-23 15:59:49 -070072 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -080073 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000074 mDequeueBufferLatency(kDequeueLatencyBinSize),
75 mIPCTransport(transport) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080076
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080077 if (mConsumer == NULL) {
78 ALOGE("%s: Consumer is NULL!", __FUNCTION__);
79 mState = STATE_ERROR;
80 }
Zhijun He125684a2015-12-26 15:07:30 -080081
Shuzhen Wang0160ddd2019-08-15 09:11:56 -070082 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
83 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -080084}
85
86Camera3OutputStream::Camera3OutputStream(int id,
Eino-Ville Talvala727d1722015-06-09 13:44:19 -070087 sp<Surface> consumer,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -080088 uint32_t width, uint32_t height, size_t maxSize, int format,
Emilian Peevf4816702020-04-03 15:44:51 -070089 android_dataspace dataSpace, camera_stream_rotation_t rotation,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080090 nsecs_t timestampOffset, const String8& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000091 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -080092 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -080093 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +000094 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -070095 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height, maxSize,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080096 format, dataSpace, rotation, physicalCameraId, sensorPixelModesUsed,
Shuzhen Wange4208922022-02-01 16:52:48 -080097 setId, isMultiResolution, dynamicRangeProfile, streamUseCase,
Austin Borger9e2b27c2022-07-15 11:27:24 -070098 deviceTimeBaseIsRealtime, timestampBase, colorSpace),
Igor Murashkina55b5452013-04-02 16:36:33 -070099 mConsumer(consumer),
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400100 mTransform(0),
Zhijun He125684a2015-12-26 15:07:30 -0800101 mTraceFirstBuffer(true),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800102 mUseBufferManager(false),
Zhijun He5d677d12016-05-29 16:52:39 -0700103 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000104 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700105 mConsumerUsage(0),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700106 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800107 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000108 mDequeueBufferLatency(kDequeueLatencyBinSize),
109 mIPCTransport(transport) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800110
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800111 if (format != HAL_PIXEL_FORMAT_BLOB && format != HAL_PIXEL_FORMAT_RAW_OPAQUE) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800112 ALOGE("%s: Bad format for size-only stream: %d", __FUNCTION__,
113 format);
114 mState = STATE_ERROR;
115 }
116
117 if (mConsumer == NULL) {
118 ALOGE("%s: Consumer is NULL!", __FUNCTION__);
119 mState = STATE_ERROR;
120 }
Zhijun He125684a2015-12-26 15:07:30 -0800121
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700122 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
123 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800124}
125
Zhijun He5d677d12016-05-29 16:52:39 -0700126Camera3OutputStream::Camera3OutputStream(int id,
127 uint32_t width, uint32_t height, int format,
Emilian Peev050f5dc2017-05-18 14:43:56 +0100128 uint64_t consumerUsage, android_dataspace dataSpace,
Emilian Peevf4816702020-04-03 15:44:51 -0700129 camera_stream_rotation_t rotation, nsecs_t timestampOffset,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800130 const String8& physicalCameraId,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000131 const std::unordered_set<int32_t> &sensorPixelModesUsed, IPCTransport transport,
Emilian Peevc81a7592022-02-14 17:38:18 -0800132 int setId, bool isMultiResolution, int64_t dynamicRangeProfile,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800133 int64_t streamUseCase, bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000134 int mirrorMode, int32_t colorSpace, bool useReadoutTimestamp) :
Emilian Peevf4816702020-04-03 15:44:51 -0700135 Camera3IOStreamBase(id, CAMERA_STREAM_OUTPUT, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800136 /*maxSize*/0, format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -0800137 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -0800138 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -0700139 timestampBase, colorSpace),
Zhijun He5d677d12016-05-29 16:52:39 -0700140 mConsumer(nullptr),
141 mTransform(0),
142 mTraceFirstBuffer(true),
143 mUseBufferManager(false),
144 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000145 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700146 mConsumerUsage(consumerUsage),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700147 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800148 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000149 mDequeueBufferLatency(kDequeueLatencyBinSize),
150 mIPCTransport(transport) {
Zhijun He5d677d12016-05-29 16:52:39 -0700151 // Deferred consumer only support preview surface format now.
152 if (format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
153 ALOGE("%s: Deferred consumer only supports IMPLEMENTATION_DEFINED format now!",
154 __FUNCTION__);
155 mState = STATE_ERROR;
156 }
157
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400158 // Validation check for the consumer usage flag.
Zhijun He5d677d12016-05-29 16:52:39 -0700159 if ((consumerUsage & GraphicBuffer::USAGE_HW_TEXTURE) == 0 &&
160 (consumerUsage & GraphicBuffer::USAGE_HW_COMPOSER) == 0) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100161 ALOGE("%s: Deferred consumer usage flag is illegal %" PRIu64 "!",
162 __FUNCTION__, consumerUsage);
Zhijun He5d677d12016-05-29 16:52:39 -0700163 mState = STATE_ERROR;
164 }
165
166 mConsumerName = String8("Deferred");
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700167 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
168 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Zhijun He5d677d12016-05-29 16:52:39 -0700169}
170
Emilian Peevf4816702020-04-03 15:44:51 -0700171Camera3OutputStream::Camera3OutputStream(int id, camera_stream_type_t type,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700172 uint32_t width, uint32_t height,
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800173 int format,
Yin-Chia Yehb97babb2015-03-12 13:42:44 -0700174 android_dataspace dataSpace,
Emilian Peevf4816702020-04-03 15:44:51 -0700175 camera_stream_rotation_t rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800176 const String8& physicalCameraId,
Shuzhen Wange4208922022-02-01 16:52:48 -0800177 const std::unordered_set<int32_t> &sensorPixelModesUsed,
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000178 IPCTransport transport,
Emilian Peev050f5dc2017-05-18 14:43:56 +0100179 uint64_t consumerUsage, nsecs_t timestampOffset,
Emilian Peev2295df72021-11-12 18:14:10 -0800180 int setId, bool isMultiResolution,
Shuzhen Wang8ed1e872022-03-08 16:34:33 -0800181 int64_t dynamicRangeProfile, int64_t streamUseCase,
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800182 bool deviceTimeBaseIsRealtime, int timestampBase,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000183 int mirrorMode, int32_t colorSpace,
184 bool useReadoutTimestamp) :
Igor Murashkine3a9f962013-05-08 18:03:15 -0700185 Camera3IOStreamBase(id, type, width, height,
186 /*maxSize*/0,
Shuzhen Wangc28189a2017-11-27 23:05:10 -0800187 format, dataSpace, rotation,
Emilian Peev2295df72021-11-12 18:14:10 -0800188 physicalCameraId, sensorPixelModesUsed, setId, isMultiResolution,
Shuzhen Wange4208922022-02-01 16:52:48 -0800189 dynamicRangeProfile, streamUseCase, deviceTimeBaseIsRealtime,
Austin Borger9e2b27c2022-07-15 11:27:24 -0700190 timestampBase, colorSpace),
Zhijun He125684a2015-12-26 15:07:30 -0800191 mTransform(0),
192 mTraceFirstBuffer(true),
Zhijun He5d677d12016-05-29 16:52:39 -0700193 mUseBufferManager(false),
Shuzhen Wang0129d522016-10-30 22:43:41 -0700194 mTimestampOffset(timestampOffset),
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000195 mUseReadoutTime(useReadoutTimestamp),
Shuzhen Wang686f6442017-06-20 16:16:04 -0700196 mConsumerUsage(consumerUsage),
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700197 mDropBuffers(false),
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800198 mMirrorMode(mirrorMode),
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000199 mDequeueBufferLatency(kDequeueLatencyBinSize),
200 mIPCTransport(transport) {
Zhijun He125684a2015-12-26 15:07:30 -0800201
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700202 bool needsReleaseNotify = setId > CAMERA3_STREAM_SET_ID_INVALID;
203 mBufferProducerListener = new BufferProducerListener(this, needsReleaseNotify);
Igor Murashkine3a9f962013-05-08 18:03:15 -0700204
205 // Subclasses expected to initialize mConsumer themselves
206}
207
208
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800209Camera3OutputStream::~Camera3OutputStream() {
210 disconnectLocked();
211}
212
Emilian Peevf4816702020-04-03 15:44:51 -0700213status_t Camera3OutputStream::getBufferLocked(camera_stream_buffer *buffer,
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800214 const std::vector<size_t>&) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700215 ATRACE_HFR_CALL();
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800216
217 ANativeWindowBuffer* anb;
Zhijun He125684a2015-12-26 15:07:30 -0800218 int fenceFd = -1;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700219
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800220 status_t res;
221 res = getBufferLockedCommon(&anb, &fenceFd);
222 if (res != OK) {
223 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800224 }
225
Igor Murashkine3a9f962013-05-08 18:03:15 -0700226 /**
227 * FenceFD now owned by HAL except in case of error,
228 * in which case we reassign it to acquire_fence
229 */
230 handoutBufferLocked(*buffer, &(anb->handle), /*acquireFence*/fenceFd,
Emilian Peevf4816702020-04-03 15:44:51 -0700231 /*releaseFence*/-1, CAMERA_BUFFER_STATUS_OK, /*output*/true);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800232
233 return OK;
234}
235
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800236status_t Camera3OutputStream::getBuffersLocked(std::vector<OutstandingBuffer>* outBuffers) {
237 status_t res;
238
239 if ((res = getBufferPreconditionCheckLocked()) != OK) {
240 return res;
241 }
242
243 if (mUseBufferManager) {
244 ALOGE("%s: stream %d is managed by buffer manager and does not support batch operation",
245 __FUNCTION__, mId);
246 return INVALID_OPERATION;
247 }
248
249 sp<Surface> consumer = mConsumer;
250 /**
251 * Release the lock briefly to avoid deadlock for below scenario:
252 * Thread 1: StreamingProcessor::startStream -> Camera3Stream::isConfiguring().
253 * This thread acquired StreamingProcessor lock and try to lock Camera3Stream lock.
254 * Thread 2: Camera3Stream::returnBuffer->StreamingProcessor::onFrameAvailable().
255 * This thread acquired Camera3Stream lock and bufferQueue lock, and try to lock
256 * StreamingProcessor lock.
257 * Thread 3: Camera3Stream::getBuffer(). This thread acquired Camera3Stream lock
258 * and try to lock bufferQueue lock.
259 * Then there is circular locking dependency.
260 */
261 mLock.unlock();
262
263 size_t numBuffersRequested = outBuffers->size();
264 std::vector<Surface::BatchBuffer> buffers(numBuffersRequested);
265
266 nsecs_t dequeueStart = systemTime(SYSTEM_TIME_MONOTONIC);
267 res = consumer->dequeueBuffers(&buffers);
268 nsecs_t dequeueEnd = systemTime(SYSTEM_TIME_MONOTONIC);
269 mDequeueBufferLatency.add(dequeueStart, dequeueEnd);
270
271 mLock.lock();
272
273 if (res != OK) {
274 if (shouldLogError(res, mState)) {
275 ALOGE("%s: Stream %d: Can't dequeue %zu output buffers: %s (%d)",
276 __FUNCTION__, mId, numBuffersRequested, strerror(-res), res);
277 }
278 checkRetAndSetAbandonedLocked(res);
279 return res;
280 }
281 checkRemovedBuffersLocked();
282
283 /**
284 * FenceFD now owned by HAL except in case of error,
285 * in which case we reassign it to acquire_fence
286 */
287 for (size_t i = 0; i < numBuffersRequested; i++) {
288 handoutBufferLocked(*(outBuffers->at(i).outBuffer),
289 &(buffers[i].buffer->handle), /*acquireFence*/buffers[i].fenceFd,
290 /*releaseFence*/-1, CAMERA_BUFFER_STATUS_OK, /*output*/true);
291 }
292 return OK;
293}
294
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800295status_t Camera3OutputStream::queueBufferToConsumer(sp<ANativeWindow>& consumer,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700296 ANativeWindowBuffer* buffer, int anwReleaseFence,
297 const std::vector<size_t>&) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800298 return consumer->queueBuffer(consumer.get(), buffer, anwReleaseFence);
299}
300
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800301status_t Camera3OutputStream::returnBufferLocked(
Emilian Peevf4816702020-04-03 15:44:51 -0700302 const camera_stream_buffer &buffer,
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700303 nsecs_t timestamp, nsecs_t readoutTimestamp,
304 int32_t transform, const std::vector<size_t>& surface_ids) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700305 ATRACE_HFR_CALL();
Igor Murashkine3a9f962013-05-08 18:03:15 -0700306
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800307 if (mHandoutTotalBufferCount == 1) {
308 returnPrefetchedBuffersLocked();
309 }
310
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700311 status_t res = returnAnyBufferLocked(buffer, timestamp, readoutTimestamp,
312 /*output*/true, transform, surface_ids);
Igor Murashkine3a9f962013-05-08 18:03:15 -0700313
314 if (res != OK) {
315 return res;
316 }
317
318 mLastTimestamp = timestamp;
Eino-Ville Talvalac31dc7e2017-01-31 17:35:41 -0800319 mFrameCount++;
Igor Murashkine3a9f962013-05-08 18:03:15 -0700320
321 return OK;
322}
323
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000324status_t Camera3OutputStream::fixUpHidlJpegBlobHeader(ANativeWindowBuffer* anwBuffer, int fence) {
325 // Lock the JPEG buffer for CPU read
326 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(anwBuffer);
327 void* mapped = nullptr;
328 base::unique_fd fenceFd(dup(fence));
329 // Use USAGE_SW_WRITE_RARELY since we're going to re-write the CameraBlob
330 // header.
331 GraphicBufferLocker gbLocker(graphicBuffer);
332 status_t res =
333 gbLocker.lockAsync(
334 GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_RARELY,
Emilian Peev293bd972022-08-05 17:28:06 -0700335 &mapped, fenceFd.release());
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000336 if (res != OK) {
337 ALOGE("%s: Failed to lock the buffer: %s (%d)", __FUNCTION__, strerror(-res), res);
338 return res;
339 }
340
341 uint8_t *hidlHeaderStart =
342 static_cast<uint8_t*>(mapped) + graphicBuffer->getWidth() - sizeof(camera_jpeg_blob_t);
343 // Check that the jpeg buffer is big enough to contain HIDL camera blob
344 if (hidlHeaderStart < static_cast<uint8_t *>(mapped)) {
345 ALOGE("%s, jpeg buffer not large enough to fit HIDL camera blob %" PRIu32, __FUNCTION__,
346 graphicBuffer->getWidth());
347 return BAD_VALUE;
348 }
349 camera_jpeg_blob_t *hidlBlobHeader = reinterpret_cast<camera_jpeg_blob_t *>(hidlHeaderStart);
350
351 // Check that the blob is indeed the jpeg blob id.
352 if (hidlBlobHeader->jpeg_blob_id != CAMERA_JPEG_BLOB_ID) {
353 ALOGE("%s, jpeg blob id %d is not correct", __FUNCTION__, hidlBlobHeader->jpeg_blob_id);
354 return BAD_VALUE;
355 }
356
357 // Retrieve id and blob size
358 CameraBlobId blobId = static_cast<CameraBlobId>(hidlBlobHeader->jpeg_blob_id);
359 uint32_t blobSizeBytes = hidlBlobHeader->jpeg_size;
360
361 if (blobSizeBytes > (graphicBuffer->getWidth() - sizeof(camera_jpeg_blob_t))) {
362 ALOGE("%s, blobSize in HIDL jpeg blob : %d is corrupt, buffer size %" PRIu32, __FUNCTION__,
363 blobSizeBytes, graphicBuffer->getWidth());
364 }
365
366 uint8_t *aidlHeaderStart =
367 static_cast<uint8_t*>(mapped) + graphicBuffer->getWidth() - sizeof(CameraBlob);
368
369 // Check that the jpeg buffer is big enough to contain AIDL camera blob
370 if (aidlHeaderStart < static_cast<uint8_t *>(mapped)) {
371 ALOGE("%s, jpeg buffer not large enough to fit AIDL camera blob %" PRIu32, __FUNCTION__,
372 graphicBuffer->getWidth());
373 return BAD_VALUE;
374 }
375
376 if (static_cast<uint8_t*>(mapped) + blobSizeBytes > aidlHeaderStart) {
377 ALOGE("%s, jpeg blob with size %d , buffer size %" PRIu32 " not large enough to fit"
378 " AIDL camera blob without corrupting jpeg", __FUNCTION__, blobSizeBytes,
379 graphicBuffer->getWidth());
380 return BAD_VALUE;
381 }
382
383 // Fill in JPEG header
Avichal Rakesh51af0702022-05-26 22:58:03 +0000384 CameraBlob aidlHeader = {
385 .blobId = blobId,
386 .blobSizeBytes = static_cast<int32_t>(blobSizeBytes)
387 };
388 memcpy(aidlHeaderStart, &aidlHeader, sizeof(CameraBlob));
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000389 graphicBuffer->unlock();
390 return OK;
391}
392
Igor Murashkine3a9f962013-05-08 18:03:15 -0700393status_t Camera3OutputStream::returnBufferCheckedLocked(
Emilian Peevf4816702020-04-03 15:44:51 -0700394 const camera_stream_buffer &buffer,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700395 nsecs_t timestamp,
Shuzhen Wang90708ea2021-11-04 11:40:49 -0700396 nsecs_t readoutTimestamp,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700397 bool output,
Emilian Peev5104fe92021-10-21 14:27:09 -0700398 int32_t transform,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -0700399 const std::vector<size_t>& surface_ids,
Igor Murashkine3a9f962013-05-08 18:03:15 -0700400 /*out*/
401 sp<Fence> *releaseFenceOut) {
402
403 (void)output;
404 ALOG_ASSERT(output, "Expected output to be true");
405
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800406 status_t res;
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700407
Yin-Chia Yeh4c9736f2015-03-05 15:01:36 -0800408 // Fence management - always honor release fence from HAL
409 sp<Fence> releaseFence = new Fence(buffer.release_fence);
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700410 int anwReleaseFence = releaseFence->dup();
411
412 /**
Zhijun He124ccf42013-05-22 14:01:30 -0700413 * Release the lock briefly to avoid deadlock with
414 * StreamingProcessor::startStream -> Camera3Stream::isConfiguring (this
415 * thread will go into StreamingProcessor::onFrameAvailable) during
416 * queueBuffer
417 */
418 sp<ANativeWindow> currentConsumer = mConsumer;
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700419 StreamState state = mState;
Zhijun He124ccf42013-05-22 14:01:30 -0700420 mLock.unlock();
421
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800422 ANativeWindowBuffer *anwBuffer = container_of(buffer.buffer, ANativeWindowBuffer, handle);
Shuzhen Wangc2352702022-09-06 18:36:31 -0700423 bool bufferDeferred = false;
Zhijun He124ccf42013-05-22 14:01:30 -0700424 /**
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700425 * Return buffer back to ANativeWindow
426 */
Emilian Peevf4816702020-04-03 15:44:51 -0700427 if (buffer.status == CAMERA_BUFFER_STATUS_ERROR || mDropBuffers || timestamp == 0) {
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700428 // Cancel buffer
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700429 if (mDropBuffers) {
430 ALOGV("%s: Dropping a frame for stream %d.", __FUNCTION__, mId);
Emilian Peevf4816702020-04-03 15:44:51 -0700431 } else if (buffer.status == CAMERA_BUFFER_STATUS_ERROR) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700432 ALOGV("%s: A frame is dropped for stream %d due to buffer error.", __FUNCTION__, mId);
Shuzhen Wangf0c4a6b2018-09-05 09:36:14 -0700433 } else {
434 ALOGE("%s: Stream %d: timestamp shouldn't be 0", __FUNCTION__, mId);
Chien-Yu Chena936ac22017-10-23 15:59:49 -0700435 }
436
Zhijun He124ccf42013-05-22 14:01:30 -0700437 res = currentConsumer->cancelBuffer(currentConsumer.get(),
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800438 anwBuffer,
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700439 anwReleaseFence);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700440 if (shouldLogError(res, state)) {
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700441 ALOGE("%s: Stream %d: Error cancelling buffer to native window:"
Igor Murashkine3a9f962013-05-08 18:03:15 -0700442 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700443 }
Zhijun He1ff811b2016-01-26 14:39:51 -0800444
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800445 notifyBufferReleased(anwBuffer);
Zhijun He1ff811b2016-01-26 14:39:51 -0800446 if (mUseBufferManager) {
447 // Return this buffer back to buffer manager.
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700448 mBufferProducerListener->onBufferReleased();
Zhijun He1ff811b2016-01-26 14:39:51 -0800449 }
Igor Murashkin5a1798a2013-05-07 10:58:13 -0700450 } else {
Emilian Peevf4816702020-04-03 15:44:51 -0700451 if (mTraceFirstBuffer && (stream_type == CAMERA_STREAM_OUTPUT)) {
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400452 {
453 char traceLog[48];
454 snprintf(traceLog, sizeof(traceLog), "Stream %d: first full buffer\n", mId);
455 ATRACE_NAME(traceLog);
456 }
457 mTraceFirstBuffer = false;
458 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +0000459 // Fix CameraBlob id type discrepancy between HIDL and AIDL, details : http://b/229688810
460 if (getFormat() == HAL_PIXEL_FORMAT_BLOB && getDataSpace() == HAL_DATASPACE_V0_JFIF) {
461 if (mIPCTransport == IPCTransport::HIDL) {
462 fixUpHidlJpegBlobHeader(anwBuffer, anwReleaseFence);
463 }
464 // If this is a JPEG output, and image dump mask is set, save image to
465 // disk.
466 if (mImageDumpMask) {
467 dumpImageToDisk(timestamp, anwBuffer, anwReleaseFence);
468 }
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -0800469 }
Yin-Chia Yeh4c9736f2015-03-05 15:01:36 -0800470
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000471 nsecs_t captureTime = ((mUseReadoutTime || mSyncToDisplay) && readoutTimestamp != 0 ?
Shuzhen Wangffc4c012022-04-20 15:55:46 -0700472 readoutTimestamp : timestamp) - mTimestampOffset;
Shuzhen Wangba92d772022-04-11 11:47:24 -0700473 if (mPreviewFrameSpacer != nullptr) {
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700474 nsecs_t readoutTime = (readoutTimestamp != 0 ? readoutTimestamp : timestamp)
475 - mTimestampOffset;
476 res = mPreviewFrameSpacer->queuePreviewBuffer(captureTime, readoutTime,
477 transform, anwBuffer, anwReleaseFence);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700478 if (res != OK) {
479 ALOGE("%s: Stream %d: Error queuing buffer to preview buffer spacer: %s (%d)",
480 __FUNCTION__, mId, strerror(-res), res);
481 return res;
482 }
Shuzhen Wangc2352702022-09-06 18:36:31 -0700483 bufferDeferred = true;
Shuzhen Wangba92d772022-04-11 11:47:24 -0700484 } else {
Shuzhen Wangba92d772022-04-11 11:47:24 -0700485 nsecs_t presentTime = mSyncToDisplay ?
486 syncTimestampToDisplayLocked(captureTime) : captureTime;
Emilian Peev2295df72021-11-12 18:14:10 -0800487
Shuzhen Wangba92d772022-04-11 11:47:24 -0700488 setTransform(transform, true/*mayChangeMirror*/);
489 res = native_window_set_buffers_timestamp(mConsumer.get(), presentTime);
490 if (res != OK) {
491 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
492 __FUNCTION__, mId, strerror(-res), res);
493 return res;
494 }
Emilian Peev2295df72021-11-12 18:14:10 -0800495
Shuzhen Wangba92d772022-04-11 11:47:24 -0700496 queueHDRMetadata(anwBuffer->handle, currentConsumer, dynamic_range_profile);
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800497
Shuzhen Wangba92d772022-04-11 11:47:24 -0700498 res = queueBufferToConsumer(currentConsumer, anwBuffer, anwReleaseFence, surface_ids);
499 if (shouldLogError(res, state)) {
500 ALOGE("%s: Stream %d: Error queueing buffer to native window:"
501 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
502 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800503 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800504 }
Zhijun He124ccf42013-05-22 14:01:30 -0700505 mLock.lock();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700506
Shuzhen Wangc2352702022-09-06 18:36:31 -0700507 if (bufferDeferred) {
508 mCachedOutputBufferCount++;
509 }
510
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700511 // Once a valid buffer has been returned to the queue, can no longer
512 // dequeue all buffers for preallocation.
Emilian Peevf4816702020-04-03 15:44:51 -0700513 if (buffer.status != CAMERA_BUFFER_STATUS_ERROR) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700514 mStreamUnpreparable = true;
515 }
516
Igor Murashkine3a9f962013-05-08 18:03:15 -0700517 *releaseFenceOut = releaseFence;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800518
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700519 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800520}
521
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800522void Camera3OutputStream::dump(int fd, const Vector<String16> &args) const {
523 (void) args;
524 String8 lines;
525 lines.appendFormat(" Stream[%d]: Output\n", mId);
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700526 lines.appendFormat(" Consumer name: %s\n", mConsumerName.string());
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800527 write(fd, lines.string(), lines.size());
Igor Murashkine3a9f962013-05-08 18:03:15 -0700528
529 Camera3IOStreamBase::dump(fd, args);
Shuzhen Wang686f6442017-06-20 16:16:04 -0700530
531 mDequeueBufferLatency.dump(fd,
532 " DequeueBuffer latency histogram:");
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800533}
534
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800535status_t Camera3OutputStream::setTransform(int transform, bool mayChangeMirror) {
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800536 ATRACE_CALL();
537 Mutex::Autolock l(mLock);
Shuzhen Wang610d7b82022-02-08 14:37:22 -0800538 if (mMirrorMode != OutputConfiguration::MIRROR_MODE_AUTO && mayChangeMirror) {
539 // If the mirroring mode is not AUTO, do not allow transform update
540 // which may change mirror.
541 return OK;
542 }
543
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800544 return setTransformLocked(transform);
545}
546
547status_t Camera3OutputStream::setTransformLocked(int transform) {
548 status_t res = OK;
Shuzhen Wange4adddb2021-09-21 15:24:44 -0700549
550 if (transform == -1) return res;
551
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800552 if (mState == STATE_ERROR) {
553 ALOGE("%s: Stream in error state", __FUNCTION__);
554 return INVALID_OPERATION;
555 }
556
557 mTransform = transform;
558 if (mState == STATE_CONFIGURED) {
559 res = native_window_set_buffers_transform(mConsumer.get(),
560 transform);
561 if (res != OK) {
562 ALOGE("%s: Unable to configure stream transform to %x: %s (%d)",
563 __FUNCTION__, transform, strerror(-res), res);
564 }
565 }
566 return res;
567}
568
569status_t Camera3OutputStream::configureQueueLocked() {
570 status_t res;
571
Ruchit Sharmae0711f22014-08-18 13:48:24 -0400572 mTraceFirstBuffer = true;
Igor Murashkine3a9f962013-05-08 18:03:15 -0700573 if ((res = Camera3IOStreamBase::configureQueueLocked()) != OK) {
574 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800575 }
576
Shuzhen Wangba92d772022-04-11 11:47:24 -0700577 if ((res = configureConsumerQueueLocked(true /*allowPreviewRespace*/)) != OK) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700578 return res;
579 }
580
581 // Set dequeueBuffer/attachBuffer timeout if the consumer is not hw composer or hw texture.
582 // We need skip these cases as timeout will disable the non-blocking (async) mode.
583 if (!(isConsumedByHWComposer() || isConsumedByHWTexture())) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800584 if (mUseBufferManager) {
585 // When buffer manager is handling the buffer, we should have available buffers in
586 // buffer queue before we calls into dequeueBuffer because buffer manager is tracking
587 // free buffers.
588 // There are however some consumer side feature (ImageReader::discardFreeBuffers) that
589 // can discard free buffers without notifying buffer manager. We want the timeout to
590 // happen immediately here so buffer manager can try to update its internal state and
591 // try to allocate a buffer instead of waiting.
592 mConsumer->setDequeueTimeout(0);
593 } else {
594 mConsumer->setDequeueTimeout(kDequeueBufferTimeout);
595 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700596 }
597
598 return OK;
599}
600
Shuzhen Wangba92d772022-04-11 11:47:24 -0700601status_t Camera3OutputStream::configureConsumerQueueLocked(bool allowPreviewRespace) {
Shuzhen Wang0129d522016-10-30 22:43:41 -0700602 status_t res;
603
604 mTraceFirstBuffer = true;
605
Igor Murashkine3a9f962013-05-08 18:03:15 -0700606 ALOG_ASSERT(mConsumer != 0, "mConsumer should never be NULL");
607
Zhijun He125684a2015-12-26 15:07:30 -0800608 // Configure consumer-side ANativeWindow interface. The listener may be used
609 // to notify buffer manager (if it is used) of the returned buffers.
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700610 res = mConsumer->connect(NATIVE_WINDOW_API_CAMERA,
Shuzhen Wang0160ddd2019-08-15 09:11:56 -0700611 /*reportBufferRemoval*/true,
612 /*listener*/mBufferProducerListener);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800613 if (res != OK) {
614 ALOGE("%s: Unable to connect to native window for stream %d",
615 __FUNCTION__, mId);
616 return res;
617 }
618
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700619 mConsumerName = mConsumer->getConsumerName();
620
Emilian Peev050f5dc2017-05-18 14:43:56 +0100621 res = native_window_set_usage(mConsumer.get(), mUsage);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800622 if (res != OK) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100623 ALOGE("%s: Unable to configure usage %" PRIu64 " for stream %d",
624 __FUNCTION__, mUsage, mId);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800625 return res;
626 }
627
628 res = native_window_set_scaling_mode(mConsumer.get(),
629 NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
630 if (res != OK) {
631 ALOGE("%s: Unable to configure stream scaling: %s (%d)",
632 __FUNCTION__, strerror(-res), res);
633 return res;
634 }
635
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800636 if (mMaxSize == 0) {
637 // For buffers of known size
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700638 res = native_window_set_buffers_dimensions(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700639 camera_stream::width, camera_stream::height);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800640 } else {
641 // For buffers with bounded size
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700642 res = native_window_set_buffers_dimensions(mConsumer.get(),
643 mMaxSize, 1);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800644 }
645 if (res != OK) {
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700646 ALOGE("%s: Unable to configure stream buffer dimensions"
647 " %d x %d (maxSize %zu) for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700648 __FUNCTION__, camera_stream::width, camera_stream::height,
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700649 mMaxSize, mId);
650 return res;
651 }
652 res = native_window_set_buffers_format(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700653 camera_stream::format);
Eino-Ville Talvala7d70c5e2014-07-24 18:10:23 -0700654 if (res != OK) {
655 ALOGE("%s: Unable to configure stream buffer format %#x for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700656 __FUNCTION__, camera_stream::format, mId);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800657 return res;
658 }
659
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800660 res = native_window_set_buffers_data_space(mConsumer.get(),
Emilian Peevf4816702020-04-03 15:44:51 -0700661 camera_stream::data_space);
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800662 if (res != OK) {
663 ALOGE("%s: Unable to configure stream dataspace %#x for stream %d",
Emilian Peevf4816702020-04-03 15:44:51 -0700664 __FUNCTION__, camera_stream::data_space, mId);
Eino-Ville Talvala3d82c0d2015-02-23 15:19:19 -0800665 return res;
666 }
667
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800668 int maxConsumerBuffers;
Eino-Ville Talvala727d1722015-06-09 13:44:19 -0700669 res = static_cast<ANativeWindow*>(mConsumer.get())->query(
670 mConsumer.get(),
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800671 NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &maxConsumerBuffers);
672 if (res != OK) {
673 ALOGE("%s: Unable to query consumer undequeued"
674 " buffer count for stream %d", __FUNCTION__, mId);
675 return res;
676 }
677
Alex Ray20cb3002013-05-28 20:18:22 -0700678 ALOGV("%s: Consumer wants %d buffers, HAL wants %d", __FUNCTION__,
Emilian Peevf4816702020-04-03 15:44:51 -0700679 maxConsumerBuffers, camera_stream::max_buffers);
680 if (camera_stream::max_buffers == 0) {
Zhijun He2ab500c2013-07-23 08:02:53 -0700681 ALOGE("%s: Camera HAL requested max_buffer count: %d, requires at least 1",
Emilian Peevf4816702020-04-03 15:44:51 -0700682 __FUNCTION__, camera_stream::max_buffers);
Alex Ray20cb3002013-05-28 20:18:22 -0700683 return INVALID_OPERATION;
684 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800685
Emilian Peevf4816702020-04-03 15:44:51 -0700686 mTotalBufferCount = maxConsumerBuffers + camera_stream::max_buffers;
Shuzhen Wange4208922022-02-01 16:52:48 -0800687
688 int timestampBase = getTimestampBase();
689 bool isDefaultTimeBase = (timestampBase ==
690 OutputConfiguration::TIMESTAMP_BASE_DEFAULT);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700691 if (allowPreviewRespace) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800692 bool forceChoreographer = (timestampBase ==
693 OutputConfiguration::TIMESTAMP_BASE_CHOREOGRAPHER_SYNCED);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700694 bool defaultToChoreographer = (isDefaultTimeBase &&
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700695 isConsumedByHWComposer());
696 bool defaultToSpacer = (isDefaultTimeBase &&
697 isConsumedByHWTexture() &&
698 !isConsumedByCPU() &&
699 !isVideoStream());
Shuzhen Wange4208922022-02-01 16:52:48 -0800700 if (forceChoreographer || defaultToChoreographer) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800701 mSyncToDisplay = true;
Shuzhen Wangc2352702022-09-06 18:36:31 -0700702 // For choreographer synced stream, extra buffers aren't kept by
703 // camera service. So no need to update mMaxCachedBufferCount.
Shuzhen Wang00abbeb2022-02-25 17:14:42 -0800704 mTotalBufferCount += kDisplaySyncExtraBuffer;
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -0700705 } else if (defaultToSpacer) {
Shuzhen Wangdc9aa822022-05-16 10:04:17 -0700706 mPreviewFrameSpacer = new PreviewFrameSpacer(this, mConsumer);
Shuzhen Wangc2352702022-09-06 18:36:31 -0700707 // For preview frame spacer, the extra buffer is kept by camera
708 // service. So update mMaxCachedBufferCount.
709 mMaxCachedBufferCount = 1;
710 mTotalBufferCount += mMaxCachedBufferCount;
Shuzhen Wangba92d772022-04-11 11:47:24 -0700711 res = mPreviewFrameSpacer->run(String8::format("PreviewSpacer-%d", mId).string());
712 if (res != OK) {
Austin Borger7b129542022-06-09 13:23:06 -0700713 ALOGE("%s: Unable to start preview spacer: %s (%d)", __FUNCTION__,
714 strerror(-res), res);
Shuzhen Wangba92d772022-04-11 11:47:24 -0700715 return res;
716 }
Shuzhen Wange4adddb2021-09-21 15:24:44 -0700717 }
718 }
Zhijun He6adc9cc2014-04-15 14:09:55 -0700719 mHandoutTotalBufferCount = 0;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800720 mFrameCount = 0;
721 mLastTimestamp = 0;
Shuzhen Wange4208922022-02-01 16:52:48 -0800722
723 if (isDeviceTimeBaseRealtime()) {
724 if (isDefaultTimeBase && !isConsumedByHWComposer() && !isVideoStream()) {
725 // Default time base, but not hardware composer or video encoder
726 mTimestampOffset = 0;
727 } else if (timestampBase == OutputConfiguration::TIMESTAMP_BASE_REALTIME ||
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000728 timestampBase == OutputConfiguration::TIMESTAMP_BASE_SENSOR) {
Shuzhen Wange4208922022-02-01 16:52:48 -0800729 mTimestampOffset = 0;
730 }
731 // If timestampBase is CHOREOGRAPHER SYNCED or MONOTONIC, leave
732 // timestamp offset as bootTime - monotonicTime.
733 } else {
734 if (timestampBase == OutputConfiguration::TIMESTAMP_BASE_REALTIME) {
735 // Reverse offset for monotonicTime -> bootTime
736 mTimestampOffset = -mTimestampOffset;
737 } else {
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000738 // If timestampBase is DEFAULT, MONOTONIC, SENSOR or
Shuzhen Wange4208922022-02-01 16:52:48 -0800739 // CHOREOGRAPHER_SYNCED, timestamp offset is 0.
740 mTimestampOffset = 0;
741 }
742 }
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800743
744 res = native_window_set_buffer_count(mConsumer.get(),
745 mTotalBufferCount);
746 if (res != OK) {
747 ALOGE("%s: Unable to set buffer count for stream %d",
748 __FUNCTION__, mId);
749 return res;
750 }
751
752 res = native_window_set_buffers_transform(mConsumer.get(),
753 mTransform);
754 if (res != OK) {
755 ALOGE("%s: Unable to configure stream transform to %x: %s (%d)",
756 __FUNCTION__, mTransform, strerror(-res), res);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700757 return res;
Zhijun Hef0645c12016-08-02 00:58:11 -0700758 }
759
Zhijun He125684a2015-12-26 15:07:30 -0800760 /**
Zhijun Heedd41ae2016-02-03 14:45:53 -0800761 * Camera3 Buffer manager is only supported by HAL3.3 onwards, as the older HALs requires
Zhijun He125684a2015-12-26 15:07:30 -0800762 * buffers to be statically allocated for internal static buffer registration, while the
763 * buffers provided by buffer manager are really dynamically allocated. Camera3Device only
Zhijun Heedd41ae2016-02-03 14:45:53 -0800764 * sets the mBufferManager if device version is > HAL3.2, which guarantees that the buffer
765 * manager setup is skipped in below code. Note that HAL3.2 is also excluded here, as some
766 * HAL3.2 devices may not support the dynamic buffer registeration.
Yin-Chia Yehb6578902019-04-16 13:36:16 -0700767 * Also Camera3BufferManager does not support display/texture streams as they have its own
768 * buffer management logic.
Zhijun He125684a2015-12-26 15:07:30 -0800769 */
Yin-Chia Yehb6578902019-04-16 13:36:16 -0700770 if (mBufferManager != 0 && mSetId > CAMERA3_STREAM_SET_ID_INVALID &&
771 !(isConsumedByHWComposer() || isConsumedByHWTexture())) {
Emilian Peev050f5dc2017-05-18 14:43:56 +0100772 uint64_t consumerUsage = 0;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700773 getEndpointUsage(&consumerUsage);
Shuzhen Wang83bff122020-11-20 15:51:39 -0800774 uint32_t width = (mMaxSize == 0) ? getWidth() : mMaxSize;
775 uint32_t height = (mMaxSize == 0) ? getHeight() : 1;
Zhijun He125684a2015-12-26 15:07:30 -0800776 StreamInfo streamInfo(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800777 getId(), getStreamSetId(), width, height, getFormat(), getDataSpace(),
Emilian Peev050f5dc2017-05-18 14:43:56 +0100778 mUsage | consumerUsage, mTotalBufferCount,
Shuzhen Wang83bff122020-11-20 15:51:39 -0800779 /*isConfigured*/true, isMultiResolution());
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -0700780 wp<Camera3OutputStream> weakThis(this);
781 res = mBufferManager->registerStream(weakThis,
782 streamInfo);
Zhijun He125684a2015-12-26 15:07:30 -0800783 if (res == OK) {
784 // Disable buffer allocation for this BufferQueue, buffer manager will take over
785 // the buffer allocation responsibility.
786 mConsumer->getIGraphicBufferProducer()->allowAllocation(false);
787 mUseBufferManager = true;
788 } else {
789 ALOGE("%s: Unable to register stream %d to camera3 buffer manager, "
790 "(error %d %s), fall back to BufferQueue for buffer management!",
791 __FUNCTION__, mId, res, strerror(-res));
792 }
793 }
794
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800795 return OK;
796}
797
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800798status_t Camera3OutputStream::getBufferLockedCommon(ANativeWindowBuffer** anb, int* fenceFd) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -0700799 ATRACE_HFR_CALL();
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800800 status_t res;
801
802 if ((res = getBufferPreconditionCheckLocked()) != OK) {
803 return res;
804 }
805
806 bool gotBufferFromManager = false;
807
808 if (mUseBufferManager) {
809 sp<GraphicBuffer> gb;
Shuzhen Wang83bff122020-11-20 15:51:39 -0800810 res = mBufferManager->getBufferForStream(getId(), getStreamSetId(),
811 isMultiResolution(), &gb, fenceFd);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800812 if (res == OK) {
813 // Attach this buffer to the bufferQueue: the buffer will be in dequeue state after a
814 // successful return.
815 *anb = gb.get();
816 res = mConsumer->attachBuffer(*anb);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700817 if (shouldLogError(res, mState)) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800818 ALOGE("%s: Stream %d: Can't attach the output buffer to this surface: %s (%d)",
819 __FUNCTION__, mId, strerror(-res), res);
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700820 }
821 if (res != OK) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800822 checkRetAndSetAbandonedLocked(res);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800823 return res;
824 }
825 gotBufferFromManager = true;
826 ALOGV("Stream %d: Attached new buffer", getId());
827 } else if (res == ALREADY_EXISTS) {
828 // Have sufficient free buffers already attached, can just
829 // dequeue from buffer queue
830 ALOGV("Stream %d: Reusing attached buffer", getId());
831 gotBufferFromManager = false;
832 } else if (res != OK) {
833 ALOGE("%s: Stream %d: Can't get next output buffer from buffer manager: %s (%d)",
834 __FUNCTION__, mId, strerror(-res), res);
835 return res;
836 }
837 }
838 if (!gotBufferFromManager) {
839 /**
840 * Release the lock briefly to avoid deadlock for below scenario:
841 * Thread 1: StreamingProcessor::startStream -> Camera3Stream::isConfiguring().
842 * This thread acquired StreamingProcessor lock and try to lock Camera3Stream lock.
843 * Thread 2: Camera3Stream::returnBuffer->StreamingProcessor::onFrameAvailable().
844 * This thread acquired Camera3Stream lock and bufferQueue lock, and try to lock
845 * StreamingProcessor lock.
846 * Thread 3: Camera3Stream::getBuffer(). This thread acquired Camera3Stream lock
847 * and try to lock bufferQueue lock.
848 * Then there is circular locking dependency.
849 */
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800850 sp<Surface> consumer = mConsumer;
Shuzhen Wang6c14e312021-07-05 16:20:33 -0700851 size_t remainingBuffers = (mState == STATE_PREPARING ? mTotalBufferCount :
852 camera_stream::max_buffers) - mHandoutTotalBufferCount;
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800853 mLock.unlock();
854
Shuzhen Wang686f6442017-06-20 16:16:04 -0700855 nsecs_t dequeueStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800856
Shuzhen Wangc7629462021-07-12 15:02:58 -0700857 size_t batchSize = mBatchSize.load();
858 if (batchSize == 1) {
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800859 sp<ANativeWindow> anw = consumer;
860 res = anw->dequeueBuffer(anw.get(), anb, fenceFd);
861 } else {
Shuzhen Wangc7629462021-07-12 15:02:58 -0700862 std::unique_lock<std::mutex> batchLock(mBatchLock);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800863 res = OK;
864 if (mBatchedBuffers.size() == 0) {
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800865 if (remainingBuffers == 0) {
866 ALOGE("%s: cannot get buffer while all buffers are handed out", __FUNCTION__);
867 return INVALID_OPERATION;
868 }
869 if (batchSize > remainingBuffers) {
870 batchSize = remainingBuffers;
871 }
Shuzhen Wangc7629462021-07-12 15:02:58 -0700872 batchLock.unlock();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800873 // Refill batched buffers
Shuzhen Wangc7629462021-07-12 15:02:58 -0700874 std::vector<Surface::BatchBuffer> batchedBuffers;
875 batchedBuffers.resize(batchSize);
876 res = consumer->dequeueBuffers(&batchedBuffers);
877 batchLock.lock();
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800878 if (res != OK) {
879 ALOGE("%s: batch dequeueBuffers call failed! %s (%d)",
880 __FUNCTION__, strerror(-res), res);
Shuzhen Wangc7629462021-07-12 15:02:58 -0700881 } else {
882 mBatchedBuffers = std::move(batchedBuffers);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800883 }
884 }
885
886 if (res == OK) {
887 // Dispatch batch buffers
888 *anb = mBatchedBuffers.back().buffer;
889 *fenceFd = mBatchedBuffers.back().fenceFd;
890 mBatchedBuffers.pop_back();
891 }
892 }
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800893
Shuzhen Wang686f6442017-06-20 16:16:04 -0700894 nsecs_t dequeueEnd = systemTime(SYSTEM_TIME_MONOTONIC);
895 mDequeueBufferLatency.add(dequeueStart, dequeueEnd);
896
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800897 mLock.lock();
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800898
899 if (mUseBufferManager && res == TIMED_OUT) {
900 checkRemovedBuffersLocked();
901
902 sp<GraphicBuffer> gb;
903 res = mBufferManager->getBufferForStream(
Shuzhen Wang83bff122020-11-20 15:51:39 -0800904 getId(), getStreamSetId(), isMultiResolution(),
905 &gb, fenceFd, /*noFreeBuffer*/true);
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800906
907 if (res == OK) {
908 // Attach this buffer to the bufferQueue: the buffer will be in dequeue state after
909 // a successful return.
910 *anb = gb.get();
911 res = mConsumer->attachBuffer(*anb);
912 gotBufferFromManager = true;
913 ALOGV("Stream %d: Attached new buffer", getId());
914
915 if (res != OK) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700916 if (shouldLogError(res, mState)) {
917 ALOGE("%s: Stream %d: Can't attach the output buffer to this surface:"
918 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
919 }
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800920 checkRetAndSetAbandonedLocked(res);
921 return res;
922 }
923 } else {
924 ALOGE("%s: Stream %d: Can't get next output buffer from buffer manager:"
925 " %s (%d)", __FUNCTION__, mId, strerror(-res), res);
926 return res;
927 }
928 } else if (res != OK) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700929 if (shouldLogError(res, mState)) {
930 ALOGE("%s: Stream %d: Can't dequeue next output buffer: %s (%d)",
931 __FUNCTION__, mId, strerror(-res), res);
932 }
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800933 checkRetAndSetAbandonedLocked(res);
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800934 return res;
935 }
936 }
937
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700938 if (res == OK) {
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800939 checkRemovedBuffersLocked();
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -0700940 }
941
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -0800942 return res;
943}
944
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800945void Camera3OutputStream::checkRemovedBuffersLocked(bool notifyBufferManager) {
946 std::vector<sp<GraphicBuffer>> removedBuffers;
947 status_t res = mConsumer->getAndFlushRemovedBuffers(&removedBuffers);
948 if (res == OK) {
949 onBuffersRemovedLocked(removedBuffers);
950
951 if (notifyBufferManager && mUseBufferManager && removedBuffers.size() > 0) {
Shuzhen Wang83bff122020-11-20 15:51:39 -0800952 mBufferManager->onBuffersRemoved(getId(), getStreamSetId(), isMultiResolution(),
953 removedBuffers.size());
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -0800954 }
955 }
956}
957
958void Camera3OutputStream::checkRetAndSetAbandonedLocked(status_t res) {
959 // Only transition to STATE_ABANDONED from STATE_CONFIGURED. (If it is
960 // STATE_PREPARING, let prepareNextBuffer handle the error.)
961 if ((res == NO_INIT || res == DEAD_OBJECT) && mState == STATE_CONFIGURED) {
962 mState = STATE_ABANDONED;
963 }
964}
965
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -0700966bool Camera3OutputStream::shouldLogError(status_t res, StreamState state) {
967 if (res == OK) {
968 return false;
969 }
970 if ((res == DEAD_OBJECT || res == NO_INIT) && state == STATE_ABANDONED) {
971 return false;
972 }
973 return true;
974}
975
Shuzhen Wangc2352702022-09-06 18:36:31 -0700976void Camera3OutputStream::onCachedBufferQueued() {
977 Mutex::Autolock l(mLock);
978 mCachedOutputBufferCount--;
979 // Signal whoever is waiting for the buffer to be returned to the buffer
980 // queue.
981 mOutputBufferReturnedSignal.signal();
982}
983
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800984status_t Camera3OutputStream::disconnectLocked() {
985 status_t res;
986
Igor Murashkine3a9f962013-05-08 18:03:15 -0700987 if ((res = Camera3IOStreamBase::disconnectLocked()) != OK) {
988 return res;
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -0800989 }
990
Zhijun He5d677d12016-05-29 16:52:39 -0700991 // Stream configuration was not finished (can only be in STATE_IN_CONFIG or STATE_CONSTRUCTED
992 // state), don't need change the stream state, return OK.
993 if (mConsumer == nullptr) {
994 return OK;
995 }
996
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -0800997 returnPrefetchedBuffersLocked();
998
Shuzhen Wangdc9aa822022-05-16 10:04:17 -0700999 if (mPreviewFrameSpacer != nullptr) {
1000 mPreviewFrameSpacer->requestExit();
1001 }
1002
Zhijun He125684a2015-12-26 15:07:30 -08001003 ALOGV("%s: disconnecting stream %d from native window", __FUNCTION__, getId());
1004
Igor Murashkine3a9f962013-05-08 18:03:15 -07001005 res = native_window_api_disconnect(mConsumer.get(),
1006 NATIVE_WINDOW_API_CAMERA);
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001007 /**
1008 * This is not an error. if client calling process dies, the window will
1009 * also die and all calls to it will return DEAD_OBJECT, thus it's already
1010 * "disconnected"
1011 */
1012 if (res == DEAD_OBJECT) {
1013 ALOGW("%s: While disconnecting stream %d from native window, the"
1014 " native window died from under us", __FUNCTION__, mId);
1015 }
1016 else if (res != OK) {
Igor Murashkine3a9f962013-05-08 18:03:15 -07001017 ALOGE("%s: Unable to disconnect stream %d from native window "
1018 "(error %d %s)",
1019 __FUNCTION__, mId, res, strerror(-res));
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001020 mState = STATE_ERROR;
1021 return res;
1022 }
1023
Zhijun He125684a2015-12-26 15:07:30 -08001024 // Since device is already idle, there is no getBuffer call to buffer manager, unregister the
1025 // stream at this point should be safe.
1026 if (mUseBufferManager) {
Shuzhen Wang83bff122020-11-20 15:51:39 -08001027 res = mBufferManager->unregisterStream(getId(), getStreamSetId(), isMultiResolution());
Zhijun He125684a2015-12-26 15:07:30 -08001028 if (res != OK) {
1029 ALOGE("%s: Unable to unregister stream %d from buffer manager "
1030 "(error %d %s)", __FUNCTION__, mId, res, strerror(-res));
1031 mState = STATE_ERROR;
1032 return res;
1033 }
1034 // Note that, to make prepare/teardown case work, we must not mBufferManager.clear(), as
1035 // the stream is still in usable state after this call.
1036 mUseBufferManager = false;
1037 }
1038
Igor Murashkine3a9f962013-05-08 18:03:15 -07001039 mState = (mState == STATE_IN_RECONFIG) ? STATE_IN_CONFIG
1040 : STATE_CONSTRUCTED;
Shuzhen Wang686f6442017-06-20 16:16:04 -07001041
1042 mDequeueBufferLatency.log("Stream %d dequeueBuffer latency histogram", mId);
1043 mDequeueBufferLatency.reset();
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001044 return OK;
1045}
1046
Emilian Peev050f5dc2017-05-18 14:43:56 +01001047status_t Camera3OutputStream::getEndpointUsage(uint64_t *usage) const {
Eino-Ville Talvalab2f5b192013-07-30 14:36:03 -07001048
1049 status_t res;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001050
Zhijun He5d677d12016-05-29 16:52:39 -07001051 if (mConsumer == nullptr) {
1052 // mConsumerUsage was sanitized before the Camera3OutputStream was constructed.
1053 *usage = mConsumerUsage;
1054 return OK;
1055 }
1056
Shuzhen Wang0129d522016-10-30 22:43:41 -07001057 res = getEndpointUsageForSurface(usage, mConsumer);
1058
1059 return res;
1060}
1061
Emilian Peev35ae8262018-11-08 13:11:32 +00001062void Camera3OutputStream::applyZSLUsageQuirk(int format, uint64_t *consumerUsage /*inout*/) {
1063 if (consumerUsage == nullptr) {
1064 return;
1065 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001066
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001067 // If an opaque output stream's endpoint is ImageReader, add
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -07001068 // GRALLOC_USAGE_HW_CAMERA_ZSL to the usage so HAL knows it will be used
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001069 // for the ZSL use case.
1070 // Assume it's for ImageReader if the consumer usage doesn't have any of these bits set:
1071 // 1. GRALLOC_USAGE_HW_TEXTURE
1072 // 2. GRALLOC_USAGE_HW_RENDER
1073 // 3. GRALLOC_USAGE_HW_COMPOSER
1074 // 4. GRALLOC_USAGE_HW_VIDEO_ENCODER
Emilian Peev35ae8262018-11-08 13:11:32 +00001075 if (format == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
1076 (*consumerUsage & (GRALLOC_USAGE_HW_TEXTURE | GRALLOC_USAGE_HW_RENDER |
Shuzhen Wang0129d522016-10-30 22:43:41 -07001077 GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_VIDEO_ENCODER)) == 0) {
Emilian Peev35ae8262018-11-08 13:11:32 +00001078 *consumerUsage |= GRALLOC_USAGE_HW_CAMERA_ZSL;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001079 }
Emilian Peev35ae8262018-11-08 13:11:32 +00001080}
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001081
Emilian Peev35ae8262018-11-08 13:11:32 +00001082status_t Camera3OutputStream::getEndpointUsageForSurface(uint64_t *usage,
1083 const sp<Surface>& surface) const {
1084 status_t res;
1085 uint64_t u = 0;
1086
1087 res = native_window_get_consumer_usage(static_cast<ANativeWindow*>(surface.get()), &u);
Emilian Peevf4816702020-04-03 15:44:51 -07001088 applyZSLUsageQuirk(camera_stream::format, &u);
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001089 *usage = u;
Eino-Ville Talvalab2f5b192013-07-30 14:36:03 -07001090 return res;
1091}
1092
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001093bool Camera3OutputStream::isVideoStream() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001094 uint64_t usage = 0;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07001095 status_t res = getEndpointUsage(&usage);
1096 if (res != OK) {
1097 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1098 return false;
1099 }
1100
1101 return (usage & GRALLOC_USAGE_HW_VIDEO_ENCODER) != 0;
1102}
1103
Zhijun He125684a2015-12-26 15:07:30 -08001104status_t Camera3OutputStream::setBufferManager(sp<Camera3BufferManager> bufferManager) {
1105 Mutex::Autolock l(mLock);
1106 if (mState != STATE_CONSTRUCTED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001107 ALOGE("%s: this method can only be called when stream in CONSTRUCTED state.",
Zhijun He125684a2015-12-26 15:07:30 -08001108 __FUNCTION__);
1109 return INVALID_OPERATION;
1110 }
1111 mBufferManager = bufferManager;
1112
1113 return OK;
1114}
1115
Emilian Peev40ead602017-09-26 15:46:36 +01001116status_t Camera3OutputStream::updateStream(const std::vector<sp<Surface>> &/*outputSurfaces*/,
1117 const std::vector<OutputStreamInfo> &/*outputInfo*/,
1118 const std::vector<size_t> &/*removedSurfaceIds*/,
1119 KeyedVector<sp<Surface>, size_t> * /*outputMapo*/) {
1120 ALOGE("%s: this method is not supported!", __FUNCTION__);
1121 return INVALID_OPERATION;
1122}
1123
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001124void Camera3OutputStream::BufferProducerListener::onBufferReleased() {
Zhijun He125684a2015-12-26 15:07:30 -08001125 sp<Camera3OutputStream> stream = mParent.promote();
1126 if (stream == nullptr) {
1127 ALOGV("%s: Parent camera3 output stream was destroyed", __FUNCTION__);
1128 return;
1129 }
1130
1131 Mutex::Autolock l(stream->mLock);
1132 if (!(stream->mUseBufferManager)) {
1133 return;
1134 }
1135
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001136 ALOGV("Stream %d: Buffer released", stream->getId());
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001137 bool shouldFreeBuffer = false;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001138 status_t res = stream->mBufferManager->onBufferReleased(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001139 stream->getId(), stream->getStreamSetId(), stream->isMultiResolution(),
1140 &shouldFreeBuffer);
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001141 if (res != OK) {
1142 ALOGE("%s: signaling buffer release to buffer manager failed: %s (%d).", __FUNCTION__,
1143 strerror(-res), res);
1144 stream->mState = STATE_ERROR;
1145 }
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001146
1147 if (shouldFreeBuffer) {
1148 sp<GraphicBuffer> buffer;
1149 // Detach and free a buffer (when buffer goes out of scope)
1150 stream->detachBufferLocked(&buffer, /*fenceFd*/ nullptr);
1151 if (buffer.get() != nullptr) {
1152 stream->mBufferManager->notifyBufferRemoved(
Shuzhen Wang83bff122020-11-20 15:51:39 -08001153 stream->getId(), stream->getStreamSetId(), stream->isMultiResolution());
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001154 }
1155 }
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001156}
1157
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001158void Camera3OutputStream::BufferProducerListener::onBuffersDiscarded(
1159 const std::vector<sp<GraphicBuffer>>& buffers) {
1160 sp<Camera3OutputStream> stream = mParent.promote();
1161 if (stream == nullptr) {
1162 ALOGV("%s: Parent camera3 output stream was destroyed", __FUNCTION__);
1163 return;
1164 }
1165
1166 if (buffers.size() > 0) {
1167 Mutex::Autolock l(stream->mLock);
1168 stream->onBuffersRemovedLocked(buffers);
1169 if (stream->mUseBufferManager) {
1170 stream->mBufferManager->onBuffersRemoved(stream->getId(),
Shuzhen Wang83bff122020-11-20 15:51:39 -08001171 stream->getStreamSetId(), stream->isMultiResolution(), buffers.size());
Shuzhen Wang0160ddd2019-08-15 09:11:56 -07001172 }
1173 ALOGV("Stream %d: %zu Buffers discarded.", stream->getId(), buffers.size());
1174 }
1175}
1176
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001177void Camera3OutputStream::onBuffersRemovedLocked(
1178 const std::vector<sp<GraphicBuffer>>& removedBuffers) {
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -07001179 sp<Camera3StreamBufferFreedListener> callback = mBufferFreedListener.promote();
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001180 if (callback != nullptr) {
Chih-Hung Hsieh48fc6192017-08-04 14:37:31 -07001181 for (const auto& gb : removedBuffers) {
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001182 callback->onBufferFreed(mId, gb->handle);
1183 }
1184 }
1185}
1186
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001187status_t Camera3OutputStream::detachBuffer(sp<GraphicBuffer>* buffer, int* fenceFd) {
1188 Mutex::Autolock l(mLock);
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001189 return detachBufferLocked(buffer, fenceFd);
1190}
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001191
Yin-Chia Yeh89954d92017-05-21 17:28:53 -07001192status_t Camera3OutputStream::detachBufferLocked(sp<GraphicBuffer>* buffer, int* fenceFd) {
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001193 ALOGV("Stream %d: detachBuffer", getId());
1194 if (buffer == nullptr) {
1195 return BAD_VALUE;
1196 }
1197
Zhijun He125684a2015-12-26 15:07:30 -08001198 sp<Fence> fence;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001199 status_t res = mConsumer->detachNextBuffer(buffer, &fence);
Zhijun He125684a2015-12-26 15:07:30 -08001200 if (res == NO_MEMORY) {
1201 // This may rarely happen, which indicates that the released buffer was freed by other
1202 // call (e.g., attachBuffer, dequeueBuffer etc.) before reaching here. We should notify the
1203 // buffer manager that this buffer has been freed. It's not fatal, but should be avoided,
1204 // therefore log a warning.
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001205 *buffer = 0;
Zhijun He125684a2015-12-26 15:07:30 -08001206 ALOGW("%s: the released buffer has already been freed by the buffer queue!", __FUNCTION__);
1207 } else if (res != OK) {
Eino-Ville Talvalaff51b472016-06-28 15:26:19 -07001208 // Treat other errors as abandonment
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001209 if (shouldLogError(res, mState)) {
1210 ALOGE("%s: detach next buffer failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1211 }
Eino-Ville Talvalaff51b472016-06-28 15:26:19 -07001212 mState = STATE_ABANDONED;
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001213 return res;
Zhijun He125684a2015-12-26 15:07:30 -08001214 }
1215
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001216 if (fenceFd != nullptr) {
1217 if (fence!= 0 && fence->isValid()) {
1218 *fenceFd = fence->dup();
1219 } else {
1220 *fenceFd = -1;
1221 }
Zhijun He125684a2015-12-26 15:07:30 -08001222 }
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07001223
Yin-Chia Yehbf1b8b92019-03-06 14:56:08 -08001224 // Here we assume detachBuffer is called by buffer manager so it doesn't need to be notified
1225 checkRemovedBuffersLocked(/*notifyBufferManager*/false);
Yin-Chia Yeh017d49c2017-03-31 19:11:00 -07001226 return res;
Zhijun He125684a2015-12-26 15:07:30 -08001227}
Shuzhen Wang13a69632016-01-26 09:51:07 -08001228
Chien-Yu Chena936ac22017-10-23 15:59:49 -07001229status_t Camera3OutputStream::dropBuffers(bool dropping) {
1230 Mutex::Autolock l(mLock);
1231 mDropBuffers = dropping;
1232 return OK;
1233}
1234
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001235const String8& Camera3OutputStream::getPhysicalCameraId() const {
1236 Mutex::Autolock l(mLock);
1237 return physicalCameraId();
1238}
1239
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08001240status_t Camera3OutputStream::notifyBufferReleased(ANativeWindowBuffer* /*anwBuffer*/) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001241 return OK;
1242}
1243
1244bool Camera3OutputStream::isConsumerConfigurationDeferred(size_t surface_id) const {
Zhijun He5d677d12016-05-29 16:52:39 -07001245 Mutex::Autolock l(mLock);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001246
1247 if (surface_id != 0) {
Shuzhen Wang758c2152017-01-10 18:26:18 -08001248 ALOGE("%s: surface_id %zu for Camera3OutputStream should be 0!", __FUNCTION__, surface_id);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001249 }
Zhijun He5d677d12016-05-29 16:52:39 -07001250 return mConsumer == nullptr;
1251}
1252
Shuzhen Wang758c2152017-01-10 18:26:18 -08001253status_t Camera3OutputStream::setConsumers(const std::vector<sp<Surface>>& consumers) {
Shuzhen Wangbee0f0a2017-01-24 14:51:37 -08001254 Mutex::Autolock l(mLock);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001255 if (consumers.size() != 1) {
1256 ALOGE("%s: it's illegal to set %zu consumer surfaces!",
1257 __FUNCTION__, consumers.size());
1258 return INVALID_OPERATION;
1259 }
1260 if (consumers[0] == nullptr) {
1261 ALOGE("%s: it's illegal to set null consumer surface!", __FUNCTION__);
Zhijun He5d677d12016-05-29 16:52:39 -07001262 return INVALID_OPERATION;
1263 }
1264
1265 if (mConsumer != nullptr) {
1266 ALOGE("%s: consumer surface was already set!", __FUNCTION__);
1267 return INVALID_OPERATION;
1268 }
1269
Shuzhen Wang758c2152017-01-10 18:26:18 -08001270 mConsumer = consumers[0];
Zhijun He5d677d12016-05-29 16:52:39 -07001271 return OK;
1272}
1273
Shuzhen Wang13a69632016-01-26 09:51:07 -08001274bool Camera3OutputStream::isConsumedByHWComposer() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001275 uint64_t usage = 0;
Shuzhen Wang13a69632016-01-26 09:51:07 -08001276 status_t res = getEndpointUsage(&usage);
1277 if (res != OK) {
1278 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1279 return false;
1280 }
1281
1282 return (usage & GRALLOC_USAGE_HW_COMPOSER) != 0;
1283}
1284
Zhijun Hef0645c12016-08-02 00:58:11 -07001285bool Camera3OutputStream::isConsumedByHWTexture() const {
Emilian Peev050f5dc2017-05-18 14:43:56 +01001286 uint64_t usage = 0;
Zhijun Hef0645c12016-08-02 00:58:11 -07001287 status_t res = getEndpointUsage(&usage);
1288 if (res != OK) {
1289 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1290 return false;
1291 }
1292
1293 return (usage & GRALLOC_USAGE_HW_TEXTURE) != 0;
1294}
1295
Shuzhen Wangfe8a2a32022-05-10 18:18:54 -07001296bool Camera3OutputStream::isConsumedByCPU() const {
1297 uint64_t usage = 0;
1298 status_t res = getEndpointUsage(&usage);
1299 if (res != OK) {
1300 ALOGE("%s: getting end point usage failed: %s (%d).", __FUNCTION__, strerror(-res), res);
1301 return false;
1302 }
1303
1304 return (usage & GRALLOC_USAGE_SW_READ_MASK) != 0;
1305}
1306
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001307void Camera3OutputStream::dumpImageToDisk(nsecs_t timestamp,
1308 ANativeWindowBuffer* anwBuffer, int fence) {
1309 // Deriver output file name
1310 std::string fileExtension = "jpg";
1311 char imageFileName[64];
1312 time_t now = time(0);
1313 tm *localTime = localtime(&now);
1314 snprintf(imageFileName, sizeof(imageFileName), "IMG_%4d%02d%02d_%02d%02d%02d_%" PRId64 ".%s",
Shuzhen Wang6a8237f2021-07-13 14:42:57 -07001315 1900 + localTime->tm_year, localTime->tm_mon + 1, localTime->tm_mday,
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001316 localTime->tm_hour, localTime->tm_min, localTime->tm_sec,
1317 timestamp, fileExtension.c_str());
1318
1319 // Lock the image for CPU read
1320 sp<GraphicBuffer> graphicBuffer = GraphicBuffer::from(anwBuffer);
1321 void* mapped = nullptr;
1322 base::unique_fd fenceFd(dup(fence));
1323 status_t res = graphicBuffer->lockAsync(GraphicBuffer::USAGE_SW_READ_OFTEN, &mapped,
Emilian Peev293bd972022-08-05 17:28:06 -07001324 fenceFd.release());
Shuzhen Wangabbcb6b2020-12-09 22:32:44 -08001325 if (res != OK) {
1326 ALOGE("%s: Failed to lock the buffer: %s (%d)", __FUNCTION__, strerror(-res), res);
1327 return;
1328 }
1329
1330 // Figure out actual file size
1331 auto actualJpegSize = android::camera2::JpegProcessor::findJpegSize((uint8_t*)mapped, mMaxSize);
1332 if (actualJpegSize == 0) {
1333 actualJpegSize = mMaxSize;
1334 }
1335
1336 // Output image data to file
1337 std::string filePath = "/data/misc/cameraserver/";
1338 filePath += imageFileName;
1339 std::ofstream imageFile(filePath.c_str(), std::ofstream::binary);
1340 if (!imageFile.is_open()) {
1341 ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
1342 graphicBuffer->unlock();
1343 return;
1344 }
1345 imageFile.write((const char*)mapped, actualJpegSize);
1346
1347 graphicBuffer->unlock();
1348}
1349
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001350status_t Camera3OutputStream::setBatchSize(size_t batchSize) {
1351 Mutex::Autolock l(mLock);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001352 if (batchSize == 0) {
1353 ALOGE("%s: invalid batch size 0", __FUNCTION__);
1354 return BAD_VALUE;
1355 }
1356
1357 if (mUseBufferManager) {
1358 ALOGE("%s: batch operation is not supported with buffer manager", __FUNCTION__);
1359 return INVALID_OPERATION;
1360 }
1361
1362 if (!isVideoStream()) {
1363 ALOGE("%s: batch operation is not supported with non-video stream", __FUNCTION__);
1364 return INVALID_OPERATION;
1365 }
1366
Shuzhen Wangc7629462021-07-12 15:02:58 -07001367 if (camera_stream::max_buffers < batchSize) {
1368 ALOGW("%s: batch size is capped by max_buffers %d", __FUNCTION__,
1369 camera_stream::max_buffers);
1370 batchSize = camera_stream::max_buffers;
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001371 }
Shuzhen Wangc7629462021-07-12 15:02:58 -07001372
1373 size_t defaultBatchSize = 1;
1374 if (!mBatchSize.compare_exchange_strong(defaultBatchSize, batchSize)) {
1375 ALOGE("%s: change batch size from %zu to %zu dynamically is not supported",
1376 __FUNCTION__, defaultBatchSize, batchSize);
1377 return INVALID_OPERATION;
1378 }
1379
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001380 return OK;
1381}
1382
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001383void Camera3OutputStream::onMinDurationChanged(nsecs_t duration, bool fixedFps) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001384 Mutex::Autolock l(mLock);
1385 mMinExpectedDuration = duration;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001386 mFixedFps = fixedFps;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001387}
1388
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001389void Camera3OutputStream::returnPrefetchedBuffersLocked() {
Shuzhen Wangc7629462021-07-12 15:02:58 -07001390 std::vector<Surface::BatchBuffer> batchedBuffers;
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001391
Shuzhen Wangc7629462021-07-12 15:02:58 -07001392 {
1393 std::lock_guard<std::mutex> batchLock(mBatchLock);
1394 if (mBatchedBuffers.size() != 0) {
1395 ALOGW("%s: %zu extra prefetched buffers detected. Returning",
1396 __FUNCTION__, mBatchedBuffers.size());
1397 batchedBuffers = std::move(mBatchedBuffers);
1398 }
1399 }
1400
1401 if (batchedBuffers.size() > 0) {
1402 mConsumer->cancelBuffers(batchedBuffers);
Yin-Chia Yeh14ef48d2020-02-10 15:06:37 -08001403 }
1404}
1405
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001406nsecs_t Camera3OutputStream::syncTimestampToDisplayLocked(nsecs_t t) {
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001407 nsecs_t currentTime = systemTime();
1408 if (!mFixedFps) {
1409 mLastCaptureTime = t;
1410 mLastPresentTime = currentTime;
1411 return t;
1412 }
1413
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001414 ParcelableVsyncEventData parcelableVsyncEventData;
1415 auto res = mDisplayEventReceiver.getLatestVsyncEventData(&parcelableVsyncEventData);
1416 if (res != OK) {
1417 ALOGE("%s: Stream %d: Error getting latest vsync event data: %s (%d)",
1418 __FUNCTION__, mId, strerror(-res), res);
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001419 mLastCaptureTime = t;
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001420 mLastPresentTime = currentTime;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001421 return t;
1422 }
1423
1424 const VsyncEventData& vsyncEventData = parcelableVsyncEventData.vsync;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001425 nsecs_t minPresentT = mLastPresentTime + vsyncEventData.frameInterval / 2;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001426
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001427 // Find the best presentation time without worrying about previous frame's
1428 // presentation time if capture interval is more than kSpacingResetIntervalNs.
1429 //
1430 // When frame interval is more than 50 ms apart (3 vsyncs for 60hz refresh rate),
1431 // there is little risk in starting over and finding the earliest vsync to latch onto.
1432 // - Update captureToPresentTime offset to be used for later frames.
1433 // - Example use cases:
1434 // - when frame rate drops down to below 20 fps, or
1435 // - A new streaming session starts (stopPreview followed by
1436 // startPreview)
1437 //
Shuzhen Wang34a5e282022-06-17 14:48:35 -07001438 nsecs_t captureInterval = t - mLastCaptureTime;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001439 if (captureInterval > kSpacingResetIntervalNs) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001440 for (size_t i = 0; i < VsyncEventData::kFrameTimelinesLength; i++) {
Shuzhen Wang34a5e282022-06-17 14:48:35 -07001441 const auto& timeline = vsyncEventData.frameTimelines[i];
1442 if (timeline.deadlineTimestamp >= currentTime &&
1443 timeline.expectedPresentationTime > minPresentT) {
1444 nsecs_t presentT = vsyncEventData.frameTimelines[i].expectedPresentationTime;
1445 mCaptureToPresentOffset = presentT - t;
1446 mLastCaptureTime = t;
1447 mLastPresentTime = presentT;
1448
1449 // Move the expected presentation time back by 1/3 of frame interval to
1450 // mitigate the time drift. Due to time drift, if we directly use the
1451 // expected presentation time, often times 2 expected presentation time
1452 // falls into the same VSYNC interval.
1453 return presentT - vsyncEventData.frameInterval/3;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001454 }
1455 }
1456 }
1457
1458 nsecs_t idealPresentT = t + mCaptureToPresentOffset;
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001459 nsecs_t expectedPresentT = mLastPresentTime;
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001460 nsecs_t minDiff = INT64_MAX;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001461
1462 // In fixed FPS case, when frame durations are close to multiples of display refresh
1463 // rate, derive minimum intervals between presentation times based on minimal
Shuzhen Wang661b34f2022-05-18 22:00:19 -07001464 // expected duration. The minimum number of Vsyncs is:
1465 // - 0 if minFrameDuration in (0, 1.5] * vSyncInterval,
1466 // - 1 if minFrameDuration in (1.5, 2.5] * vSyncInterval,
1467 // - and so on.
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001468 //
1469 // This spaces out the displaying of the frames so that the frame
1470 // presentations are roughly in sync with frame captures.
Shuzhen Wang661b34f2022-05-18 22:00:19 -07001471 int minVsyncs = (mMinExpectedDuration - vsyncEventData.frameInterval / 2) /
1472 vsyncEventData.frameInterval;
1473 if (minVsyncs < 0) minVsyncs = 0;
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001474 nsecs_t minInterval = minVsyncs * vsyncEventData.frameInterval;
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001475
1476 // In fixed FPS case, if the frame duration deviates from multiples of
1477 // display refresh rate, find the closest Vsync without requiring a minimum
1478 // number of Vsync.
1479 //
1480 // Example: (24fps camera, 60hz refresh):
1481 // capture readout: | t1 | t1 | .. | t1 | .. | t1 | .. | t1 |
1482 // display VSYNC: | t2 | t2 | ... | t2 | ... | t2 | ... | t2 |
1483 // | : 1 frame
1484 // t1 : 41.67ms
1485 // t2 : 16.67ms
1486 // t1/t2 = 2.5
1487 //
1488 // 24fps is a commonly used video frame rate. Because the capture
1489 // interval is 2.5 times of display refresh interval, the minVsyncs
1490 // calculation will directly fall at the boundary condition. In this case,
1491 // we should fall back to the basic logic of finding closest vsync
1492 // timestamp without worrying about minVsyncs.
1493 float captureToVsyncIntervalRatio = 1.0f * mMinExpectedDuration / vsyncEventData.frameInterval;
1494 float ratioDeviation = std::fabs(
1495 captureToVsyncIntervalRatio - std::roundf(captureToVsyncIntervalRatio));
1496 bool captureDeviateFromVsync = ratioDeviation >= kMaxIntervalRatioDeviation;
1497 bool cameraDisplayInSync = (mFixedFps && !captureDeviateFromVsync);
1498
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001499 // Find best timestamp in the vsync timelines:
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001500 // - Only use at most kMaxTimelines timelines to avoid long latency
1501 // - closest to the ideal presentation time,
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001502 // - deadline timestamp is greater than the current time, and
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001503 // - For fixed FPS, if the capture interval doesn't deviate too much from refresh interval,
1504 // the candidate presentation time is at least minInterval in the future compared to last
1505 // presentation time.
1506 // - For variable FPS, or if the capture interval deviates from refresh
1507 // interval for more than 5%, find a presentation time closest to the
1508 // (lastPresentationTime + captureToPresentOffset) instead.
Shuzhen Wanged08fbe2022-06-21 01:00:50 -07001509 int maxTimelines = std::min(kMaxTimelines, (int)VsyncEventData::kFrameTimelinesLength);
1510 float biasForShortDelay = 1.0f;
1511 for (int i = 0; i < maxTimelines; i ++) {
1512 const auto& vsyncTime = vsyncEventData.frameTimelines[i];
1513 if (minVsyncs > 0) {
1514 // Bias towards using smaller timeline index:
1515 // i = 0: bias = 1
1516 // i = maxTimelines-1: bias = -1
1517 biasForShortDelay = 1.0 - 2.0 * i / (maxTimelines - 1);
1518 }
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001519 if (std::abs(vsyncTime.expectedPresentationTime - idealPresentT) < minDiff &&
1520 vsyncTime.deadlineTimestamp >= currentTime &&
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001521 ((!cameraDisplayInSync && vsyncTime.expectedPresentationTime > minPresentT) ||
1522 (cameraDisplayInSync && vsyncTime.expectedPresentationTime >
1523 mLastPresentTime + minInterval + biasForShortDelay * kTimelineThresholdNs))) {
Shuzhen Wang00abbeb2022-02-25 17:14:42 -08001524 expectedPresentT = vsyncTime.expectedPresentationTime;
1525 minDiff = std::abs(vsyncTime.expectedPresentationTime - idealPresentT);
1526 }
1527 }
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001528
Shuzhen Wang35bd3552022-09-21 16:56:04 -07001529 if (expectedPresentT == mLastPresentTime && expectedPresentT <
1530 vsyncEventData.frameTimelines[maxTimelines-1].expectedPresentationTime) {
Shuzhen Wang696e4da2022-09-08 14:31:13 -07001531 // Couldn't find a reasonable presentation time. Using last frame's
1532 // presentation time would cause a frame drop. The best option now
1533 // is to use the next VSync as long as the last presentation time
1534 // doesn't already has the maximum latency, in which case dropping the
1535 // buffer is more desired than increasing latency.
1536 //
1537 // Example: (60fps camera, 59.9hz refresh):
1538 // capture readout: | t1 | t1 | .. | t1 | .. | t1 | .. | t1 |
1539 // \ \ \ \ \ \ \ \ \
1540 // queue to BQ: | | | | | | | | |
1541 // \ \ \ \ \ \ \ \ \
1542 // display VSYNC: | t2 | t2 | ... | t2 | ... | t2 | ... | t2 |
1543 //
1544 // |: 1 frame
1545 // t1 : 16.67ms
1546 // t2 : 16.69ms
1547 //
1548 // It takes 833 frames for capture readout count and display VSYNC count to be off
1549 // by 1.
1550 // - At frames [0, 832], presentationTime is set to timeline[0]
1551 // - At frames [833, 833*2-1], presentationTime is set to timeline[1]
1552 // - At frames [833*2, 833*3-1] presentationTime is set to timeline[2]
1553 // - At frame 833*3, no presentation time is found because we only
1554 // search for timeline[0..2].
1555 // - Drop one buffer is better than further extend the presentation
1556 // time.
1557 //
1558 // However, if frame 833*2 arrives 16.67ms early (right after frame
1559 // 833*2-1), no presentation time can be found because
1560 // getLatestVsyncEventData is called early. In that case, it's better to
1561 // set presentation time by offseting last presentation time.
1562 expectedPresentT += vsyncEventData.frameInterval;
1563 }
1564
Shuzhen Wang14c62b82022-04-11 09:37:05 -07001565 mLastCaptureTime = t;
1566 mLastPresentTime = expectedPresentT;
1567
1568 // Move the expected presentation time back by 1/3 of frame interval to
1569 // mitigate the time drift. Due to time drift, if we directly use the
1570 // expected presentation time, often times 2 expected presentation time
1571 // falls into the same VSYNC interval.
1572 return expectedPresentT - vsyncEventData.frameInterval/3;
Shuzhen Wange4adddb2021-09-21 15:24:44 -07001573}
1574
Shuzhen Wangba92d772022-04-11 11:47:24 -07001575bool Camera3OutputStream::shouldLogError(status_t res) {
1576 Mutex::Autolock l(mLock);
1577 return shouldLogError(res, mState);
1578}
1579
Eino-Ville Talvalafd58f1a2013-03-06 16:20:06 -08001580}; // namespace camera3
1581
1582}; // namespace android