blob: 2f05d4da0c9e3db2ca90f03f44059ba6f2770c00 [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>
Shuzhen Wang219c2992019-02-15 17:24:28 -080028#include <libyuv.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080029#include <gui/Surface.h>
30#include <utils/Log.h>
31#include <utils/Trace.h>
Austin Borger1c1bee02023-06-01 16:51:35 -070032#include <camera/StringUtils.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080033
Marco Nelissen13aa1a42019-09-27 10:21:55 -070034#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080035#include <media/MediaCodecBuffer.h>
36#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080037#include <media/stagefright/foundation/MediaDefs.h>
38#include <media/stagefright/MediaCodecConstants.h>
39
40#include "common/CameraDeviceBase.h"
41#include "utils/ExifUtils.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080042#include "utils/SessionConfigurationUtils.h"
Eino-Ville Talvalab7723202024-06-24 17:45:51 -070043#include "utils/Utils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080044#include "HeicEncoderInfoManager.h"
45#include "HeicCompositeStream.h"
46
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000047using aidl::android::hardware::camera::device::CameraBlob;
48using aidl::android::hardware::camera::device::CameraBlobId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080049
50namespace android {
51namespace camera3 {
52
Shuzhen Wange8675782019-12-05 09:12:14 -080053HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080054 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
55 CompositeStream(device, cb),
56 mUseHeic(false),
57 mNumOutputTiles(1),
58 mOutputWidth(0),
59 mOutputHeight(0),
60 mMaxHeicBufferSize(0),
61 mGridWidth(HeicEncoderInfoManager::kGridWidth),
62 mGridHeight(HeicEncoderInfoManager::kGridHeight),
63 mGridRows(1),
64 mGridCols(1),
65 mUseGrid(false),
66 mAppSegmentStreamId(-1),
67 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080068 mMainImageStreamId(-1),
69 mMainImageSurfaceId(-1),
70 mYuvBufferAcquired(false),
Carlos Martinez Romeroae9834f2024-07-03 13:33:47 -070071 mStreamSurfaceListener(new StreamSurfaceListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070072 mDequeuedOutputBufferCnt(0),
73 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070074 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080075 mGridTimestampUs(0),
76 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080077}
78
79HeicCompositeStream::~HeicCompositeStream() {
80 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
81 // memory/resource leak.
82 deinitCodec();
83
84 mInputAppSegmentBuffers.clear();
85 mCodecOutputBuffers.clear();
86
87 mAppSegmentStreamId = -1;
88 mAppSegmentSurfaceId = -1;
89 mAppSegmentConsumer.clear();
90 mAppSegmentSurface.clear();
91
92 mMainImageStreamId = -1;
93 mMainImageSurfaceId = -1;
94 mMainImageConsumer.clear();
95 mMainImageSurface.clear();
96}
97
Emilian Peeve75a2852024-05-20 22:35:15 +000098bool HeicCompositeStream::isHeicCompositeStreamInfo(const OutputStreamInfo& streamInfo) {
99 return ((streamInfo.dataSpace == static_cast<android_dataspace_t>(HAL_DATASPACE_HEIF)) &&
100 (streamInfo.format == HAL_PIXEL_FORMAT_BLOB));
101}
102
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800103bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
104 ANativeWindow *anw = surface.get();
105 status_t err;
106 int format;
107 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
Austin Borger1c1bee02023-06-01 16:51:35 -0700108 std::string msg = fmt::sprintf("Failed to query Surface format: %s (%d)", strerror(-err),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800109 err);
Austin Borger1c1bee02023-06-01 16:51:35 -0700110 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800111 return false;
112 }
113
114 int dataspace;
115 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
Austin Borger1c1bee02023-06-01 16:51:35 -0700116 std::string msg = fmt::sprintf("Failed to query Surface dataspace: %s (%d)", strerror(-err),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800117 err);
Austin Borger1c1bee02023-06-01 16:51:35 -0700118 ALOGE("%s: %s", __FUNCTION__, msg.c_str());
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800119 return false;
120 }
121
122 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
123}
124
125status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
126 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
Austin Borger1c1bee02023-06-01 16:51:35 -0700127 camera_stream_rotation_t rotation, int *id, const std::string& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800128 const std::unordered_set<int32_t> &sensorPixelModesUsed,
129 std::vector<int> *surfaceIds,
Syed Haqc8a536d2023-05-09 12:14:52 -0700130 int /*streamSetId*/, bool /*isShared*/, int32_t colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000131 int64_t /*dynamicProfile*/, int64_t /*streamUseCase*/, bool useReadoutTimestamp) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800132 sp<CameraDeviceBase> device = mDevice.promote();
133 if (!device.get()) {
134 ALOGE("%s: Invalid camera device!", __FUNCTION__);
135 return NO_INIT;
136 }
137
138 status_t res = initializeCodec(width, height, device);
139 if (res != OK) {
140 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
141 __FUNCTION__, strerror(-res), res);
142 return NO_INIT;
143 }
144
145 sp<IGraphicBufferProducer> producer;
146 sp<IGraphicBufferConsumer> consumer;
147 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700148 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800149 mAppSegmentConsumer->setFrameAvailableListener(this);
150 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
151 mAppSegmentSurface = new Surface(producer);
152
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800153 mStaticInfo = device->info();
154
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800155 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800156 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000157 sensorPixelModesUsed, surfaceIds, camera3::CAMERA3_STREAM_SET_ID_INVALID,
158 /*isShared*/false, /*isMultiResolution*/false,
159 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
160 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
161 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
162 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700163 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000164 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800165 if (res == OK) {
166 mAppSegmentSurfaceId = (*surfaceIds)[0];
167 } else {
168 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
169 strerror(-res), res);
170 return res;
171 }
172
173 if (!mUseGrid) {
174 res = mCodec->createInputSurface(&producer);
175 if (res != OK) {
176 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
177 __FUNCTION__, strerror(-res), res);
178 return res;
179 }
180 } else {
181 BufferQueue::createBufferQueue(&producer, &consumer);
182 mMainImageConsumer = new CpuConsumer(consumer, 1);
183 mMainImageConsumer->setFrameAvailableListener(this);
184 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
185 }
186 mMainImageSurface = new Surface(producer);
187
188 res = mCodec->start();
189 if (res != OK) {
190 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
191 strerror(-res), res);
192 return res;
193 }
194
195 std::vector<int> sourceSurfaceId;
196 //Use YUV_888 format if framework tiling is needed.
197 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
198 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
199 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000200 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId,
201 camera3::CAMERA3_STREAM_SET_ID_INVALID, /*isShared*/false, /*isMultiResolution*/false,
202 /*consumerUsage*/0, ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
203 ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
204 OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
205 OutputConfiguration::MIRROR_MODE_AUTO,
Syed Haqc8a536d2023-05-09 12:14:52 -0700206 colorSpace,
Shuzhen Wangbce53db2022-12-03 00:38:20 +0000207 useReadoutTimestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800208 if (res == OK) {
209 mMainImageSurfaceId = sourceSurfaceId[0];
210 mMainImageStreamId = *id;
211 } else {
212 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
213 strerror(-res), res);
214 return res;
215 }
216
217 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800218 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800219 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800220 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
221 strerror(-res), res);
222 return res;
223 }
224
225 res = registerCompositeStreamListener(mAppSegmentStreamId);
226 if (res != OK) {
227 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
228 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800229 return res;
230 }
231
Shuzhen Wang219c2992019-02-15 17:24:28 -0800232 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800233 return res;
234}
235
236status_t HeicCompositeStream::deleteInternalStreams() {
237 requestExit();
238 auto res = join();
239 if (res != OK) {
240 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
241 strerror(-res), res);
242 }
243
244 deinitCodec();
245
246 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700247 // Camera devices may not be valid after switching to offline mode.
248 // In this case, all offline streams including internal composite streams
249 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800250 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700251 if (device.get() != nullptr) {
252 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800253 }
254
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800255 mAppSegmentStreamId = -1;
256 }
257
Shuzhen Wang2c545042019-02-07 10:27:35 -0800258 if (mOutputSurface != nullptr) {
259 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
260 mOutputSurface.clear();
261 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800262
263 sp<StatusTracker> statusTracker = mStatusTracker.promote();
264 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
265 statusTracker->removeComponent(mStatusId);
266 mStatusId = StatusTracker::NO_STATUS_ID;
267 }
268
269 if (mPendingInputFrames.size() > 0) {
270 ALOGW("%s: mPendingInputFrames has %zu stale entries",
271 __FUNCTION__, mPendingInputFrames.size());
272 mPendingInputFrames.clear();
273 }
274
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800275 return res;
276}
277
278void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
279 Mutex::Autolock l(mMutex);
280
281 if (bufferInfo.mError) return;
282
Shuzhen Wange8675782019-12-05 09:12:14 -0800283 if (bufferInfo.mStreamId == mMainImageStreamId) {
284 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
285 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
286 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
287 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
288 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
289 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
290 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
291 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
292 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800293}
294
295// We need to get the settings early to handle the case where the codec output
296// arrives earlier than result metadata.
297void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
298 const CameraMetadata& settings) {
299 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
300
301 Mutex::Autolock l(mMutex);
302 if (mErrorState || (streamId != getStreamId())) {
303 return;
304 }
305
306 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
307
308 camera_metadata_ro_entry entry;
309
310 int32_t orientation = 0;
311 entry = settings.find(ANDROID_JPEG_ORIENTATION);
312 if (entry.count == 1) {
313 orientation = entry.data.i32[0];
314 }
315
316 int32_t quality = kDefaultJpegQuality;
317 entry = settings.find(ANDROID_JPEG_QUALITY);
318 if (entry.count == 1) {
319 quality = entry.data.i32[0];
320 }
321
Shuzhen Wange8675782019-12-05 09:12:14 -0800322 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800323}
324
325void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
326 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
327 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
328 __func__, ns2ms(item.mTimestamp));
329
330 Mutex::Autolock l(mMutex);
331 if (!mErrorState) {
332 mInputAppSegmentBuffers.push_back(item.mTimestamp);
333 mInputReadyCondition.signal();
334 }
335 } else if (item.mDataSpace == kHeifDataSpace) {
336 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
337 __func__, ns2ms(item.mTimestamp));
338
339 Mutex::Autolock l(mMutex);
340 if (!mUseGrid) {
341 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
342 __FUNCTION__);
343 return;
344 }
345 if (!mErrorState) {
346 mInputYuvBuffers.push_back(item.mTimestamp);
347 mInputReadyCondition.signal();
348 }
349 } else {
350 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
351 }
352}
353
354status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
355 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
356 if (compositeOutput == nullptr) {
357 return BAD_VALUE;
358 }
359
360 compositeOutput->clear();
361
362 bool useGrid, useHeic;
363 bool isSizeSupported = isSizeSupportedByHeifEncoder(
364 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
365 if (!isSizeSupported) {
366 // Size is not supported by either encoder.
367 return OK;
368 }
369
370 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
371
372 // JPEG APPS segments Blob stream info
373 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
374 (*compositeOutput)[0].height = 1;
375 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
376 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
377 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
378
379 // YUV/IMPLEMENTATION_DEFINED stream info
380 (*compositeOutput)[1].width = streamInfo.width;
381 (*compositeOutput)[1].height = streamInfo.height;
382 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
383 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
384 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
385 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
386 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
387
388 return NO_ERROR;
389}
390
391bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700392 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800393 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700394 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800395}
396
397bool HeicCompositeStream::isInMemoryTempFileSupported() {
398 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
399 if (memfd == -1) {
400 if (errno != ENOSYS) {
401 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
402 }
403 return false;
404 }
405 close(memfd);
406 return true;
407}
408
409void HeicCompositeStream::onHeicOutputFrameAvailable(
410 const CodecOutputBufferInfo& outputBufferInfo) {
411 Mutex::Autolock l(mMutex);
412
413 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
414 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
415 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
416
417 if (!mErrorState) {
418 if ((outputBufferInfo.size > 0) &&
419 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
420 mCodecOutputBuffers.push_back(outputBufferInfo);
421 mInputReadyCondition.signal();
422 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700423 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
424 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800425 mCodec->releaseOutputBuffer(outputBufferInfo.index);
426 }
427 } else {
428 mCodec->releaseOutputBuffer(outputBufferInfo.index);
429 }
430}
431
432void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
433 Mutex::Autolock l(mMutex);
434
435 if (!mUseGrid) {
436 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
437 return;
438 }
439
440 mCodecInputBuffers.push_back(index);
441 mInputReadyCondition.signal();
442}
443
444void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
445 if (newFormat == nullptr) {
446 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
447 return;
448 }
449
450 Mutex::Autolock l(mMutex);
451
452 AString mime;
453 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
454 newFormat->findString(KEY_MIME, &mime);
455 if (mime != mimeHeic) {
456 // For HEVC codec, below keys need to be filled out or overwritten so that the
457 // muxer can handle them as HEIC output image.
458 newFormat->setString(KEY_MIME, mimeHeic);
459 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
460 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000461 }
462
463 if (mUseGrid || mUseHeic) {
464 int32_t gridRows, gridCols, tileWidth, tileHeight;
465 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
466 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols) &&
467 newFormat->findInt32(KEY_TILE_WIDTH, &tileWidth) &&
468 newFormat->findInt32(KEY_TILE_HEIGHT, &tileHeight)) {
469 mGridWidth = tileWidth;
470 mGridHeight = tileHeight;
471 mGridRows = gridRows;
472 mGridCols = gridCols;
473 } else {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800474 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
475 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
476 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
477 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
Shuzhen Wang1403d952023-07-31 20:42:19 +0000478 }
479 int32_t left, top, right, bottom;
480 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
481 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800482 }
483 }
484 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
485
486 int32_t gridRows, gridCols;
487 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
488 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
489 mNumOutputTiles = gridRows * gridCols;
490 } else {
491 mNumOutputTiles = 1;
492 }
493
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800494 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700495
496 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
497 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800498}
499
500void HeicCompositeStream::onHeicCodecError() {
501 Mutex::Autolock l(mMutex);
502 mErrorState = true;
503}
504
505status_t HeicCompositeStream::configureStream() {
506 if (isRunning()) {
507 // Processing thread is already running, nothing more to do.
508 return NO_ERROR;
509 }
510
511 if (mOutputSurface.get() == nullptr) {
512 ALOGE("%s: No valid output surface set!", __FUNCTION__);
513 return NO_INIT;
514 }
515
Carlos Martinez Romeroae9834f2024-07-03 13:33:47 -0700516 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mStreamSurfaceListener);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800517 if (res != OK) {
518 ALOGE("%s: Unable to connect to native window for stream %d",
519 __FUNCTION__, mMainImageStreamId);
520 return res;
521 }
522
523 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
524 != OK) {
525 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
526 mMainImageStreamId);
527 return res;
528 }
529
530 ANativeWindow *anwConsumer = mOutputSurface.get();
531 int maxConsumerBuffers;
532 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
533 &maxConsumerBuffers)) != OK) {
534 ALOGE("%s: Unable to query consumer undequeued"
535 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
536 return res;
537 }
538
539 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
540 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800541 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700542 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800543 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
544 return res;
545 }
546
547 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
548 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
549 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
550 return res;
551 }
552
Shuzhen Wange8675782019-12-05 09:12:14 -0800553 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
554 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700555 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
556 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800557 }
558
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800559 run("HeicCompositeStreamProc");
560
561 return NO_ERROR;
562}
563
564status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
565 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
566 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800567 outputStreamIds->push_back(mAppSegmentStreamId);
568 }
569 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
570
571 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800572 outputStreamIds->push_back(mMainImageStreamId);
573 }
574 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
575
576 if (currentStreamId != nullptr) {
577 *currentStreamId = mMainImageStreamId;
578 }
579
580 return NO_ERROR;
581}
582
Emilian Peev4697b642019-11-19 17:11:14 -0800583status_t HeicCompositeStream::insertCompositeStreamIds(
584 std::vector<int32_t>* compositeStreamIds /*out*/) {
585 if (compositeStreamIds == nullptr) {
586 return BAD_VALUE;
587 }
588
589 compositeStreamIds->push_back(mAppSegmentStreamId);
590 compositeStreamIds->push_back(mMainImageStreamId);
591
592 return OK;
593}
594
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800595void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
596 Mutex::Autolock l(mMutex);
597 if (mErrorState) {
598 return;
599 }
600
601 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800602 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
603 resultExtras.frameNumber, timestamp, resultExtras.requestId);
604 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
605 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
606 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800607 mInputReadyCondition.signal();
608 }
609}
610
611void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800612 auto i = mSettingsByFrameNumber.begin();
613 while (i != mSettingsByFrameNumber.end()) {
614 if (i->second.shutterNotified) {
615 mPendingInputFrames[i->first].orientation = i->second.orientation;
616 mPendingInputFrames[i->first].quality = i->second.quality;
617 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
618 mPendingInputFrames[i->first].requestId = i->second.requestId;
619 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
620 i->first, i->second.timestamp);
621 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700622
Shuzhen Wange8675782019-12-05 09:12:14 -0800623 // Set encoder quality if no inflight encoding
624 if (mPendingInputFrames.size() == 1) {
625 sp<StatusTracker> statusTracker = mStatusTracker.promote();
626 if (statusTracker != nullptr) {
627 statusTracker->markComponentActive(mStatusId);
628 ALOGV("%s: Mark component as active", __FUNCTION__);
629 }
630
631 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
632 updateCodecQualityLocked(newQuality);
633 }
634 } else {
635 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700636 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800637 }
638
Shuzhen Wange8675782019-12-05 09:12:14 -0800639 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800640 CpuConsumer::LockedBuffer imgBuffer;
641 auto it = mInputAppSegmentBuffers.begin();
642 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
643 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700644 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800645 break;
646 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
647 if (res != OK) {
648 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
649 strerror(-res), res);
650 } else {
651 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
652 " received buffer with time stamp: %" PRId64, __FUNCTION__,
653 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700654 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800655 }
656 mPendingInputFrames[*it].error = true;
657 mInputAppSegmentBuffers.erase(it);
658 continue;
659 }
660
Shuzhen Wange8675782019-12-05 09:12:14 -0800661 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
662 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
663 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700664 mInputAppSegmentBuffers.erase(it);
665 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800666 continue;
667 }
668
669 int64_t frameNumber = mAppSegmentFrameNumbers.front();
670 // If mPendingInputFrames doesn't contain the expected frame number, the captured
671 // input app segment frame must have been dropped via a buffer error. Simply
672 // return the buffer to the buffer queue.
673 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
674 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800675 mAppSegmentConsumer->unlockBuffer(imgBuffer);
676 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800677 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800678 }
679 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800680 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800681 }
682
Shuzhen Wange8675782019-12-05 09:12:14 -0800683 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800684 CpuConsumer::LockedBuffer imgBuffer;
685 auto it = mInputYuvBuffers.begin();
686 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
687 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700688 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800689 break;
690 } else if (res != OK) {
691 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
692 strerror(-res), res);
693 mPendingInputFrames[*it].error = true;
694 mInputYuvBuffers.erase(it);
695 continue;
696 } else if (*it != imgBuffer.timestamp) {
697 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
698 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
699 mPendingInputFrames[*it].error = true;
700 mInputYuvBuffers.erase(it);
701 continue;
702 }
703
Shuzhen Wange8675782019-12-05 09:12:14 -0800704 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
705 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
706 mMainImageFrameNumbers.front());
707 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700708 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800709 continue;
710 }
711
712 int64_t frameNumber = mMainImageFrameNumbers.front();
713 // If mPendingInputFrames doesn't contain the expected frame number, the captured
714 // input main image must have been dropped via a buffer error. Simply
715 // return the buffer to the buffer queue.
716 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
717 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800718 mMainImageConsumer->unlockBuffer(imgBuffer);
719 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800720 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800721 mYuvBufferAcquired = true;
722 }
723 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800724 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800725 }
726
727 while (!mCodecOutputBuffers.empty()) {
728 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800729 // Assume encoder input to output is FIFO, use a queue to look up
730 // frameNumber when handling codec outputs.
731 int64_t bufferFrameNumber = -1;
732 if (mCodecOutputBufferFrameNumbers.empty()) {
733 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700734 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800735 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800736 // Direct mapping between camera frame number and codec timestamp (in us).
737 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700738 mCodecOutputCounter++;
739 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800740 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700741 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800742 }
743
Shuzhen Wange8675782019-12-05 09:12:14 -0800744 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
745 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
746 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800747 }
748 mCodecOutputBuffers.erase(it);
749 }
750
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800751 while (!mCaptureResults.empty()) {
752 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800753 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800754 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800755 int64_t frameNumber = std::get<0>(it->second);
756 if (it->first >= 0 &&
757 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
758 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
759 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800760 std::make_unique<CameraMetadata>(std::get<1>(it->second));
761 } else {
762 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800763 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
764 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
765 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800766 }
767 }
768 mCaptureResults.erase(it);
769 }
770
771 // mErrorFrameNumbers stores frame number of dropped buffers.
772 auto it = mErrorFrameNumbers.begin();
773 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800774 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
775 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800776 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800777 //Error callback is guaranteed to arrive after shutter notify, which
778 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800779 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
780 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800781 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800782 it = mErrorFrameNumbers.erase(it);
783 }
784
785 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
786 it = mExifErrorFrameNumbers.begin();
787 while (it != mExifErrorFrameNumbers.end()) {
788 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
789 mPendingInputFrames[*it].exifError = true;
790 }
791 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800792 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800793
794 // Distribute codec input buffers to be filled out from YUV output
795 for (auto it = mPendingInputFrames.begin();
796 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
797 InputFrame& inputFrame(it->second);
798 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
799 // Available input tiles that are required for the current input
800 // image.
801 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
802 mGridRows * mGridCols - inputFrame.codecInputCounter);
803 for (size_t i = 0; i < newInputTiles; i++) {
804 CodecInputBufferInfo inputInfo =
805 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
806 inputFrame.codecInputBuffers.push_back(inputInfo);
807
808 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
809 inputFrame.codecInputCounter++;
810 }
811 break;
812 }
813 }
814}
815
Shuzhen Wange8675782019-12-05 09:12:14 -0800816bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
817 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800818 return false;
819 }
820
821 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700822 for (auto& it : mPendingInputFrames) {
823 // New input is considered to be available only if:
824 // 1. input buffers are ready, or
825 // 2. App segment and muxer is created, or
826 // 3. A codec output tile is ready, and an output buffer is available.
827 // This makes sure that muxer gets created only when an output tile is
828 // generated, because right now we only handle 1 HEIC output buffer at a
829 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800830 bool appSegmentReady =
831 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700832 !it.second.appSegmentWritten && it.second.result != nullptr &&
833 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800834 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
835 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
836 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700837 bool hasOutputBuffer = it.second.muxer != nullptr ||
838 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800839 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700840 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800841 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700842 if (it.second.format == nullptr && mFormat != nullptr) {
843 it.second.format = mFormat->dup();
844 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800845 newInputAvailable = true;
846 break;
847 }
848 }
849
850 return newInputAvailable;
851}
852
Shuzhen Wange8675782019-12-05 09:12:14 -0800853int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800854 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800855
856 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800857 if (it.second.error) {
858 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800859 break;
860 }
861 }
862
863 return res;
864}
865
Shuzhen Wange8675782019-12-05 09:12:14 -0800866status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800867 InputFrame &inputFrame) {
868 ATRACE_CALL();
869 status_t res = OK;
870
Shuzhen Wange8675782019-12-05 09:12:14 -0800871 bool appSegmentReady =
872 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700873 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
874 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800875 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
876 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700877 !inputFrame.codecInputBuffers.empty();
878 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
879 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800880
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700881 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800882 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
883 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
884 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800885
886 // Handle inputs for Hevc tiling
887 if (codecInputReady) {
888 res = processCodecInputFrame(inputFrame);
889 if (res != OK) {
890 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
891 strerror(-res), res);
892 return res;
893 }
894 }
895
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700896 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
897 return OK;
898 }
899
900 // Initialize and start muxer if not yet done so. In this case,
901 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
902 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800903 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800904 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800905 if (res != OK) {
906 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
907 strerror(-res), res);
908 return res;
909 }
910 }
911
912 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700913 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800914 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800915 if (res != OK) {
916 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
917 strerror(-res), res);
918 return res;
919 }
920 }
921
922 // Write media codec bitstream buffers to muxer.
923 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800924 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800925 if (res != OK) {
926 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
927 strerror(-res), res);
928 return res;
929 }
930 }
931
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700932 if (inputFrame.pendingOutputTiles == 0) {
933 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800934 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700935 if (res != OK) {
936 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
937 strerror(-res), res);
938 return res;
939 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800940 }
941 }
942
943 return res;
944}
945
Shuzhen Wange8675782019-12-05 09:12:14 -0800946status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800947 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800948
949 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
950 if (res != OK) {
951 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
952 res);
953 return res;
954 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700955 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800956
957 // Combine current thread id, stream id and timestamp to uniquely identify image.
958 std::ostringstream tempOutputFile;
959 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800960 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800961 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
962 if (inputFrame.fileFd < 0) {
963 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
964 tempOutputFile.str().c_str(), errno);
965 return NO_INIT;
966 }
Manisha Jajoo022b52f2021-10-09 00:51:42 +0530967 inputFrame.muxer = MediaMuxer::create(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800968 if (inputFrame.muxer == nullptr) {
969 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
970 __FUNCTION__, inputFrame.fileFd);
971 return NO_INIT;
972 }
973
974 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
975 if (res != OK) {
976 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
977 strerror(-res), res);
978 return res;
979 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800980
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700981 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800982 if (trackId < 0) {
983 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
984 return NO_INIT;
985 }
986
987 inputFrame.trackIndex = trackId;
988 inputFrame.pendingOutputTiles = mNumOutputTiles;
989
990 res = inputFrame.muxer->start();
991 if (res != OK) {
992 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
993 __FUNCTION__, strerror(-res), res);
994 return res;
995 }
996
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700997 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800998 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800999 return OK;
1000}
1001
Shuzhen Wange8675782019-12-05 09:12:14 -08001002status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001003 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -08001004 size_t appSegmentSize = 0;
1005 if (!inputFrame.exifError) {
1006 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
1007 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
1008 &app1Size);
1009 if (appSegmentSize == 0) {
1010 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
1011 return NO_INIT;
1012 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001013 }
1014
1015 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -08001016 auto exifRes = inputFrame.exifError ?
1017 exifUtils->initializeEmpty() :
1018 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001019 if (!exifRes) {
1020 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
1021 return BAD_VALUE;
1022 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001023 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
1024 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001025 if (!exifRes) {
1026 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
1027 return BAD_VALUE;
1028 }
1029 exifRes = exifUtils->setOrientation(inputFrame.orientation);
1030 if (!exifRes) {
1031 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
1032 return BAD_VALUE;
1033 }
1034 exifRes = exifUtils->generateApp1();
1035 if (!exifRes) {
1036 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1037 return BAD_VALUE;
1038 }
1039
1040 unsigned int newApp1Length = exifUtils->getApp1Length();
1041 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1042
1043 //Assemble the APP1 marker buffer required by MediaCodec
1044 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1045 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1046 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1047 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1048 appSegmentSize - app1Size + newApp1Length;
1049 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1050 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1051 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1052 if (appSegmentSize - app1Size > 0) {
1053 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1054 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1055 }
1056
1057 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1058 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001059 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001060 delete[] appSegmentBuffer;
1061
1062 if (res != OK) {
1063 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1064 __FUNCTION__, strerror(-res), res);
1065 return res;
1066 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001067
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001068 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001069 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001070 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001071
1072 inputFrame.appSegmentWritten = true;
1073 // Release the buffer now so any pending input app segments can be processed
1074 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1075 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001076 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001077
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001078 return OK;
1079}
1080
1081status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1082 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1083 sp<MediaCodecBuffer> buffer;
1084 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1085 if (res != OK) {
1086 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1087 strerror(-res), res);
1088 return res;
1089 }
1090
1091 // Copy one tile from source to destination.
1092 size_t tileX = inputBuffer.tileIndex % mGridCols;
1093 size_t tileY = inputBuffer.tileIndex / mGridCols;
1094 size_t top = mGridHeight * tileY;
1095 size_t left = mGridWidth * tileX;
1096 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1097 mOutputWidth - tileX * mGridWidth : mGridWidth;
1098 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1099 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001100 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1101 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1102 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001103
1104 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1105 if (res != OK) {
1106 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1107 strerror(-res), res);
1108 return res;
1109 }
1110
1111 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1112 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1113 if (res != OK) {
1114 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1115 __FUNCTION__, strerror(-res), res);
1116 return res;
1117 }
1118 }
1119
1120 inputFrame.codecInputBuffers.clear();
1121 return OK;
1122}
1123
Shuzhen Wange8675782019-12-05 09:12:14 -08001124status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001125 InputFrame &inputFrame) {
1126 auto it = inputFrame.codecOutputBuffers.begin();
1127 sp<MediaCodecBuffer> buffer;
1128 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1129 if (res != OK) {
1130 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1131 __FUNCTION__, it->index, strerror(-res), res);
1132 return res;
1133 }
1134 if (buffer == nullptr) {
1135 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1136 __FUNCTION__, it->index);
1137 return BAD_VALUE;
1138 }
1139
1140 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1141 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001142 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001143 if (res != OK) {
1144 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1145 __FUNCTION__, it->index, strerror(-res), res);
1146 return res;
1147 }
1148
1149 mCodec->releaseOutputBuffer(it->index);
1150 if (inputFrame.pendingOutputTiles == 0) {
1151 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1152 } else {
1153 inputFrame.pendingOutputTiles--;
1154 }
1155
1156 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001157
1158 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001159 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001160 return OK;
1161}
1162
Shuzhen Wange8675782019-12-05 09:12:14 -08001163status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001164 InputFrame &inputFrame) {
1165 sp<ANativeWindow> outputANW = mOutputSurface;
1166 inputFrame.muxer->stop();
1167
1168 // Copy the content of the file to memory.
1169 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1170 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001171 GraphicBufferLocker gbLocker(gb);
1172 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001173 if (res != OK) {
1174 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1175 strerror(-res), res);
1176 return res;
1177 }
1178
1179 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1180 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1181 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1182 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1183 return BAD_VALUE;
1184 }
1185
1186 lseek(inputFrame.fileFd, 0, SEEK_SET);
1187 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1188 if (bytesRead < fSize) {
1189 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1190 return BAD_VALUE;
1191 }
1192
1193 close(inputFrame.fileFd);
1194 inputFrame.fileFd = -1;
1195
1196 // Fill in HEIC header
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001197 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
Shuzhen Wangdc519092022-12-02 12:29:04 -08001198 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1199 CameraBlob blobHeader = {
1200 .blobId = static_cast<CameraBlobId>(0x00FE),
1201 .blobSizeBytes = static_cast<int32_t>(fSize)
1202 };
1203 memcpy(header, &blobHeader, sizeof(CameraBlob));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001204
Shuzhen Wange8675782019-12-05 09:12:14 -08001205 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001206 if (res != OK) {
1207 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1208 __FUNCTION__, getStreamId(), strerror(-res), res);
1209 return res;
1210 }
1211
1212 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1213 if (res != OK) {
1214 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1215 strerror(-res), res);
1216 return res;
1217 }
1218 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001219 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001220
Shuzhen Wange8675782019-12-05 09:12:14 -08001221 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1222 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001223 return OK;
1224}
1225
1226
Shuzhen Wange8675782019-12-05 09:12:14 -08001227void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1228 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001229 if (inputFrame == nullptr) {
1230 return;
1231 }
1232
1233 if (inputFrame->appSegmentBuffer.data != nullptr) {
1234 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1235 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001236 }
1237
1238 while (!inputFrame->codecOutputBuffers.empty()) {
1239 auto it = inputFrame->codecOutputBuffers.begin();
1240 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1241 mCodec->releaseOutputBuffer(it->index);
1242 inputFrame->codecOutputBuffers.erase(it);
1243 }
1244
1245 if (inputFrame->yuvBuffer.data != nullptr) {
1246 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1247 inputFrame->yuvBuffer.data = nullptr;
1248 mYuvBufferAcquired = false;
1249 }
1250
1251 while (!inputFrame->codecInputBuffers.empty()) {
1252 auto it = inputFrame->codecInputBuffers.begin();
1253 inputFrame->codecInputBuffers.erase(it);
1254 }
1255
Shuzhen Wange8675782019-12-05 09:12:14 -08001256 if (inputFrame->error || mErrorState) {
1257 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1258 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001259 }
1260
1261 if (inputFrame->fileFd >= 0) {
1262 close(inputFrame->fileFd);
1263 inputFrame->fileFd = -1;
1264 }
1265
1266 if (inputFrame->anb != nullptr) {
1267 sp<ANativeWindow> outputANW = mOutputSurface;
1268 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1269 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001270
1271 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001272 }
1273}
1274
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001275void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001276 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001277 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001278 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001279 auto& inputFrame = it->second;
1280 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001281 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1282 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001283 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001284 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001285 } else {
1286 it++;
1287 }
1288 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001289
1290 // Update codec quality based on first upcoming input frame.
1291 // Note that when encoding is in surface mode, currently there is no
1292 // way for camera service to synchronize quality setting on a per-frame
1293 // basis: we don't get notification when codec is ready to consume a new
1294 // input frame. So we update codec quality on a best-effort basis.
1295 if (inputFrameDone) {
1296 auto firstPendingFrame = mPendingInputFrames.begin();
1297 if (firstPendingFrame != mPendingInputFrames.end()) {
1298 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001299 } else {
1300 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001301 }
1302 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001303}
1304
1305status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1306 const sp<CameraDeviceBase>& cameraDevice) {
1307 ALOGV("%s", __FUNCTION__);
1308
1309 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001310 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001311 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001312 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001313 if (!isSizeSupported) {
1314 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1315 __FUNCTION__, width, height);
1316 return BAD_VALUE;
1317 }
1318
1319 // Create Looper for MediaCodec.
1320 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1321 mCodecLooper = new ALooper;
1322 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1323 status_t res = mCodecLooper->start(
1324 false, // runOnCallingThread
1325 false, // canCallJava
1326 PRIORITY_AUDIO);
1327 if (res != OK) {
1328 ALOGE("%s: Failed to start codec looper: %s (%d)",
1329 __FUNCTION__, strerror(-res), res);
1330 return NO_INIT;
1331 }
1332
1333 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001334 if (mUseHeic) {
1335 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1336 } else {
1337 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1338 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001339 if (mCodec == nullptr) {
1340 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1341 return NO_INIT;
1342 }
1343
1344 // Create Looper and handler for Codec callback.
1345 mCodecCallbackHandler = new CodecCallbackHandler(this);
1346 if (mCodecCallbackHandler == nullptr) {
1347 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1348 return NO_MEMORY;
1349 }
1350 mCallbackLooper = new ALooper;
1351 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1352 res = mCallbackLooper->start(
1353 false, // runOnCallingThread
1354 false, // canCallJava
1355 PRIORITY_AUDIO);
1356 if (res != OK) {
1357 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1358 __FUNCTION__, strerror(-res), res);
1359 return NO_INIT;
1360 }
1361 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1362
1363 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1364 res = mCodec->setCallback(mAsyncNotify);
1365 if (res != OK) {
1366 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1367 strerror(-res), res);
1368 return res;
1369 }
1370
1371 // Create output format and configure the Codec.
1372 sp<AMessage> outputFormat = new AMessage();
1373 outputFormat->setString(KEY_MIME, desiredMime);
1374 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1375 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1376 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001377 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001378
1379 int32_t gridWidth, gridHeight, gridRows, gridCols;
1380 if (useGrid || mUseHeic) {
1381 gridWidth = HeicEncoderInfoManager::kGridWidth;
1382 gridHeight = HeicEncoderInfoManager::kGridHeight;
1383 gridRows = (height + gridHeight - 1)/gridHeight;
1384 gridCols = (width + gridWidth - 1)/gridWidth;
1385
1386 if (mUseHeic) {
1387 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1388 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1389 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1390 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1391 }
1392
1393 } else {
1394 gridWidth = width;
1395 gridHeight = height;
1396 gridRows = 1;
1397 gridCols = 1;
1398 }
1399
1400 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1401 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1402 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1403 outputFormat->setInt32(KEY_COLOR_FORMAT,
1404 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001405 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001406 // This only serves as a hint to encoder when encoding is not real-time.
1407 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1408
1409 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1410 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1411 if (res != OK) {
1412 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1413 strerror(-res), res);
1414 return res;
1415 }
1416
1417 mGridWidth = gridWidth;
1418 mGridHeight = gridHeight;
1419 mGridRows = gridRows;
1420 mGridCols = gridCols;
1421 mUseGrid = useGrid;
1422 mOutputWidth = width;
1423 mOutputHeight = height;
1424 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001425 mMaxHeicBufferSize =
1426 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1427 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001428
1429 return OK;
1430}
1431
1432void HeicCompositeStream::deinitCodec() {
1433 ALOGV("%s", __FUNCTION__);
1434 if (mCodec != nullptr) {
1435 mCodec->stop();
1436 mCodec->release();
1437 mCodec.clear();
1438 }
1439
1440 if (mCodecLooper != nullptr) {
1441 mCodecLooper->stop();
1442 mCodecLooper.clear();
1443 }
1444
1445 if (mCallbackLooper != nullptr) {
1446 mCallbackLooper->stop();
1447 mCallbackLooper.clear();
1448 }
1449
1450 mAsyncNotify.clear();
1451 mFormat.clear();
1452}
1453
1454// Return the size of the complete list of app segment, 0 indicates failure
1455size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1456 size_t maxSize, size_t *app1SegmentSize) {
1457 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1458 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1459 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1460 return 0;
1461 }
1462
1463 size_t expectedSize = 0;
1464 // First check for EXIF transport header at the end of the buffer
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001465 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(CameraBlob));
1466 const CameraBlob *blob = (const CameraBlob*)(header);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001467 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
Eino-Ville Talvalab7723202024-06-24 17:45:51 -07001468 ALOGE("%s: Invalid EXIF blobId %d", __FUNCTION__, eToI(blob->blobId));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001469 return 0;
1470 }
1471
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001472 expectedSize = blob->blobSizeBytes;
1473 if (expectedSize == 0 || expectedSize > maxSize - sizeof(CameraBlob)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001474 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1475 return 0;
1476 }
1477
1478 uint32_t totalSize = 0;
1479
1480 // Verify APP1 marker (mandatory)
1481 uint8_t app1Marker[] = {0xFF, 0xE1};
1482 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1483 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1484 appSegmentBuffer[0], appSegmentBuffer[1]);
1485 return 0;
1486 }
1487 totalSize += sizeof(app1Marker);
1488
1489 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1490 appSegmentBuffer[totalSize+1];
1491 totalSize += app1Size;
1492
1493 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1494 __FUNCTION__, expectedSize, app1Size);
1495 while (totalSize < expectedSize) {
1496 if (appSegmentBuffer[totalSize] != 0xFF ||
1497 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1498 appSegmentBuffer[totalSize+1] > 0xEF) {
1499 // Invalid APPn marker
1500 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1501 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1502 return 0;
1503 }
1504 totalSize += 2;
1505
1506 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1507 appSegmentBuffer[totalSize+1];
1508 totalSize += appnSize;
1509 }
1510
1511 if (totalSize != expectedSize) {
1512 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1513 __FUNCTION__, totalSize, expectedSize);
1514 return 0;
1515 }
1516
1517 *app1SegmentSize = app1Size + sizeof(app1Marker);
1518 return expectedSize;
1519}
1520
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001521status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1522 const CpuConsumer::LockedBuffer& yuvBuffer,
1523 size_t top, size_t left, size_t width, size_t height) {
1524 ATRACE_CALL();
1525
1526 // Get stride information for codecBuffer
1527 sp<ABuffer> imageData;
1528 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1529 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1530 return BAD_VALUE;
1531 }
1532 if (imageData->size() != sizeof(MediaImage2)) {
1533 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1534 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1535 return BAD_VALUE;
1536 }
1537 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1538 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1539 imageInfo->mBitDepth != 8 ||
1540 imageInfo->mBitDepthAllocated != 8 ||
1541 imageInfo->mNumPlanes != 3) {
1542 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1543 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1544 imageInfo->mType, imageInfo->mBitDepth,
1545 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1546 return BAD_VALUE;
1547 }
1548
1549 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1550 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1551 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1552 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1553 imageInfo->mPlane[MediaImage2::V].mOffset,
1554 imageInfo->mPlane[MediaImage2::U].mRowInc,
1555 imageInfo->mPlane[MediaImage2::V].mRowInc,
1556 imageInfo->mPlane[MediaImage2::U].mColInc,
1557 imageInfo->mPlane[MediaImage2::V].mColInc);
1558
1559 // Y
1560 for (auto row = top; row < top+height; row++) {
1561 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1562 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001563 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001564 }
1565
1566 // U is Cb, V is Cr
1567 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1568 imageInfo->mPlane[MediaImage2::U].mOffset;
1569 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1570 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1571 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1572 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1573 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1574 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1575 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1576 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1577 bool isCodecUvPlannar =
1578 ((codecUPlaneFirst && codecUvOffsetDiff >=
1579 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1580 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1581 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1582 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1583 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1584 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1585
1586 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1587 (codecUPlaneFirst == cameraUPlaneFirst)) {
1588 // UV semiplannar
1589 // The chrome plane could be either Cb first, or Cr first. Take the
1590 // smaller address.
1591 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
Emilian Peev48ae29e2024-06-27 19:06:05 +00001592 MediaImage2::PlaneIndex dstPlane = codecUPlaneFirst ? MediaImage2::U : MediaImage2::V;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001593 for (auto row = top/2; row < (top+height)/2; row++) {
1594 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1595 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001596 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001597 }
1598 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1599 // U plane
1600 for (auto row = top/2; row < (top+height)/2; row++) {
1601 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1602 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001603 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001604 }
1605
1606 // V plane
1607 for (auto row = top/2; row < (top+height)/2; row++) {
1608 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1609 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001610 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001611 }
1612 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001613 // Convert between semiplannar and plannar, or when UV orders are
1614 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001615 uint8_t *dst = codecBuffer->data();
1616 for (auto row = top/2; row < (top+height)/2; row++) {
1617 for (auto col = left/2; col < (left+width)/2; col++) {
1618 // U/Cb
1619 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1620 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1621 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1622 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1623 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1624
1625 // V/Cr
1626 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1627 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1628 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1629 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1630 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1631 }
1632 }
1633 }
1634 return OK;
1635}
1636
Colin Cross14900c92023-01-13 14:50:17 -08001637void HeicCompositeStream::initCopyRowFunction([[maybe_unused]] int32_t width)
Shuzhen Wang219c2992019-02-15 17:24:28 -08001638{
1639 using namespace libyuv;
1640
1641 mFnCopyRow = CopyRow_C;
1642#if defined(HAS_COPYROW_SSE2)
1643 if (TestCpuFlag(kCpuHasSSE2)) {
1644 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1645 }
1646#endif
1647#if defined(HAS_COPYROW_AVX)
1648 if (TestCpuFlag(kCpuHasAVX)) {
1649 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1650 }
1651#endif
1652#if defined(HAS_COPYROW_ERMS)
1653 if (TestCpuFlag(kCpuHasERMS)) {
1654 mFnCopyRow = CopyRow_ERMS;
1655 }
1656#endif
1657#if defined(HAS_COPYROW_NEON)
1658 if (TestCpuFlag(kCpuHasNEON)) {
1659 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1660 }
1661#endif
1662#if defined(HAS_COPYROW_MIPS)
1663 if (TestCpuFlag(kCpuHasMIPS)) {
1664 mFnCopyRow = CopyRow_MIPS;
1665 }
1666#endif
1667}
1668
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001669size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1670 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1671 size_t maxAppsSegment = 1;
1672 if (entry.count > 0) {
1673 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1674 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1675 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001676 return maxAppsSegment * (2 + 0xFFFF) + sizeof(CameraBlob);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001677}
1678
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001679void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1680 if (quality != mQuality) {
1681 sp<AMessage> qualityParams = new AMessage;
1682 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1683 status_t res = mCodec->setParameters(qualityParams);
1684 if (res != OK) {
1685 ALOGE("%s: Failed to set codec quality: %s (%d)",
1686 __FUNCTION__, strerror(-res), res);
1687 } else {
1688 mQuality = quality;
1689 }
1690 }
1691}
1692
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001693bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001694 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001695 bool newInputAvailable = false;
1696
1697 {
1698 Mutex::Autolock l(mMutex);
1699 if (mErrorState) {
1700 // In case we landed in error state, return any pending buffers and
1701 // halt all further processing.
1702 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001703 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001704 return false;
1705 }
1706
1707
1708 while (!newInputAvailable) {
1709 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001710 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001711
1712 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001713 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001714 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001715 releaseInputFrameLocked(failingFrameNumber,
1716 &mPendingInputFrames[failingFrameNumber]);
1717
1718 // It's okay to remove the entry from mPendingInputFrames
1719 // because:
1720 // 1. Only one internal stream (main input) is critical in
1721 // backing the output stream.
1722 // 2. If captureResult/appSegment arrives after the entry is
1723 // removed, they are simply skipped.
1724 mPendingInputFrames.erase(failingFrameNumber);
1725 if (mPendingInputFrames.size() == 0) {
1726 markTrackerIdle();
1727 }
1728 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001729 }
1730
1731 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1732 if (ret == TIMED_OUT) {
1733 return true;
1734 } else if (ret != OK) {
1735 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1736 strerror(-ret), ret);
1737 return false;
1738 }
1739 }
1740 }
1741 }
1742
Shuzhen Wange8675782019-12-05 09:12:14 -08001743 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001744 Mutex::Autolock l(mMutex);
1745 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001746 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1747 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1748 frameNumber, strerror(-res), res);
1749 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001750 }
1751
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001752 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001753
1754 return true;
1755}
1756
Shuzhen Wange8675782019-12-05 09:12:14 -08001757void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1758 Mutex::Autolock l(mMutex);
1759 mExifErrorFrameNumbers.emplace(frameNumber);
1760 mInputReadyCondition.signal();
1761}
1762
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001763bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1764 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001765 int64_t frameNumber = resultExtras.frameNumber;
1766
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001767 // Buffer errors concerning internal composite streams should not be directly visible to
1768 // camera clients. They must only receive a single buffer error with the public composite
1769 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001770 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1771 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1772 flagAnExifErrorFrameNumber(frameNumber);
1773 res = true;
1774 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1775 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1776 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001777 res = true;
1778 }
1779
1780 return res;
1781}
1782
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001783void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1784 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1785 // simply skip using the capture result metadata to override EXIF.
1786 Mutex::Autolock l(mMutex);
1787
1788 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001789 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001790 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001791 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001792 break;
1793 }
1794 }
1795 if (timestamp == -1) {
1796 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001797 if (inputFrame.first == resultExtras.frameNumber) {
1798 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001799 break;
1800 }
1801 }
1802 }
1803
1804 if (timestamp == -1) {
1805 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1806 return;
1807 }
1808
1809 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001810 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1811 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001812 mInputReadyCondition.signal();
1813}
1814
Shuzhen Wange8675782019-12-05 09:12:14 -08001815void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1816 auto frameNumber = resultExtras.frameNumber;
1817 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1818 Mutex::Autolock l(mMutex);
1819 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1820 if (numRequests == 0) {
1821 // Pending request has been populated into mPendingInputFrames
1822 mErrorFrameNumbers.emplace(frameNumber);
1823 mInputReadyCondition.signal();
1824 } else {
1825 // REQUEST_ERROR was received without onShutter.
1826 }
1827}
1828
1829void HeicCompositeStream::markTrackerIdle() {
1830 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1831 if (statusTracker != nullptr) {
1832 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1833 ALOGV("%s: Mark component as idle", __FUNCTION__);
1834 }
1835}
1836
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001837void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1838 sp<HeicCompositeStream> parent = mParent.promote();
1839 if (parent == nullptr) return;
1840
1841 switch (msg->what()) {
1842 case kWhatCallbackNotify: {
1843 int32_t cbID;
1844 if (!msg->findInt32("callbackID", &cbID)) {
1845 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1846 break;
1847 }
1848
1849 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1850
1851 switch (cbID) {
1852 case MediaCodec::CB_INPUT_AVAILABLE: {
1853 int32_t index;
1854 if (!msg->findInt32("index", &index)) {
1855 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1856 break;
1857 }
1858 parent->onHeicInputFrameAvailable(index);
1859 break;
1860 }
1861
1862 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1863 int32_t index;
1864 size_t offset;
1865 size_t size;
1866 int64_t timeUs;
1867 int32_t flags;
1868
1869 if (!msg->findInt32("index", &index)) {
1870 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1871 break;
1872 }
1873 if (!msg->findSize("offset", &offset)) {
1874 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1875 break;
1876 }
1877 if (!msg->findSize("size", &size)) {
1878 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1879 break;
1880 }
1881 if (!msg->findInt64("timeUs", &timeUs)) {
1882 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1883 break;
1884 }
1885 if (!msg->findInt32("flags", &flags)) {
1886 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1887 break;
1888 }
1889
1890 CodecOutputBufferInfo bufferInfo = {
1891 index,
1892 (int32_t)offset,
1893 (int32_t)size,
1894 timeUs,
1895 (uint32_t)flags};
1896
1897 parent->onHeicOutputFrameAvailable(bufferInfo);
1898 break;
1899 }
1900
1901 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1902 sp<AMessage> format;
1903 if (!msg->findMessage("format", &format)) {
1904 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1905 break;
1906 }
Chong Zhang860eff12019-09-16 16:15:00 -07001907 // Here format is MediaCodec's internal copy of output format.
1908 // Make a copy since onHeicFormatChanged() might modify it.
1909 sp<AMessage> formatCopy;
1910 if (format != nullptr) {
1911 formatCopy = format->dup();
1912 }
1913 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001914 break;
1915 }
1916
1917 case MediaCodec::CB_ERROR: {
1918 status_t err;
1919 int32_t actionCode;
1920 AString detail;
1921 if (!msg->findInt32("err", &err)) {
1922 ALOGE("CB_ERROR: err is expected.");
1923 break;
1924 }
1925 if (!msg->findInt32("action", &actionCode)) {
1926 ALOGE("CB_ERROR: action is expected.");
1927 break;
1928 }
1929 msg->findString("detail", &detail);
1930 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1931 err, actionCode, detail.c_str());
1932
1933 parent->onHeicCodecError();
1934 break;
1935 }
1936
1937 default: {
1938 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1939 break;
1940 }
1941 }
1942 break;
1943 }
1944
1945 default:
1946 ALOGE("shouldn't be here");
1947 break;
1948 }
1949}
1950
1951}; // namespace camera3
1952}; // namespace android