blob: 0f4ba654c08eb186924fd969ce94c6613cd5f83a [file] [log] [blame]
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-HeicCompositeStream"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
Susmitha Gummallae911f2e2020-11-23 09:57:03 -080019#define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) )
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080020//#define LOG_NDEBUG 0
21
22#include <linux/memfd.h>
23#include <pthread.h>
24#include <sys/syscall.h>
25
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000026#include <aidl/android/hardware/camera/device/CameraBlob.h>
27#include <aidl/android/hardware/camera/device/CameraBlobId.h>
Jim Shargo2e0202f2024-07-30 19:54:43 +000028#include <camera/StringUtils.h>
29#include <com_android_graphics_libgui_flags.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080030#include <gui/Surface.h>
Jim Shargo2e0202f2024-07-30 19:54:43 +000031#include <libyuv.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080032#include <utils/Log.h>
33#include <utils/Trace.h>
34
Marco Nelissen13aa1a42019-09-27 10:21:55 -070035#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080036#include <media/MediaCodecBuffer.h>
37#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080038#include <media/stagefright/foundation/MediaDefs.h>
39#include <media/stagefright/MediaCodecConstants.h>
40
41#include "common/CameraDeviceBase.h"
42#include "utils/ExifUtils.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080043#include "utils/SessionConfigurationUtils.h"
Eino-Ville Talvalab7723202024-06-24 17:45:51 -070044#include "utils/Utils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080045#include "HeicEncoderInfoManager.h"
46#include "HeicCompositeStream.h"
47
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000048using aidl::android::hardware::camera::device::CameraBlob;
49using aidl::android::hardware::camera::device::CameraBlobId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080050
51namespace android {
52namespace camera3 {
53
Shuzhen Wange8675782019-12-05 09:12:14 -080054HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080055 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
56 CompositeStream(device, cb),
57 mUseHeic(false),
58 mNumOutputTiles(1),
59 mOutputWidth(0),
60 mOutputHeight(0),
61 mMaxHeicBufferSize(0),
62 mGridWidth(HeicEncoderInfoManager::kGridWidth),
63 mGridHeight(HeicEncoderInfoManager::kGridHeight),
64 mGridRows(1),
65 mGridCols(1),
66 mUseGrid(false),
67 mAppSegmentStreamId(-1),
68 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080069 mMainImageStreamId(-1),
70 mMainImageSurfaceId(-1),
71 mYuvBufferAcquired(false),
Carlos Martinez Romeroae9834f2024-07-03 13:33:47 -070072 mStreamSurfaceListener(new StreamSurfaceListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070073 mDequeuedOutputBufferCnt(0),
74 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070075 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080076 mGridTimestampUs(0),
77 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080078}
79
80HeicCompositeStream::~HeicCompositeStream() {
81 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
82 // memory/resource leak.
83 deinitCodec();
84
85 mInputAppSegmentBuffers.clear();
86 mCodecOutputBuffers.clear();
87
88 mAppSegmentStreamId = -1;
89 mAppSegmentSurfaceId = -1;
90 mAppSegmentConsumer.clear();
91 mAppSegmentSurface.clear();
92
93 mMainImageStreamId = -1;
94 mMainImageSurfaceId = -1;
95 mMainImageConsumer.clear();
96 mMainImageSurface.clear();
97}
98
Emilian Peeve75a2852024-05-20 22:35:15 +000099bool HeicCompositeStream::isHeicCompositeStreamInfo(const OutputStreamInfo& streamInfo) {
100 return ((streamInfo.dataSpace == static_cast<android_dataspace_t>(HAL_DATASPACE_HEIF)) &&
101 (streamInfo.format == HAL_PIXEL_FORMAT_BLOB));
102}
103
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800104bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
105 ANativeWindow *anw = surface.get();
106 status_t err;
107 int format;
108 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
Austin Borger1c1bee02023-06-01 16:51:35 -0700109 std::string msg = fmt::sprintf("Failed to query Surface format: %s (%d)", strerror(-err),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800110 err);
Austin Borger1c1bee02023-06-01 16:51:35 -0700111 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800112 return false;
113 }
114
115 int dataspace;
116 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
Austin Borger1c1bee02023-06-01 16:51:35 -0700117 std::string msg = fmt::sprintf("Failed to query Surface dataspace: %s (%d)", strerror(-err),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800118 err);
Austin Borger1c1bee02023-06-01 16:51:35 -0700119 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800120 return false;
121 }
122
123 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
124}
125
Shuzhen Wang38df0ca2024-10-09 11:33:44 -0700126status_t HeicCompositeStream::createInternalStreams(const std::vector<SurfaceHolder>& consumers,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800127 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
Austin Borger1c1bee02023-06-01 16:51:35 -0700128 camera_stream_rotation_t rotation, int *id, const std::string& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800129 const std::unordered_set<int32_t> &sensorPixelModesUsed,
130 std::vector<int> *surfaceIds,
Syed Haqc8a536d2023-05-09 12:14:52 -0700131 int /*streamSetId*/, bool /*isShared*/, int32_t colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000132 int64_t /*dynamicProfile*/, int64_t /*streamUseCase*/, bool useReadoutTimestamp) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800133 sp<CameraDeviceBase> device = mDevice.promote();
134 if (!device.get()) {
135 ALOGE("%s: Invalid camera device!", __FUNCTION__);
136 return NO_INIT;
137 }
138
139 status_t res = initializeCodec(width, height, device);
140 if (res != OK) {
141 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
142 __FUNCTION__, strerror(-res), res);
143 return NO_INIT;
144 }
145
Jim Shargo2e0202f2024-07-30 19:54:43 +0000146#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
147 mAppSegmentConsumer = new CpuConsumer(kMaxAcquiredAppSegment);
148 mAppSegmentConsumer->setFrameAvailableListener(this);
149 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
150 mAppSegmentSurface = mAppSegmentConsumer->getSurface();
151 sp<IGraphicBufferProducer> producer = mAppSegmentSurface->getIGraphicBufferProducer();
152#else
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800153 sp<IGraphicBufferProducer> producer;
154 sp<IGraphicBufferConsumer> consumer;
155 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700156 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800157 mAppSegmentConsumer->setFrameAvailableListener(this);
158 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
159 mAppSegmentSurface = new Surface(producer);
Jim Shargo2e0202f2024-07-30 19:54:43 +0000160#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800161
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800162 mStaticInfo = device->info();
163
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800164 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800165 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000166 sensorPixelModesUsed, surfaceIds, camera3::CAMERA3_STREAM_SET_ID_INVALID,
167 /*isShared*/false, /*isMultiResolution*/false,
168 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
169 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
170 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
171 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700172 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000173 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800174 if (res == OK) {
175 mAppSegmentSurfaceId = (*surfaceIds)[0];
176 } else {
177 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
178 strerror(-res), res);
179 return res;
180 }
181
182 if (!mUseGrid) {
183 res = mCodec->createInputSurface(&producer);
184 if (res != OK) {
185 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
186 __FUNCTION__, strerror(-res), res);
187 return res;
188 }
189 } else {
Jim Shargo2e0202f2024-07-30 19:54:43 +0000190#if COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
191 mMainImageConsumer = new CpuConsumer(1);
192 producer = mMainImageConsumer->getSurface()->getIGraphicBufferProducer();
193#else
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800194 BufferQueue::createBufferQueue(&producer, &consumer);
195 mMainImageConsumer = new CpuConsumer(consumer, 1);
Jim Shargo2e0202f2024-07-30 19:54:43 +0000196#endif // COM_ANDROID_GRAPHICS_LIBGUI_FLAGS(WB_CONSUMER_BASE_OWNS_BQ)
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800197 mMainImageConsumer->setFrameAvailableListener(this);
198 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
199 }
200 mMainImageSurface = new Surface(producer);
201
202 res = mCodec->start();
203 if (res != OK) {
204 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
205 strerror(-res), res);
206 return res;
207 }
208
209 std::vector<int> sourceSurfaceId;
210 //Use YUV_888 format if framework tiling is needed.
211 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
212 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
213 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000214 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId,
215 camera3::CAMERA3_STREAM_SET_ID_INVALID, /*isShared*/false, /*isMultiResolution*/false,
216 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
217 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
218 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
219 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700220 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000221 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800222 if (res == OK) {
223 mMainImageSurfaceId = sourceSurfaceId[0];
224 mMainImageStreamId = *id;
225 } else {
226 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
227 strerror(-res), res);
228 return res;
229 }
230
Shuzhen Wang38df0ca2024-10-09 11:33:44 -0700231 mOutputSurface = consumers[0].mSurface;
Shuzhen Wange8675782019-12-05 09:12:14 -0800232 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800233 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800234 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
235 strerror(-res), res);
236 return res;
237 }
238
239 res = registerCompositeStreamListener(mAppSegmentStreamId);
240 if (res != OK) {
241 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
242 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800243 return res;
244 }
245
Shuzhen Wang219c2992019-02-15 17:24:28 -0800246 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800247 return res;
248}
249
250status_t HeicCompositeStream::deleteInternalStreams() {
251 requestExit();
252 auto res = join();
253 if (res != OK) {
254 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
255 strerror(-res), res);
256 }
257
258 deinitCodec();
259
260 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700261 // Camera devices may not be valid after switching to offline mode.
262 // In this case, all offline streams including internal composite streams
263 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800264 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700265 if (device.get() != nullptr) {
266 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800267 }
268
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800269 mAppSegmentStreamId = -1;
270 }
271
Shuzhen Wang2c545042019-02-07 10:27:35 -0800272 if (mOutputSurface != nullptr) {
273 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
274 mOutputSurface.clear();
275 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800276
277 sp<StatusTracker> statusTracker = mStatusTracker.promote();
278 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
279 statusTracker->removeComponent(mStatusId);
280 mStatusId = StatusTracker::NO_STATUS_ID;
281 }
282
283 if (mPendingInputFrames.size() > 0) {
284 ALOGW("%s: mPendingInputFrames has %zu stale entries",
285 __FUNCTION__, mPendingInputFrames.size());
286 mPendingInputFrames.clear();
287 }
288
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800289 return res;
290}
291
292void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
293 Mutex::Autolock l(mMutex);
294
295 if (bufferInfo.mError) return;
296
Shuzhen Wange8675782019-12-05 09:12:14 -0800297 if (bufferInfo.mStreamId == mMainImageStreamId) {
298 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
299 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
300 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
301 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
302 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
303 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
304 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
305 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
306 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800307}
308
309// We need to get the settings early to handle the case where the codec output
310// arrives earlier than result metadata.
311void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
312 const CameraMetadata& settings) {
313 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
314
315 Mutex::Autolock l(mMutex);
316 if (mErrorState || (streamId != getStreamId())) {
317 return;
318 }
319
320 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
321
322 camera_metadata_ro_entry entry;
323
324 int32_t orientation = 0;
325 entry = settings.find(ANDROID_JPEG_ORIENTATION);
326 if (entry.count == 1) {
327 orientation = entry.data.i32[0];
328 }
329
330 int32_t quality = kDefaultJpegQuality;
331 entry = settings.find(ANDROID_JPEG_QUALITY);
332 if (entry.count == 1) {
333 quality = entry.data.i32[0];
334 }
335
Shuzhen Wange8675782019-12-05 09:12:14 -0800336 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800337}
338
339void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
340 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
341 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
342 __func__, ns2ms(item.mTimestamp));
343
344 Mutex::Autolock l(mMutex);
345 if (!mErrorState) {
346 mInputAppSegmentBuffers.push_back(item.mTimestamp);
347 mInputReadyCondition.signal();
348 }
349 } else if (item.mDataSpace == kHeifDataSpace) {
350 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
351 __func__, ns2ms(item.mTimestamp));
352
353 Mutex::Autolock l(mMutex);
354 if (!mUseGrid) {
355 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
356 __FUNCTION__);
357 return;
358 }
359 if (!mErrorState) {
360 mInputYuvBuffers.push_back(item.mTimestamp);
361 mInputReadyCondition.signal();
362 }
363 } else {
364 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
365 }
366}
367
368status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
369 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
370 if (compositeOutput == nullptr) {
371 return BAD_VALUE;
372 }
373
374 compositeOutput->clear();
375
376 bool useGrid, useHeic;
377 bool isSizeSupported = isSizeSupportedByHeifEncoder(
378 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
379 if (!isSizeSupported) {
380 // Size is not supported by either encoder.
381 return OK;
382 }
383
384 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
385
386 // JPEG APPS segments Blob stream info
387 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
388 (*compositeOutput)[0].height = 1;
389 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
390 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
391 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
392
393 // YUV/IMPLEMENTATION_DEFINED stream info
394 (*compositeOutput)[1].width = streamInfo.width;
395 (*compositeOutput)[1].height = streamInfo.height;
396 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
397 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
398 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
399 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
400 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
401
402 return NO_ERROR;
403}
404
405bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700406 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800407 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700408 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800409}
410
411bool HeicCompositeStream::isInMemoryTempFileSupported() {
412 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
413 if (memfd == -1) {
414 if (errno != ENOSYS) {
415 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
416 }
417 return false;
418 }
419 close(memfd);
420 return true;
421}
422
423void HeicCompositeStream::onHeicOutputFrameAvailable(
424 const CodecOutputBufferInfo& outputBufferInfo) {
425 Mutex::Autolock l(mMutex);
426
427 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
428 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
429 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
430
431 if (!mErrorState) {
432 if ((outputBufferInfo.size > 0) &&
433 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
434 mCodecOutputBuffers.push_back(outputBufferInfo);
435 mInputReadyCondition.signal();
436 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700437 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
438 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800439 mCodec->releaseOutputBuffer(outputBufferInfo.index);
440 }
441 } else {
442 mCodec->releaseOutputBuffer(outputBufferInfo.index);
443 }
444}
445
446void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
447 Mutex::Autolock l(mMutex);
448
449 if (!mUseGrid) {
450 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
451 return;
452 }
453
454 mCodecInputBuffers.push_back(index);
455 mInputReadyCondition.signal();
456}
457
458void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
459 if (newFormat == nullptr) {
460 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
461 return;
462 }
463
464 Mutex::Autolock l(mMutex);
465
466 AString mime;
467 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
468 newFormat->findString(KEY_MIME, &mime);
469 if (mime != mimeHeic) {
470 // For HEVC codec, below keys need to be filled out or overwritten so that the
471 // muxer can handle them as HEIC output image.
472 newFormat->setString(KEY_MIME, mimeHeic);
473 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
474 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000475 }
476
477 if (mUseGrid || mUseHeic) {
478 int32_t gridRows, gridCols, tileWidth, tileHeight;
479 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
480 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols) &&
481 newFormat->findInt32(KEY_TILE_WIDTH, &tileWidth) &&
482 newFormat->findInt32(KEY_TILE_HEIGHT, &tileHeight)) {
483 mGridWidth = tileWidth;
484 mGridHeight = tileHeight;
485 mGridRows = gridRows;
486 mGridCols = gridCols;
487 } else {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800488 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
489 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
490 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
491 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000492 }
493 int32_t left, top, right, bottom;
494 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
495 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800496 }
497 }
498 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
499
500 int32_t gridRows, gridCols;
501 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
502 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
503 mNumOutputTiles = gridRows * gridCols;
504 } else {
505 mNumOutputTiles = 1;
506 }
507
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800508 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700509
510 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
511 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800512}
513
514void HeicCompositeStream::onHeicCodecError() {
515 Mutex::Autolock l(mMutex);
516 mErrorState = true;
517}
518
519status_t HeicCompositeStream::configureStream() {
520 if (isRunning()) {
521 // Processing thread is already running, nothing more to do.
522 return NO_ERROR;
523 }
524
525 if (mOutputSurface.get() == nullptr) {
526 ALOGE("%s: No valid output surface set!", __FUNCTION__);
527 return NO_INIT;
528 }
529
Carlos Martinez Romeroae9834f2024-07-03 13:33:47 -0700530 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mStreamSurfaceListener);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800531 if (res != OK) {
532 ALOGE("%s: Unable to connect to native window for stream %d",
533 __FUNCTION__, mMainImageStreamId);
534 return res;
535 }
536
537 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
538 != OK) {
539 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
540 mMainImageStreamId);
541 return res;
542 }
543
544 ANativeWindow *anwConsumer = mOutputSurface.get();
545 int maxConsumerBuffers;
546 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
547 &maxConsumerBuffers)) != OK) {
548 ALOGE("%s: Unable to query consumer undequeued"
549 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
550 return res;
551 }
552
553 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
554 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800555 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700556 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800557 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
558 return res;
559 }
560
561 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
562 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
563 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
564 return res;
565 }
566
Shuzhen Wange8675782019-12-05 09:12:14 -0800567 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
568 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700569 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
570 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800571 }
572
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800573 run("HeicCompositeStreamProc");
574
575 return NO_ERROR;
576}
577
578status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
579 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
580 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800581 outputStreamIds->push_back(mAppSegmentStreamId);
582 }
583 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
584
585 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800586 outputStreamIds->push_back(mMainImageStreamId);
587 }
588 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
589
590 if (currentStreamId != nullptr) {
591 *currentStreamId = mMainImageStreamId;
592 }
593
594 return NO_ERROR;
595}
596
Emilian Peev4697b642019-11-19 17:11:14 -0800597status_t HeicCompositeStream::insertCompositeStreamIds(
598 std::vector<int32_t>* compositeStreamIds /*out*/) {
599 if (compositeStreamIds == nullptr) {
600 return BAD_VALUE;
601 }
602
603 compositeStreamIds->push_back(mAppSegmentStreamId);
604 compositeStreamIds->push_back(mMainImageStreamId);
605
606 return OK;
607}
608
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800609void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
610 Mutex::Autolock l(mMutex);
611 if (mErrorState) {
612 return;
613 }
614
615 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800616 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
617 resultExtras.frameNumber, timestamp, resultExtras.requestId);
618 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
619 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
620 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800621 mInputReadyCondition.signal();
622 }
623}
624
625void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800626 auto i = mSettingsByFrameNumber.begin();
627 while (i != mSettingsByFrameNumber.end()) {
628 if (i->second.shutterNotified) {
629 mPendingInputFrames[i->first].orientation = i->second.orientation;
630 mPendingInputFrames[i->first].quality = i->second.quality;
631 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
632 mPendingInputFrames[i->first].requestId = i->second.requestId;
633 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
634 i->first, i->second.timestamp);
635 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700636
Shuzhen Wange8675782019-12-05 09:12:14 -0800637 // Set encoder quality if no inflight encoding
638 if (mPendingInputFrames.size() == 1) {
639 sp<StatusTracker> statusTracker = mStatusTracker.promote();
640 if (statusTracker != nullptr) {
641 statusTracker->markComponentActive(mStatusId);
642 ALOGV("%s: Mark component as active", __FUNCTION__);
643 }
644
645 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
646 updateCodecQualityLocked(newQuality);
647 }
648 } else {
649 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700650 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800651 }
652
Shuzhen Wange8675782019-12-05 09:12:14 -0800653 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800654 CpuConsumer::LockedBuffer imgBuffer;
655 auto it = mInputAppSegmentBuffers.begin();
656 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
657 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700658 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800659 break;
660 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
661 if (res != OK) {
662 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
663 strerror(-res), res);
664 } else {
665 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
666 " received buffer with time stamp: %" PRId64, __FUNCTION__,
667 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700668 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800669 }
670 mPendingInputFrames[*it].error = true;
671 mInputAppSegmentBuffers.erase(it);
672 continue;
673 }
674
Shuzhen Wange8675782019-12-05 09:12:14 -0800675 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
676 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
677 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700678 mInputAppSegmentBuffers.erase(it);
679 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800680 continue;
681 }
682
683 int64_t frameNumber = mAppSegmentFrameNumbers.front();
684 // If mPendingInputFrames doesn't contain the expected frame number, the captured
685 // input app segment frame must have been dropped via a buffer error. Simply
686 // return the buffer to the buffer queue.
687 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
688 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800689 mAppSegmentConsumer->unlockBuffer(imgBuffer);
690 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800691 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800692 }
693 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800694 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800695 }
696
Shuzhen Wange8675782019-12-05 09:12:14 -0800697 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800698 CpuConsumer::LockedBuffer imgBuffer;
699 auto it = mInputYuvBuffers.begin();
700 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
701 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700702 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800703 break;
704 } else if (res != OK) {
705 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
706 strerror(-res), res);
707 mPendingInputFrames[*it].error = true;
708 mInputYuvBuffers.erase(it);
709 continue;
710 } else if (*it != imgBuffer.timestamp) {
711 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
712 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
713 mPendingInputFrames[*it].error = true;
714 mInputYuvBuffers.erase(it);
715 continue;
716 }
717
Shuzhen Wange8675782019-12-05 09:12:14 -0800718 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
719 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
720 mMainImageFrameNumbers.front());
721 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700722 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800723 continue;
724 }
725
726 int64_t frameNumber = mMainImageFrameNumbers.front();
727 // If mPendingInputFrames doesn't contain the expected frame number, the captured
728 // input main image must have been dropped via a buffer error. Simply
729 // return the buffer to the buffer queue.
730 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
731 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800732 mMainImageConsumer->unlockBuffer(imgBuffer);
733 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800734 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800735 mYuvBufferAcquired = true;
736 }
737 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800738 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800739 }
740
741 while (!mCodecOutputBuffers.empty()) {
742 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800743 // Assume encoder input to output is FIFO, use a queue to look up
744 // frameNumber when handling codec outputs.
745 int64_t bufferFrameNumber = -1;
746 if (mCodecOutputBufferFrameNumbers.empty()) {
747 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700748 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800749 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800750 // Direct mapping between camera frame number and codec timestamp (in us).
751 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700752 mCodecOutputCounter++;
753 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800754 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700755 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800756 }
757
Shuzhen Wange8675782019-12-05 09:12:14 -0800758 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
759 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
760 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800761 }
762 mCodecOutputBuffers.erase(it);
763 }
764
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800765 while (!mCaptureResults.empty()) {
766 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800767 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800768 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800769 int64_t frameNumber = std::get<0>(it->second);
770 if (it->first >= 0 &&
771 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
772 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
773 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800774 std::make_unique<CameraMetadata>(std::get<1>(it->second));
775 } else {
776 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800777 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
778 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
779 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800780 }
781 }
782 mCaptureResults.erase(it);
783 }
784
785 // mErrorFrameNumbers stores frame number of dropped buffers.
786 auto it = mErrorFrameNumbers.begin();
787 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800788 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
789 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800790 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800791 //Error callback is guaranteed to arrive after shutter notify, which
792 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800793 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
794 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800795 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800796 it = mErrorFrameNumbers.erase(it);
797 }
798
799 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
800 it = mExifErrorFrameNumbers.begin();
801 while (it != mExifErrorFrameNumbers.end()) {
802 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
803 mPendingInputFrames[*it].exifError = true;
804 }
805 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800806 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800807
808 // Distribute codec input buffers to be filled out from YUV output
809 for (auto it = mPendingInputFrames.begin();
810 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
811 InputFrame& inputFrame(it->second);
812 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
813 // Available input tiles that are required for the current input
814 // image.
815 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
816 mGridRows * mGridCols - inputFrame.codecInputCounter);
817 for (size_t i = 0; i < newInputTiles; i++) {
818 CodecInputBufferInfo inputInfo =
819 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
820 inputFrame.codecInputBuffers.push_back(inputInfo);
821
822 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
823 inputFrame.codecInputCounter++;
824 }
825 break;
826 }
827 }
828}
829
Shuzhen Wange8675782019-12-05 09:12:14 -0800830bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
831 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800832 return false;
833 }
834
835 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700836 for (auto& it : mPendingInputFrames) {
837 // New input is considered to be available only if:
838 // 1. input buffers are ready, or
839 // 2. App segment and muxer is created, or
840 // 3. A codec output tile is ready, and an output buffer is available.
841 // This makes sure that muxer gets created only when an output tile is
842 // generated, because right now we only handle 1 HEIC output buffer at a
843 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800844 bool appSegmentReady =
845 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700846 !it.second.appSegmentWritten && it.second.result != nullptr &&
847 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800848 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
849 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
850 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700851 bool hasOutputBuffer = it.second.muxer != nullptr ||
852 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800853 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700854 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800855 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700856 if (it.second.format == nullptr && mFormat != nullptr) {
857 it.second.format = mFormat->dup();
858 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800859 newInputAvailable = true;
860 break;
861 }
862 }
863
864 return newInputAvailable;
865}
866
Shuzhen Wange8675782019-12-05 09:12:14 -0800867int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800868 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800869
870 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800871 if (it.second.error) {
872 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800873 break;
874 }
875 }
876
877 return res;
878}
879
Shuzhen Wange8675782019-12-05 09:12:14 -0800880status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800881 InputFrame &inputFrame) {
882 ATRACE_CALL();
883 status_t res = OK;
884
Shuzhen Wange8675782019-12-05 09:12:14 -0800885 bool appSegmentReady =
886 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700887 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
888 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800889 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
890 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700891 !inputFrame.codecInputBuffers.empty();
892 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
893 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800894
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700895 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800896 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
897 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
898 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800899
900 // Handle inputs for Hevc tiling
901 if (codecInputReady) {
902 res = processCodecInputFrame(inputFrame);
903 if (res != OK) {
904 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
905 strerror(-res), res);
906 return res;
907 }
908 }
909
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700910 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
911 return OK;
912 }
913
914 // Initialize and start muxer if not yet done so. In this case,
915 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
916 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800917 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800918 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800919 if (res != OK) {
920 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
921 strerror(-res), res);
922 return res;
923 }
924 }
925
926 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700927 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800928 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800929 if (res != OK) {
930 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
931 strerror(-res), res);
932 return res;
933 }
934 }
935
936 // Write media codec bitstream buffers to muxer.
937 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800938 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800939 if (res != OK) {
940 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
941 strerror(-res), res);
942 return res;
943 }
944 }
945
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700946 if (inputFrame.pendingOutputTiles == 0) {
947 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800948 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700949 if (res != OK) {
950 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
951 strerror(-res), res);
952 return res;
953 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800954 }
955 }
956
957 return res;
958}
959
Shuzhen Wange8675782019-12-05 09:12:14 -0800960status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800961 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800962
963 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
964 if (res != OK) {
965 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
966 res);
967 return res;
968 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700969 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800970
971 // Combine current thread id, stream id and timestamp to uniquely identify image.
972 std::ostringstream tempOutputFile;
973 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800974 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800975 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
976 if (inputFrame.fileFd < 0) {
977 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
978 tempOutputFile.str().c_str(), errno);
979 return NO_INIT;
980 }
Manisha Jajoo022b52f2021-10-09 00:51:42 +0530981 inputFrame.muxer = MediaMuxer::create(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800982 if (inputFrame.muxer == nullptr) {
983 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
984 __FUNCTION__, inputFrame.fileFd);
985 return NO_INIT;
986 }
987
988 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
989 if (res != OK) {
990 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
991 strerror(-res), res);
992 return res;
993 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800994
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700995 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800996 if (trackId < 0) {
997 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
998 return NO_INIT;
999 }
1000
1001 inputFrame.trackIndex = trackId;
1002 inputFrame.pendingOutputTiles = mNumOutputTiles;
1003
1004 res = inputFrame.muxer->start();
1005 if (res != OK) {
1006 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
1007 __FUNCTION__, strerror(-res), res);
1008 return res;
1009 }
1010
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001011 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -08001012 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001013 return OK;
1014}
1015
Shuzhen Wange8675782019-12-05 09:12:14 -08001016status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001017 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -08001018 size_t appSegmentSize = 0;
1019 if (!inputFrame.exifError) {
1020 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
1021 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
1022 &app1Size);
1023 if (appSegmentSize == 0) {
1024 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
1025 return NO_INIT;
1026 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001027 }
1028
1029 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -08001030 auto exifRes = inputFrame.exifError ?
1031 exifUtils->initializeEmpty() :
1032 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001033 if (!exifRes) {
1034 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
1035 return BAD_VALUE;
1036 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001037 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
1038 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001039 if (!exifRes) {
1040 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
1041 return BAD_VALUE;
1042 }
1043 exifRes = exifUtils->setOrientation(inputFrame.orientation);
1044 if (!exifRes) {
1045 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
1046 return BAD_VALUE;
1047 }
1048 exifRes = exifUtils->generateApp1();
1049 if (!exifRes) {
1050 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1051 return BAD_VALUE;
1052 }
1053
1054 unsigned int newApp1Length = exifUtils->getApp1Length();
1055 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1056
1057 //Assemble the APP1 marker buffer required by MediaCodec
1058 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1059 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1060 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1061 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1062 appSegmentSize - app1Size + newApp1Length;
1063 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1064 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1065 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1066 if (appSegmentSize - app1Size > 0) {
1067 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1068 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1069 }
1070
1071 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1072 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001073 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001074 delete[] appSegmentBuffer;
1075
1076 if (res != OK) {
1077 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1078 __FUNCTION__, strerror(-res), res);
1079 return res;
1080 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001081
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001082 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001083 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001084 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001085
1086 inputFrame.appSegmentWritten = true;
1087 // Release the buffer now so any pending input app segments can be processed
1088 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1089 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001090 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001091
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001092 return OK;
1093}
1094
1095status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1096 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1097 sp<MediaCodecBuffer> buffer;
1098 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1099 if (res != OK) {
1100 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1101 strerror(-res), res);
1102 return res;
1103 }
1104
1105 // Copy one tile from source to destination.
1106 size_t tileX = inputBuffer.tileIndex % mGridCols;
1107 size_t tileY = inputBuffer.tileIndex / mGridCols;
1108 size_t top = mGridHeight * tileY;
1109 size_t left = mGridWidth * tileX;
1110 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1111 mOutputWidth - tileX * mGridWidth : mGridWidth;
1112 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1113 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001114 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1115 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1116 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001117
1118 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1119 if (res != OK) {
1120 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1121 strerror(-res), res);
1122 return res;
1123 }
1124
1125 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1126 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1127 if (res != OK) {
1128 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1129 __FUNCTION__, strerror(-res), res);
1130 return res;
1131 }
1132 }
1133
1134 inputFrame.codecInputBuffers.clear();
1135 return OK;
1136}
1137
Shuzhen Wange8675782019-12-05 09:12:14 -08001138status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001139 InputFrame &inputFrame) {
1140 auto it = inputFrame.codecOutputBuffers.begin();
1141 sp<MediaCodecBuffer> buffer;
1142 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1143 if (res != OK) {
1144 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1145 __FUNCTION__, it->index, strerror(-res), res);
1146 return res;
1147 }
1148 if (buffer == nullptr) {
1149 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1150 __FUNCTION__, it->index);
1151 return BAD_VALUE;
1152 }
1153
1154 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1155 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001156 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001157 if (res != OK) {
1158 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1159 __FUNCTION__, it->index, strerror(-res), res);
1160 return res;
1161 }
1162
1163 mCodec->releaseOutputBuffer(it->index);
1164 if (inputFrame.pendingOutputTiles == 0) {
1165 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1166 } else {
1167 inputFrame.pendingOutputTiles--;
1168 }
1169
1170 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001171
1172 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001173 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001174 return OK;
1175}
1176
Shuzhen Wange8675782019-12-05 09:12:14 -08001177status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001178 InputFrame &inputFrame) {
1179 sp<ANativeWindow> outputANW = mOutputSurface;
1180 inputFrame.muxer->stop();
1181
1182 // Copy the content of the file to memory.
1183 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1184 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001185 GraphicBufferLocker gbLocker(gb);
1186 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001187 if (res != OK) {
1188 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1189 strerror(-res), res);
1190 return res;
1191 }
1192
1193 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1194 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1195 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1196 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1197 return BAD_VALUE;
1198 }
1199
1200 lseek(inputFrame.fileFd, 0, SEEK_SET);
1201 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1202 if (bytesRead < fSize) {
1203 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1204 return BAD_VALUE;
1205 }
1206
1207 close(inputFrame.fileFd);
1208 inputFrame.fileFd = -1;
1209
1210 // Fill in HEIC header
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001211 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
Shuzhen Wangdc519092022-12-02 12:29:04 -08001212 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1213 CameraBlob blobHeader = {
1214 .blobId = static_cast<CameraBlobId>(0x00FE),
1215 .blobSizeBytes = static_cast<int32_t>(fSize)
1216 };
1217 memcpy(header, &blobHeader, sizeof(CameraBlob));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001218
Shuzhen Wange8675782019-12-05 09:12:14 -08001219 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001220 if (res != OK) {
1221 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1222 __FUNCTION__, getStreamId(), strerror(-res), res);
1223 return res;
1224 }
1225
1226 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1227 if (res != OK) {
1228 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1229 strerror(-res), res);
1230 return res;
1231 }
1232 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001233 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001234
Shuzhen Wange8675782019-12-05 09:12:14 -08001235 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1236 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001237 return OK;
1238}
1239
1240
Shuzhen Wange8675782019-12-05 09:12:14 -08001241void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1242 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001243 if (inputFrame == nullptr) {
1244 return;
1245 }
1246
1247 if (inputFrame->appSegmentBuffer.data != nullptr) {
1248 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1249 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001250 }
1251
1252 while (!inputFrame->codecOutputBuffers.empty()) {
1253 auto it = inputFrame->codecOutputBuffers.begin();
1254 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1255 mCodec->releaseOutputBuffer(it->index);
1256 inputFrame->codecOutputBuffers.erase(it);
1257 }
1258
1259 if (inputFrame->yuvBuffer.data != nullptr) {
1260 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1261 inputFrame->yuvBuffer.data = nullptr;
1262 mYuvBufferAcquired = false;
1263 }
1264
1265 while (!inputFrame->codecInputBuffers.empty()) {
1266 auto it = inputFrame->codecInputBuffers.begin();
1267 inputFrame->codecInputBuffers.erase(it);
1268 }
1269
Shuzhen Wange8675782019-12-05 09:12:14 -08001270 if (inputFrame->error || mErrorState) {
1271 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1272 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001273 }
1274
1275 if (inputFrame->fileFd >= 0) {
1276 close(inputFrame->fileFd);
1277 inputFrame->fileFd = -1;
1278 }
1279
1280 if (inputFrame->anb != nullptr) {
1281 sp<ANativeWindow> outputANW = mOutputSurface;
1282 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1283 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001284
1285 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001286 }
1287}
1288
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001289void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001290 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001291 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001292 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001293 auto& inputFrame = it->second;
1294 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001295 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1296 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001297 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001298 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001299 } else {
1300 it++;
1301 }
1302 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001303
1304 // Update codec quality based on first upcoming input frame.
1305 // Note that when encoding is in surface mode, currently there is no
1306 // way for camera service to synchronize quality setting on a per-frame
1307 // basis: we don't get notification when codec is ready to consume a new
1308 // input frame. So we update codec quality on a best-effort basis.
1309 if (inputFrameDone) {
1310 auto firstPendingFrame = mPendingInputFrames.begin();
1311 if (firstPendingFrame != mPendingInputFrames.end()) {
1312 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001313 } else {
Shuzhen Wang40450572024-08-23 15:52:28 -07001314 if (mSettingsByFrameNumber.size() == 0) {
1315 markTrackerIdle();
1316 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001317 }
1318 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001319}
1320
1321status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1322 const sp<CameraDeviceBase>& cameraDevice) {
1323 ALOGV("%s", __FUNCTION__);
1324
1325 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001326 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001327 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001328 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001329 if (!isSizeSupported) {
1330 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1331 __FUNCTION__, width, height);
1332 return BAD_VALUE;
1333 }
1334
1335 // Create Looper for MediaCodec.
1336 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1337 mCodecLooper = new ALooper;
1338 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1339 status_t res = mCodecLooper->start(
1340 false, // runOnCallingThread
1341 false, // canCallJava
1342 PRIORITY_AUDIO);
1343 if (res != OK) {
1344 ALOGE("%s: Failed to start codec looper: %s (%d)",
1345 __FUNCTION__, strerror(-res), res);
1346 return NO_INIT;
1347 }
1348
1349 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001350 if (mUseHeic) {
1351 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1352 } else {
1353 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1354 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001355 if (mCodec == nullptr) {
1356 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1357 return NO_INIT;
1358 }
1359
1360 // Create Looper and handler for Codec callback.
1361 mCodecCallbackHandler = new CodecCallbackHandler(this);
1362 if (mCodecCallbackHandler == nullptr) {
1363 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1364 return NO_MEMORY;
1365 }
1366 mCallbackLooper = new ALooper;
1367 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1368 res = mCallbackLooper->start(
1369 false, // runOnCallingThread
1370 false, // canCallJava
1371 PRIORITY_AUDIO);
1372 if (res != OK) {
1373 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1374 __FUNCTION__, strerror(-res), res);
1375 return NO_INIT;
1376 }
1377 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1378
1379 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1380 res = mCodec->setCallback(mAsyncNotify);
1381 if (res != OK) {
1382 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1383 strerror(-res), res);
1384 return res;
1385 }
1386
1387 // Create output format and configure the Codec.
1388 sp<AMessage> outputFormat = new AMessage();
1389 outputFormat->setString(KEY_MIME, desiredMime);
1390 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1391 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1392 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001393 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001394
1395 int32_t gridWidth, gridHeight, gridRows, gridCols;
1396 if (useGrid || mUseHeic) {
1397 gridWidth = HeicEncoderInfoManager::kGridWidth;
1398 gridHeight = HeicEncoderInfoManager::kGridHeight;
1399 gridRows = (height + gridHeight - 1)/gridHeight;
1400 gridCols = (width + gridWidth - 1)/gridWidth;
1401
1402 if (mUseHeic) {
1403 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1404 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1405 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1406 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1407 }
1408
1409 } else {
1410 gridWidth = width;
1411 gridHeight = height;
1412 gridRows = 1;
1413 gridCols = 1;
1414 }
1415
1416 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1417 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1418 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1419 outputFormat->setInt32(KEY_COLOR_FORMAT,
1420 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001421 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001422 // This only serves as a hint to encoder when encoding is not real-time.
1423 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1424
1425 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1426 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1427 if (res != OK) {
1428 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1429 strerror(-res), res);
1430 return res;
1431 }
1432
1433 mGridWidth = gridWidth;
1434 mGridHeight = gridHeight;
1435 mGridRows = gridRows;
1436 mGridCols = gridCols;
1437 mUseGrid = useGrid;
1438 mOutputWidth = width;
1439 mOutputHeight = height;
1440 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001441 mMaxHeicBufferSize =
1442 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1443 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001444
1445 return OK;
1446}
1447
1448void HeicCompositeStream::deinitCodec() {
1449 ALOGV("%s", __FUNCTION__);
1450 if (mCodec != nullptr) {
1451 mCodec->stop();
1452 mCodec->release();
1453 mCodec.clear();
1454 }
1455
1456 if (mCodecLooper != nullptr) {
1457 mCodecLooper->stop();
1458 mCodecLooper.clear();
1459 }
1460
1461 if (mCallbackLooper != nullptr) {
1462 mCallbackLooper->stop();
1463 mCallbackLooper.clear();
1464 }
1465
1466 mAsyncNotify.clear();
1467 mFormat.clear();
1468}
1469
1470// Return the size of the complete list of app segment, 0 indicates failure
1471size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1472 size_t maxSize, size_t *app1SegmentSize) {
1473 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1474 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1475 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1476 return 0;
1477 }
1478
1479 size_t expectedSize = 0;
1480 // First check for EXIF transport header at the end of the buffer
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001481 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(CameraBlob));
1482 const CameraBlob *blob = (const CameraBlob*)(header);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001483 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001484 ALOGE("%s: Invalid EXIF blobId %d", __FUNCTION__, eToI(blob->blobId));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001485 return 0;
1486 }
1487
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001488 expectedSize = blob->blobSizeBytes;
1489 if (expectedSize == 0 || expectedSize > maxSize - sizeof(CameraBlob)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001490 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1491 return 0;
1492 }
1493
1494 uint32_t totalSize = 0;
1495
1496 // Verify APP1 marker (mandatory)
1497 uint8_t app1Marker[] = {0xFF, 0xE1};
1498 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1499 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1500 appSegmentBuffer[0], appSegmentBuffer[1]);
1501 return 0;
1502 }
1503 totalSize += sizeof(app1Marker);
1504
1505 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1506 appSegmentBuffer[totalSize+1];
1507 totalSize += app1Size;
1508
1509 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1510 __FUNCTION__, expectedSize, app1Size);
1511 while (totalSize < expectedSize) {
1512 if (appSegmentBuffer[totalSize] != 0xFF ||
1513 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1514 appSegmentBuffer[totalSize+1] > 0xEF) {
1515 // Invalid APPn marker
1516 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1517 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1518 return 0;
1519 }
1520 totalSize += 2;
1521
1522 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1523 appSegmentBuffer[totalSize+1];
1524 totalSize += appnSize;
1525 }
1526
1527 if (totalSize != expectedSize) {
1528 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1529 __FUNCTION__, totalSize, expectedSize);
1530 return 0;
1531 }
1532
1533 *app1SegmentSize = app1Size + sizeof(app1Marker);
1534 return expectedSize;
1535}
1536
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001537status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1538 const CpuConsumer::LockedBuffer& yuvBuffer,
1539 size_t top, size_t left, size_t width, size_t height) {
1540 ATRACE_CALL();
1541
1542 // Get stride information for codecBuffer
1543 sp<ABuffer> imageData;
1544 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1545 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1546 return BAD_VALUE;
1547 }
1548 if (imageData->size() != sizeof(MediaImage2)) {
1549 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1550 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1551 return BAD_VALUE;
1552 }
1553 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1554 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1555 imageInfo->mBitDepth != 8 ||
1556 imageInfo->mBitDepthAllocated != 8 ||
1557 imageInfo->mNumPlanes != 3) {
1558 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1559 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1560 imageInfo->mType, imageInfo->mBitDepth,
1561 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1562 return BAD_VALUE;
1563 }
1564
1565 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1566 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1567 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1568 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1569 imageInfo->mPlane[MediaImage2::V].mOffset,
1570 imageInfo->mPlane[MediaImage2::U].mRowInc,
1571 imageInfo->mPlane[MediaImage2::V].mRowInc,
1572 imageInfo->mPlane[MediaImage2::U].mColInc,
1573 imageInfo->mPlane[MediaImage2::V].mColInc);
1574
1575 // Y
1576 for (auto row = top; row < top+height; row++) {
1577 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1578 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001579 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001580 }
1581
1582 // U is Cb, V is Cr
1583 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1584 imageInfo->mPlane[MediaImage2::U].mOffset;
1585 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1586 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1587 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1588 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1589 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1590 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1591 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1592 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1593 bool isCodecUvPlannar =
1594 ((codecUPlaneFirst && codecUvOffsetDiff >=
1595 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1596 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1597 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1598 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1599 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1600 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1601
1602 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1603 (codecUPlaneFirst == cameraUPlaneFirst)) {
1604 // UV semiplannar
1605 // The chrome plane could be either Cb first, or Cr first. Take the
1606 // smaller address.
1607 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
Emilian Peev48ae29e2024-06-27 19:06:05 +00001608 MediaImage2::PlaneIndex dstPlane = codecUPlaneFirst ? MediaImage2::U : MediaImage2::V;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001609 for (auto row = top/2; row < (top+height)/2; row++) {
1610 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1611 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001612 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001613 }
1614 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1615 // U plane
1616 for (auto row = top/2; row < (top+height)/2; row++) {
1617 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1618 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001619 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001620 }
1621
1622 // V plane
1623 for (auto row = top/2; row < (top+height)/2; row++) {
1624 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1625 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001626 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001627 }
1628 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001629 // Convert between semiplannar and plannar, or when UV orders are
1630 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001631 uint8_t *dst = codecBuffer->data();
1632 for (auto row = top/2; row < (top+height)/2; row++) {
1633 for (auto col = left/2; col < (left+width)/2; col++) {
1634 // U/Cb
1635 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1636 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1637 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1638 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1639 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1640
1641 // V/Cr
1642 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1643 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1644 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1645 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1646 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1647 }
1648 }
1649 }
1650 return OK;
1651}
1652
Colin Cross14900c92023-01-13 14:50:17 -08001653void HeicCompositeStream::initCopyRowFunction([[maybe_unused]] int32_t width)
Shuzhen Wang219c2992019-02-15 17:24:28 -08001654{
1655 using namespace libyuv;
1656
1657 mFnCopyRow = CopyRow_C;
1658#if defined(HAS_COPYROW_SSE2)
1659 if (TestCpuFlag(kCpuHasSSE2)) {
1660 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1661 }
1662#endif
1663#if defined(HAS_COPYROW_AVX)
1664 if (TestCpuFlag(kCpuHasAVX)) {
1665 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1666 }
1667#endif
1668#if defined(HAS_COPYROW_ERMS)
1669 if (TestCpuFlag(kCpuHasERMS)) {
1670 mFnCopyRow = CopyRow_ERMS;
1671 }
1672#endif
1673#if defined(HAS_COPYROW_NEON)
1674 if (TestCpuFlag(kCpuHasNEON)) {
1675 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1676 }
1677#endif
1678#if defined(HAS_COPYROW_MIPS)
1679 if (TestCpuFlag(kCpuHasMIPS)) {
1680 mFnCopyRow = CopyRow_MIPS;
1681 }
1682#endif
1683}
1684
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001685size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1686 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1687 size_t maxAppsSegment = 1;
1688 if (entry.count > 0) {
1689 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1690 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1691 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001692 return maxAppsSegment * (2 + 0xFFFF) + sizeof(CameraBlob);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001693}
1694
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001695void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1696 if (quality != mQuality) {
1697 sp<AMessage> qualityParams = new AMessage;
1698 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1699 status_t res = mCodec->setParameters(qualityParams);
1700 if (res != OK) {
1701 ALOGE("%s: Failed to set codec quality: %s (%d)",
1702 __FUNCTION__, strerror(-res), res);
1703 } else {
1704 mQuality = quality;
1705 }
1706 }
1707}
1708
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001709bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001710 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001711 bool newInputAvailable = false;
1712
1713 {
1714 Mutex::Autolock l(mMutex);
1715 if (mErrorState) {
1716 // In case we landed in error state, return any pending buffers and
1717 // halt all further processing.
1718 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001719 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001720 return false;
1721 }
1722
1723
1724 while (!newInputAvailable) {
1725 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001726 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001727
1728 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001729 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001730 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001731 releaseInputFrameLocked(failingFrameNumber,
1732 &mPendingInputFrames[failingFrameNumber]);
1733
1734 // It's okay to remove the entry from mPendingInputFrames
1735 // because:
1736 // 1. Only one internal stream (main input) is critical in
1737 // backing the output stream.
1738 // 2. If captureResult/appSegment arrives after the entry is
1739 // removed, they are simply skipped.
1740 mPendingInputFrames.erase(failingFrameNumber);
1741 if (mPendingInputFrames.size() == 0) {
Shuzhen Wang40450572024-08-23 15:52:28 -07001742 if (mSettingsByFrameNumber.size() == 0) {
1743 markTrackerIdle();
1744 }
Shuzhen Wange8675782019-12-05 09:12:14 -08001745 }
1746 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001747 }
1748
1749 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1750 if (ret == TIMED_OUT) {
1751 return true;
1752 } else if (ret != OK) {
1753 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1754 strerror(-ret), ret);
1755 return false;
1756 }
1757 }
1758 }
1759 }
1760
Shuzhen Wange8675782019-12-05 09:12:14 -08001761 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001762 Mutex::Autolock l(mMutex);
1763 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001764 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1765 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1766 frameNumber, strerror(-res), res);
1767 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001768 }
1769
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001770 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001771
1772 return true;
1773}
1774
Shuzhen Wange8675782019-12-05 09:12:14 -08001775void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1776 Mutex::Autolock l(mMutex);
1777 mExifErrorFrameNumbers.emplace(frameNumber);
1778 mInputReadyCondition.signal();
1779}
1780
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001781bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1782 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001783 int64_t frameNumber = resultExtras.frameNumber;
1784
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001785 // Buffer errors concerning internal composite streams should not be directly visible to
1786 // camera clients. They must only receive a single buffer error with the public composite
1787 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001788 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1789 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1790 flagAnExifErrorFrameNumber(frameNumber);
1791 res = true;
1792 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1793 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1794 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001795 res = true;
1796 }
1797
1798 return res;
1799}
1800
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001801void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1802 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1803 // simply skip using the capture result metadata to override EXIF.
1804 Mutex::Autolock l(mMutex);
1805
1806 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001807 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001808 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001809 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001810 break;
1811 }
1812 }
1813 if (timestamp == -1) {
1814 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001815 if (inputFrame.first == resultExtras.frameNumber) {
1816 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001817 break;
1818 }
1819 }
1820 }
1821
1822 if (timestamp == -1) {
1823 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1824 return;
1825 }
1826
1827 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001828 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1829 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001830 mInputReadyCondition.signal();
1831}
1832
Shuzhen Wange8675782019-12-05 09:12:14 -08001833void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1834 auto frameNumber = resultExtras.frameNumber;
1835 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1836 Mutex::Autolock l(mMutex);
1837 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1838 if (numRequests == 0) {
1839 // Pending request has been populated into mPendingInputFrames
1840 mErrorFrameNumbers.emplace(frameNumber);
1841 mInputReadyCondition.signal();
1842 } else {
1843 // REQUEST_ERROR was received without onShutter.
1844 }
1845}
1846
1847void HeicCompositeStream::markTrackerIdle() {
1848 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1849 if (statusTracker != nullptr) {
1850 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1851 ALOGV("%s: Mark component as idle", __FUNCTION__);
1852 }
1853}
1854
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001855void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1856 sp<HeicCompositeStream> parent = mParent.promote();
1857 if (parent == nullptr) return;
1858
1859 switch (msg->what()) {
1860 case kWhatCallbackNotify: {
1861 int32_t cbID;
1862 if (!msg->findInt32("callbackID", &cbID)) {
1863 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1864 break;
1865 }
1866
1867 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1868
1869 switch (cbID) {
1870 case MediaCodec::CB_INPUT_AVAILABLE: {
1871 int32_t index;
1872 if (!msg->findInt32("index", &index)) {
1873 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1874 break;
1875 }
1876 parent->onHeicInputFrameAvailable(index);
1877 break;
1878 }
1879
1880 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1881 int32_t index;
1882 size_t offset;
1883 size_t size;
1884 int64_t timeUs;
1885 int32_t flags;
1886
1887 if (!msg->findInt32("index", &index)) {
1888 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1889 break;
1890 }
1891 if (!msg->findSize("offset", &offset)) {
1892 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1893 break;
1894 }
1895 if (!msg->findSize("size", &size)) {
1896 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1897 break;
1898 }
1899 if (!msg->findInt64("timeUs", &timeUs)) {
1900 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1901 break;
1902 }
1903 if (!msg->findInt32("flags", &flags)) {
1904 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1905 break;
1906 }
1907
1908 CodecOutputBufferInfo bufferInfo = {
1909 index,
1910 (int32_t)offset,
1911 (int32_t)size,
1912 timeUs,
1913 (uint32_t)flags};
1914
1915 parent->onHeicOutputFrameAvailable(bufferInfo);
1916 break;
1917 }
1918
1919 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1920 sp<AMessage> format;
1921 if (!msg->findMessage("format", &format)) {
1922 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1923 break;
1924 }
Chong Zhang860eff12019-09-16 16:15:00 -07001925 // Here format is MediaCodec's internal copy of output format.
1926 // Make a copy since onHeicFormatChanged() might modify it.
1927 sp<AMessage> formatCopy;
1928 if (format != nullptr) {
1929 formatCopy = format->dup();
1930 }
1931 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001932 break;
1933 }
1934
1935 case MediaCodec::CB_ERROR: {
1936 status_t err;
1937 int32_t actionCode;
1938 AString detail;
1939 if (!msg->findInt32("err", &err)) {
1940 ALOGE("CB_ERROR: err is expected.");
1941 break;
1942 }
1943 if (!msg->findInt32("action", &actionCode)) {
1944 ALOGE("CB_ERROR: action is expected.");
1945 break;
1946 }
1947 msg->findString("detail", &detail);
1948 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1949 err, actionCode, detail.c_str());
1950
1951 parent->onHeicCodecError();
1952 break;
1953 }
1954
1955 default: {
1956 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1957 break;
1958 }
1959 }
1960 break;
1961 }
1962
1963 default:
1964 ALOGE("shouldn't be here");
1965 break;
1966 }
1967}
1968
1969}; // namespace camera3
1970}; // namespace android