blob: 52ab22fc4c9bc642b08704d34825f56b437e1997 [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>
32
Marco Nelissen13aa1a42019-09-27 10:21:55 -070033#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080034#include <media/MediaCodecBuffer.h>
35#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080036#include <media/stagefright/foundation/MediaDefs.h>
37#include <media/stagefright/MediaCodecConstants.h>
38
39#include "common/CameraDeviceBase.h"
40#include "utils/ExifUtils.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080041#include "utils/SessionConfigurationUtils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080042#include "HeicEncoderInfoManager.h"
43#include "HeicCompositeStream.h"
44
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +000045using aidl::android::hardware::camera::device::CameraBlob;
46using aidl::android::hardware::camera::device::CameraBlobId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080047
48namespace android {
49namespace camera3 {
50
Shuzhen Wange8675782019-12-05 09:12:14 -080051HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080052 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
53 CompositeStream(device, cb),
54 mUseHeic(false),
55 mNumOutputTiles(1),
56 mOutputWidth(0),
57 mOutputHeight(0),
58 mMaxHeicBufferSize(0),
59 mGridWidth(HeicEncoderInfoManager::kGridWidth),
60 mGridHeight(HeicEncoderInfoManager::kGridHeight),
61 mGridRows(1),
62 mGridCols(1),
63 mUseGrid(false),
64 mAppSegmentStreamId(-1),
65 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080066 mMainImageStreamId(-1),
67 mMainImageSurfaceId(-1),
68 mYuvBufferAcquired(false),
69 mProducerListener(new ProducerListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070070 mDequeuedOutputBufferCnt(0),
71 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070072 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080073 mGridTimestampUs(0),
74 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080075}
76
77HeicCompositeStream::~HeicCompositeStream() {
78 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
79 // memory/resource leak.
80 deinitCodec();
81
82 mInputAppSegmentBuffers.clear();
83 mCodecOutputBuffers.clear();
84
85 mAppSegmentStreamId = -1;
86 mAppSegmentSurfaceId = -1;
87 mAppSegmentConsumer.clear();
88 mAppSegmentSurface.clear();
89
90 mMainImageStreamId = -1;
91 mMainImageSurfaceId = -1;
92 mMainImageConsumer.clear();
93 mMainImageSurface.clear();
94}
95
96bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
97 ANativeWindow *anw = surface.get();
98 status_t err;
99 int format;
100 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
101 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
102 err);
103 ALOGE("%s: %s", __FUNCTION__, msg.string());
104 return false;
105 }
106
107 int dataspace;
108 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
109 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
110 err);
111 ALOGE("%s: %s", __FUNCTION__, msg.string());
112 return false;
113 }
114
115 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
116}
117
118status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
119 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700120 camera_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800121 const std::unordered_set<int32_t> &sensorPixelModesUsed,
122 std::vector<int> *surfaceIds,
Emilian Peev434248e2022-10-06 14:58:54 -0700123 int /*streamSetId*/, bool /*isShared*/, int32_t /*colorSpace*/,
124 int64_t /*dynamicProfile*/, int64_t /*streamUseCase*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800125
126 sp<CameraDeviceBase> device = mDevice.promote();
127 if (!device.get()) {
128 ALOGE("%s: Invalid camera device!", __FUNCTION__);
129 return NO_INIT;
130 }
131
132 status_t res = initializeCodec(width, height, device);
133 if (res != OK) {
134 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
135 __FUNCTION__, strerror(-res), res);
136 return NO_INIT;
137 }
138
139 sp<IGraphicBufferProducer> producer;
140 sp<IGraphicBufferConsumer> consumer;
141 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700142 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800143 mAppSegmentConsumer->setFrameAvailableListener(this);
144 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
145 mAppSegmentSurface = new Surface(producer);
146
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800147 mStaticInfo = device->info();
148
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800149 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800150 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
151 sensorPixelModesUsed,surfaceIds);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800152 if (res == OK) {
153 mAppSegmentSurfaceId = (*surfaceIds)[0];
154 } else {
155 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
156 strerror(-res), res);
157 return res;
158 }
159
160 if (!mUseGrid) {
161 res = mCodec->createInputSurface(&producer);
162 if (res != OK) {
163 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
164 __FUNCTION__, strerror(-res), res);
165 return res;
166 }
167 } else {
168 BufferQueue::createBufferQueue(&producer, &consumer);
169 mMainImageConsumer = new CpuConsumer(consumer, 1);
170 mMainImageConsumer->setFrameAvailableListener(this);
171 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
172 }
173 mMainImageSurface = new Surface(producer);
174
175 res = mCodec->start();
176 if (res != OK) {
177 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
178 strerror(-res), res);
179 return res;
180 }
181
182 std::vector<int> sourceSurfaceId;
183 //Use YUV_888 format if framework tiling is needed.
184 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
185 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
186 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800187 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800188 if (res == OK) {
189 mMainImageSurfaceId = sourceSurfaceId[0];
190 mMainImageStreamId = *id;
191 } else {
192 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
193 strerror(-res), res);
194 return res;
195 }
196
197 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800198 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800199 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800200 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
201 strerror(-res), res);
202 return res;
203 }
204
205 res = registerCompositeStreamListener(mAppSegmentStreamId);
206 if (res != OK) {
207 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
208 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800209 return res;
210 }
211
Shuzhen Wang219c2992019-02-15 17:24:28 -0800212 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800213 return res;
214}
215
216status_t HeicCompositeStream::deleteInternalStreams() {
217 requestExit();
218 auto res = join();
219 if (res != OK) {
220 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
221 strerror(-res), res);
222 }
223
224 deinitCodec();
225
226 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700227 // Camera devices may not be valid after switching to offline mode.
228 // In this case, all offline streams including internal composite streams
229 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800230 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700231 if (device.get() != nullptr) {
232 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800233 }
234
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800235 mAppSegmentStreamId = -1;
236 }
237
Shuzhen Wang2c545042019-02-07 10:27:35 -0800238 if (mOutputSurface != nullptr) {
239 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
240 mOutputSurface.clear();
241 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800242
243 sp<StatusTracker> statusTracker = mStatusTracker.promote();
244 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
245 statusTracker->removeComponent(mStatusId);
246 mStatusId = StatusTracker::NO_STATUS_ID;
247 }
248
249 if (mPendingInputFrames.size() > 0) {
250 ALOGW("%s: mPendingInputFrames has %zu stale entries",
251 __FUNCTION__, mPendingInputFrames.size());
252 mPendingInputFrames.clear();
253 }
254
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800255 return res;
256}
257
258void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
259 Mutex::Autolock l(mMutex);
260
261 if (bufferInfo.mError) return;
262
Shuzhen Wange8675782019-12-05 09:12:14 -0800263 if (bufferInfo.mStreamId == mMainImageStreamId) {
264 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
265 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
266 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
267 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
268 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
269 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
270 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
271 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
272 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800273}
274
275// We need to get the settings early to handle the case where the codec output
276// arrives earlier than result metadata.
277void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
278 const CameraMetadata& settings) {
279 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
280
281 Mutex::Autolock l(mMutex);
282 if (mErrorState || (streamId != getStreamId())) {
283 return;
284 }
285
286 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
287
288 camera_metadata_ro_entry entry;
289
290 int32_t orientation = 0;
291 entry = settings.find(ANDROID_JPEG_ORIENTATION);
292 if (entry.count == 1) {
293 orientation = entry.data.i32[0];
294 }
295
296 int32_t quality = kDefaultJpegQuality;
297 entry = settings.find(ANDROID_JPEG_QUALITY);
298 if (entry.count == 1) {
299 quality = entry.data.i32[0];
300 }
301
Shuzhen Wange8675782019-12-05 09:12:14 -0800302 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800303}
304
305void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
306 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
307 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
308 __func__, ns2ms(item.mTimestamp));
309
310 Mutex::Autolock l(mMutex);
311 if (!mErrorState) {
312 mInputAppSegmentBuffers.push_back(item.mTimestamp);
313 mInputReadyCondition.signal();
314 }
315 } else if (item.mDataSpace == kHeifDataSpace) {
316 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
317 __func__, ns2ms(item.mTimestamp));
318
319 Mutex::Autolock l(mMutex);
320 if (!mUseGrid) {
321 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
322 __FUNCTION__);
323 return;
324 }
325 if (!mErrorState) {
326 mInputYuvBuffers.push_back(item.mTimestamp);
327 mInputReadyCondition.signal();
328 }
329 } else {
330 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
331 }
332}
333
334status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
335 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
336 if (compositeOutput == nullptr) {
337 return BAD_VALUE;
338 }
339
340 compositeOutput->clear();
341
342 bool useGrid, useHeic;
343 bool isSizeSupported = isSizeSupportedByHeifEncoder(
344 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
345 if (!isSizeSupported) {
346 // Size is not supported by either encoder.
347 return OK;
348 }
349
350 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
351
352 // JPEG APPS segments Blob stream info
353 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
354 (*compositeOutput)[0].height = 1;
355 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
356 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
357 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
358
359 // YUV/IMPLEMENTATION_DEFINED stream info
360 (*compositeOutput)[1].width = streamInfo.width;
361 (*compositeOutput)[1].height = streamInfo.height;
362 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
363 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
364 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
365 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
366 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
367
368 return NO_ERROR;
369}
370
371bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700372 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800373 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700374 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800375}
376
377bool HeicCompositeStream::isInMemoryTempFileSupported() {
378 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
379 if (memfd == -1) {
380 if (errno != ENOSYS) {
381 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
382 }
383 return false;
384 }
385 close(memfd);
386 return true;
387}
388
389void HeicCompositeStream::onHeicOutputFrameAvailable(
390 const CodecOutputBufferInfo& outputBufferInfo) {
391 Mutex::Autolock l(mMutex);
392
393 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
394 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
395 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
396
397 if (!mErrorState) {
398 if ((outputBufferInfo.size > 0) &&
399 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
400 mCodecOutputBuffers.push_back(outputBufferInfo);
401 mInputReadyCondition.signal();
402 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700403 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
404 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800405 mCodec->releaseOutputBuffer(outputBufferInfo.index);
406 }
407 } else {
408 mCodec->releaseOutputBuffer(outputBufferInfo.index);
409 }
410}
411
412void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
413 Mutex::Autolock l(mMutex);
414
415 if (!mUseGrid) {
416 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
417 return;
418 }
419
420 mCodecInputBuffers.push_back(index);
421 mInputReadyCondition.signal();
422}
423
424void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
425 if (newFormat == nullptr) {
426 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
427 return;
428 }
429
430 Mutex::Autolock l(mMutex);
431
432 AString mime;
433 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
434 newFormat->findString(KEY_MIME, &mime);
435 if (mime != mimeHeic) {
436 // For HEVC codec, below keys need to be filled out or overwritten so that the
437 // muxer can handle them as HEIC output image.
438 newFormat->setString(KEY_MIME, mimeHeic);
439 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
440 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
441 if (mUseGrid) {
442 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
443 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
444 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
445 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
dan.shen60fa4b92022-04-12 18:57:43 +0800446 int32_t left, top, right, bottom;
447 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
448 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
449 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800450 }
451 }
452 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
453
454 int32_t gridRows, gridCols;
455 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
456 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
457 mNumOutputTiles = gridRows * gridCols;
458 } else {
459 mNumOutputTiles = 1;
460 }
461
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800462 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700463
464 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
465 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800466}
467
468void HeicCompositeStream::onHeicCodecError() {
469 Mutex::Autolock l(mMutex);
470 mErrorState = true;
471}
472
473status_t HeicCompositeStream::configureStream() {
474 if (isRunning()) {
475 // Processing thread is already running, nothing more to do.
476 return NO_ERROR;
477 }
478
479 if (mOutputSurface.get() == nullptr) {
480 ALOGE("%s: No valid output surface set!", __FUNCTION__);
481 return NO_INIT;
482 }
483
484 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
485 if (res != OK) {
486 ALOGE("%s: Unable to connect to native window for stream %d",
487 __FUNCTION__, mMainImageStreamId);
488 return res;
489 }
490
491 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
492 != OK) {
493 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
494 mMainImageStreamId);
495 return res;
496 }
497
498 ANativeWindow *anwConsumer = mOutputSurface.get();
499 int maxConsumerBuffers;
500 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
501 &maxConsumerBuffers)) != OK) {
502 ALOGE("%s: Unable to query consumer undequeued"
503 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
504 return res;
505 }
506
507 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
508 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800509 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700510 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800511 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
512 return res;
513 }
514
515 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
516 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
517 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
518 return res;
519 }
520
Shuzhen Wange8675782019-12-05 09:12:14 -0800521 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
522 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700523 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
524 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800525 }
526
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800527 run("HeicCompositeStreamProc");
528
529 return NO_ERROR;
530}
531
532status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
533 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
534 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800535 outputStreamIds->push_back(mAppSegmentStreamId);
536 }
537 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
538
539 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800540 outputStreamIds->push_back(mMainImageStreamId);
541 }
542 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
543
544 if (currentStreamId != nullptr) {
545 *currentStreamId = mMainImageStreamId;
546 }
547
548 return NO_ERROR;
549}
550
Emilian Peev4697b642019-11-19 17:11:14 -0800551status_t HeicCompositeStream::insertCompositeStreamIds(
552 std::vector<int32_t>* compositeStreamIds /*out*/) {
553 if (compositeStreamIds == nullptr) {
554 return BAD_VALUE;
555 }
556
557 compositeStreamIds->push_back(mAppSegmentStreamId);
558 compositeStreamIds->push_back(mMainImageStreamId);
559
560 return OK;
561}
562
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800563void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
564 Mutex::Autolock l(mMutex);
565 if (mErrorState) {
566 return;
567 }
568
569 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800570 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
571 resultExtras.frameNumber, timestamp, resultExtras.requestId);
572 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
573 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
574 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800575 mInputReadyCondition.signal();
576 }
577}
578
579void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800580 auto i = mSettingsByFrameNumber.begin();
581 while (i != mSettingsByFrameNumber.end()) {
582 if (i->second.shutterNotified) {
583 mPendingInputFrames[i->first].orientation = i->second.orientation;
584 mPendingInputFrames[i->first].quality = i->second.quality;
585 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
586 mPendingInputFrames[i->first].requestId = i->second.requestId;
587 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
588 i->first, i->second.timestamp);
589 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700590
Shuzhen Wange8675782019-12-05 09:12:14 -0800591 // Set encoder quality if no inflight encoding
592 if (mPendingInputFrames.size() == 1) {
593 sp<StatusTracker> statusTracker = mStatusTracker.promote();
594 if (statusTracker != nullptr) {
595 statusTracker->markComponentActive(mStatusId);
596 ALOGV("%s: Mark component as active", __FUNCTION__);
597 }
598
599 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
600 updateCodecQualityLocked(newQuality);
601 }
602 } else {
603 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700604 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800605 }
606
Shuzhen Wange8675782019-12-05 09:12:14 -0800607 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800608 CpuConsumer::LockedBuffer imgBuffer;
609 auto it = mInputAppSegmentBuffers.begin();
610 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
611 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700612 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800613 break;
614 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
615 if (res != OK) {
616 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
617 strerror(-res), res);
618 } else {
619 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
620 " received buffer with time stamp: %" PRId64, __FUNCTION__,
621 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700622 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800623 }
624 mPendingInputFrames[*it].error = true;
625 mInputAppSegmentBuffers.erase(it);
626 continue;
627 }
628
Shuzhen Wange8675782019-12-05 09:12:14 -0800629 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
630 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
631 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700632 mInputAppSegmentBuffers.erase(it);
633 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800634 continue;
635 }
636
637 int64_t frameNumber = mAppSegmentFrameNumbers.front();
638 // If mPendingInputFrames doesn't contain the expected frame number, the captured
639 // input app segment frame must have been dropped via a buffer error. Simply
640 // return the buffer to the buffer queue.
641 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
642 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800643 mAppSegmentConsumer->unlockBuffer(imgBuffer);
644 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800645 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800646 }
647 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800648 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800649 }
650
Shuzhen Wange8675782019-12-05 09:12:14 -0800651 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800652 CpuConsumer::LockedBuffer imgBuffer;
653 auto it = mInputYuvBuffers.begin();
654 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
655 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700656 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800657 break;
658 } else if (res != OK) {
659 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
660 strerror(-res), res);
661 mPendingInputFrames[*it].error = true;
662 mInputYuvBuffers.erase(it);
663 continue;
664 } else if (*it != imgBuffer.timestamp) {
665 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
666 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
667 mPendingInputFrames[*it].error = true;
668 mInputYuvBuffers.erase(it);
669 continue;
670 }
671
Shuzhen Wange8675782019-12-05 09:12:14 -0800672 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
673 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
674 mMainImageFrameNumbers.front());
675 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700676 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800677 continue;
678 }
679
680 int64_t frameNumber = mMainImageFrameNumbers.front();
681 // If mPendingInputFrames doesn't contain the expected frame number, the captured
682 // input main image must have been dropped via a buffer error. Simply
683 // return the buffer to the buffer queue.
684 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
685 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800686 mMainImageConsumer->unlockBuffer(imgBuffer);
687 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800688 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800689 mYuvBufferAcquired = true;
690 }
691 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800692 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800693 }
694
695 while (!mCodecOutputBuffers.empty()) {
696 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800697 // Assume encoder input to output is FIFO, use a queue to look up
698 // frameNumber when handling codec outputs.
699 int64_t bufferFrameNumber = -1;
700 if (mCodecOutputBufferFrameNumbers.empty()) {
701 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700702 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800703 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800704 // Direct mapping between camera frame number and codec timestamp (in us).
705 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700706 mCodecOutputCounter++;
707 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800708 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700709 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800710 }
711
Shuzhen Wange8675782019-12-05 09:12:14 -0800712 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
713 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
714 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800715 }
716 mCodecOutputBuffers.erase(it);
717 }
718
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800719 while (!mCaptureResults.empty()) {
720 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800721 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800722 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800723 int64_t frameNumber = std::get<0>(it->second);
724 if (it->first >= 0 &&
725 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
726 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
727 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800728 std::make_unique<CameraMetadata>(std::get<1>(it->second));
729 } else {
730 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800731 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
732 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
733 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800734 }
735 }
736 mCaptureResults.erase(it);
737 }
738
739 // mErrorFrameNumbers stores frame number of dropped buffers.
740 auto it = mErrorFrameNumbers.begin();
741 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800742 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
743 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800744 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800745 //Error callback is guaranteed to arrive after shutter notify, which
746 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800747 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
748 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800749 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800750 it = mErrorFrameNumbers.erase(it);
751 }
752
753 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
754 it = mExifErrorFrameNumbers.begin();
755 while (it != mExifErrorFrameNumbers.end()) {
756 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
757 mPendingInputFrames[*it].exifError = true;
758 }
759 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800760 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800761
762 // Distribute codec input buffers to be filled out from YUV output
763 for (auto it = mPendingInputFrames.begin();
764 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
765 InputFrame& inputFrame(it->second);
766 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
767 // Available input tiles that are required for the current input
768 // image.
769 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
770 mGridRows * mGridCols - inputFrame.codecInputCounter);
771 for (size_t i = 0; i < newInputTiles; i++) {
772 CodecInputBufferInfo inputInfo =
773 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
774 inputFrame.codecInputBuffers.push_back(inputInfo);
775
776 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
777 inputFrame.codecInputCounter++;
778 }
779 break;
780 }
781 }
782}
783
Shuzhen Wange8675782019-12-05 09:12:14 -0800784bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
785 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800786 return false;
787 }
788
789 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700790 for (auto& it : mPendingInputFrames) {
791 // New input is considered to be available only if:
792 // 1. input buffers are ready, or
793 // 2. App segment and muxer is created, or
794 // 3. A codec output tile is ready, and an output buffer is available.
795 // This makes sure that muxer gets created only when an output tile is
796 // generated, because right now we only handle 1 HEIC output buffer at a
797 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800798 bool appSegmentReady =
799 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700800 !it.second.appSegmentWritten && it.second.result != nullptr &&
801 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800802 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
803 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
804 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700805 bool hasOutputBuffer = it.second.muxer != nullptr ||
806 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800807 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700808 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800809 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700810 if (it.second.format == nullptr && mFormat != nullptr) {
811 it.second.format = mFormat->dup();
812 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800813 newInputAvailable = true;
814 break;
815 }
816 }
817
818 return newInputAvailable;
819}
820
Shuzhen Wange8675782019-12-05 09:12:14 -0800821int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800822 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800823
824 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800825 if (it.second.error) {
826 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800827 break;
828 }
829 }
830
831 return res;
832}
833
Shuzhen Wange8675782019-12-05 09:12:14 -0800834status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800835 InputFrame &inputFrame) {
836 ATRACE_CALL();
837 status_t res = OK;
838
Shuzhen Wange8675782019-12-05 09:12:14 -0800839 bool appSegmentReady =
840 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700841 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
842 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800843 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
844 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700845 !inputFrame.codecInputBuffers.empty();
846 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
847 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800848
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700849 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800850 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
851 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
852 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800853
854 // Handle inputs for Hevc tiling
855 if (codecInputReady) {
856 res = processCodecInputFrame(inputFrame);
857 if (res != OK) {
858 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
859 strerror(-res), res);
860 return res;
861 }
862 }
863
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700864 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
865 return OK;
866 }
867
868 // Initialize and start muxer if not yet done so. In this case,
869 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
870 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800871 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800872 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800873 if (res != OK) {
874 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
875 strerror(-res), res);
876 return res;
877 }
878 }
879
880 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700881 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800882 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800883 if (res != OK) {
884 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
885 strerror(-res), res);
886 return res;
887 }
888 }
889
890 // Write media codec bitstream buffers to muxer.
891 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800892 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800893 if (res != OK) {
894 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
895 strerror(-res), res);
896 return res;
897 }
898 }
899
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700900 if (inputFrame.pendingOutputTiles == 0) {
901 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800902 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700903 if (res != OK) {
904 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
905 strerror(-res), res);
906 return res;
907 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800908 }
909 }
910
911 return res;
912}
913
Shuzhen Wange8675782019-12-05 09:12:14 -0800914status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800915 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800916
917 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
918 if (res != OK) {
919 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
920 res);
921 return res;
922 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700923 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800924
925 // Combine current thread id, stream id and timestamp to uniquely identify image.
926 std::ostringstream tempOutputFile;
927 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800928 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800929 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
930 if (inputFrame.fileFd < 0) {
931 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
932 tempOutputFile.str().c_str(), errno);
933 return NO_INIT;
934 }
Manisha Jajoo022b52f2021-10-09 00:51:42 +0530935 inputFrame.muxer = MediaMuxer::create(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800936 if (inputFrame.muxer == nullptr) {
937 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
938 __FUNCTION__, inputFrame.fileFd);
939 return NO_INIT;
940 }
941
942 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
943 if (res != OK) {
944 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
945 strerror(-res), res);
946 return res;
947 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800948
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700949 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800950 if (trackId < 0) {
951 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
952 return NO_INIT;
953 }
954
955 inputFrame.trackIndex = trackId;
956 inputFrame.pendingOutputTiles = mNumOutputTiles;
957
958 res = inputFrame.muxer->start();
959 if (res != OK) {
960 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
961 __FUNCTION__, strerror(-res), res);
962 return res;
963 }
964
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700965 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800966 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800967 return OK;
968}
969
Shuzhen Wange8675782019-12-05 09:12:14 -0800970status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800971 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800972 size_t appSegmentSize = 0;
973 if (!inputFrame.exifError) {
974 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
975 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
976 &app1Size);
977 if (appSegmentSize == 0) {
978 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
979 return NO_INIT;
980 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800981 }
982
983 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800984 auto exifRes = inputFrame.exifError ?
985 exifUtils->initializeEmpty() :
986 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800987 if (!exifRes) {
988 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
989 return BAD_VALUE;
990 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800991 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
992 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800993 if (!exifRes) {
994 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
995 return BAD_VALUE;
996 }
997 exifRes = exifUtils->setOrientation(inputFrame.orientation);
998 if (!exifRes) {
999 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
1000 return BAD_VALUE;
1001 }
1002 exifRes = exifUtils->generateApp1();
1003 if (!exifRes) {
1004 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1005 return BAD_VALUE;
1006 }
1007
1008 unsigned int newApp1Length = exifUtils->getApp1Length();
1009 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1010
1011 //Assemble the APP1 marker buffer required by MediaCodec
1012 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1013 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1014 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1015 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1016 appSegmentSize - app1Size + newApp1Length;
1017 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1018 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1019 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1020 if (appSegmentSize - app1Size > 0) {
1021 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1022 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1023 }
1024
1025 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1026 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001027 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001028 delete[] appSegmentBuffer;
1029
1030 if (res != OK) {
1031 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1032 __FUNCTION__, strerror(-res), res);
1033 return res;
1034 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001035
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001036 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001037 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001038 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001039
1040 inputFrame.appSegmentWritten = true;
1041 // Release the buffer now so any pending input app segments can be processed
1042 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1043 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001044 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001045
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001046 return OK;
1047}
1048
1049status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1050 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1051 sp<MediaCodecBuffer> buffer;
1052 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1053 if (res != OK) {
1054 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1055 strerror(-res), res);
1056 return res;
1057 }
1058
1059 // Copy one tile from source to destination.
1060 size_t tileX = inputBuffer.tileIndex % mGridCols;
1061 size_t tileY = inputBuffer.tileIndex / mGridCols;
1062 size_t top = mGridHeight * tileY;
1063 size_t left = mGridWidth * tileX;
1064 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1065 mOutputWidth - tileX * mGridWidth : mGridWidth;
1066 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1067 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001068 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1069 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1070 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001071
1072 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1073 if (res != OK) {
1074 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1075 strerror(-res), res);
1076 return res;
1077 }
1078
1079 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1080 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1081 if (res != OK) {
1082 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1083 __FUNCTION__, strerror(-res), res);
1084 return res;
1085 }
1086 }
1087
1088 inputFrame.codecInputBuffers.clear();
1089 return OK;
1090}
1091
Shuzhen Wange8675782019-12-05 09:12:14 -08001092status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001093 InputFrame &inputFrame) {
1094 auto it = inputFrame.codecOutputBuffers.begin();
1095 sp<MediaCodecBuffer> buffer;
1096 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1097 if (res != OK) {
1098 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1099 __FUNCTION__, it->index, strerror(-res), res);
1100 return res;
1101 }
1102 if (buffer == nullptr) {
1103 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1104 __FUNCTION__, it->index);
1105 return BAD_VALUE;
1106 }
1107
1108 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1109 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001110 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001111 if (res != OK) {
1112 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1113 __FUNCTION__, it->index, strerror(-res), res);
1114 return res;
1115 }
1116
1117 mCodec->releaseOutputBuffer(it->index);
1118 if (inputFrame.pendingOutputTiles == 0) {
1119 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1120 } else {
1121 inputFrame.pendingOutputTiles--;
1122 }
1123
1124 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001125
1126 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001127 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001128 return OK;
1129}
1130
Shuzhen Wange8675782019-12-05 09:12:14 -08001131status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001132 InputFrame &inputFrame) {
1133 sp<ANativeWindow> outputANW = mOutputSurface;
1134 inputFrame.muxer->stop();
1135
1136 // Copy the content of the file to memory.
1137 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1138 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001139 GraphicBufferLocker gbLocker(gb);
1140 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001141 if (res != OK) {
1142 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1143 strerror(-res), res);
1144 return res;
1145 }
1146
1147 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1148 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1149 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1150 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1151 return BAD_VALUE;
1152 }
1153
1154 lseek(inputFrame.fileFd, 0, SEEK_SET);
1155 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1156 if (bytesRead < fSize) {
1157 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1158 return BAD_VALUE;
1159 }
1160
1161 close(inputFrame.fileFd);
1162 inputFrame.fileFd = -1;
1163
1164 // Fill in HEIC header
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001165 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
Shuzhen Wangdc519092022-12-02 12:29:04 -08001166 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1167 CameraBlob blobHeader = {
1168 .blobId = static_cast<CameraBlobId>(0x00FE),
1169 .blobSizeBytes = static_cast<int32_t>(fSize)
1170 };
1171 memcpy(header, &blobHeader, sizeof(CameraBlob));
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001172
Shuzhen Wange8675782019-12-05 09:12:14 -08001173 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001174 if (res != OK) {
1175 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1176 __FUNCTION__, getStreamId(), strerror(-res), res);
1177 return res;
1178 }
1179
1180 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1181 if (res != OK) {
1182 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1183 strerror(-res), res);
1184 return res;
1185 }
1186 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001187 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001188
Shuzhen Wange8675782019-12-05 09:12:14 -08001189 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1190 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001191 return OK;
1192}
1193
1194
Shuzhen Wange8675782019-12-05 09:12:14 -08001195void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1196 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001197 if (inputFrame == nullptr) {
1198 return;
1199 }
1200
1201 if (inputFrame->appSegmentBuffer.data != nullptr) {
1202 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1203 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001204 }
1205
1206 while (!inputFrame->codecOutputBuffers.empty()) {
1207 auto it = inputFrame->codecOutputBuffers.begin();
1208 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1209 mCodec->releaseOutputBuffer(it->index);
1210 inputFrame->codecOutputBuffers.erase(it);
1211 }
1212
1213 if (inputFrame->yuvBuffer.data != nullptr) {
1214 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1215 inputFrame->yuvBuffer.data = nullptr;
1216 mYuvBufferAcquired = false;
1217 }
1218
1219 while (!inputFrame->codecInputBuffers.empty()) {
1220 auto it = inputFrame->codecInputBuffers.begin();
1221 inputFrame->codecInputBuffers.erase(it);
1222 }
1223
Shuzhen Wange8675782019-12-05 09:12:14 -08001224 if (inputFrame->error || mErrorState) {
1225 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1226 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001227 }
1228
1229 if (inputFrame->fileFd >= 0) {
1230 close(inputFrame->fileFd);
1231 inputFrame->fileFd = -1;
1232 }
1233
1234 if (inputFrame->anb != nullptr) {
1235 sp<ANativeWindow> outputANW = mOutputSurface;
1236 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1237 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001238
1239 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001240 }
1241}
1242
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001243void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001244 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001245 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001246 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001247 auto& inputFrame = it->second;
1248 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001249 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1250 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001251 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001252 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001253 } else {
1254 it++;
1255 }
1256 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001257
1258 // Update codec quality based on first upcoming input frame.
1259 // Note that when encoding is in surface mode, currently there is no
1260 // way for camera service to synchronize quality setting on a per-frame
1261 // basis: we don't get notification when codec is ready to consume a new
1262 // input frame. So we update codec quality on a best-effort basis.
1263 if (inputFrameDone) {
1264 auto firstPendingFrame = mPendingInputFrames.begin();
1265 if (firstPendingFrame != mPendingInputFrames.end()) {
1266 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001267 } else {
1268 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001269 }
1270 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001271}
1272
1273status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1274 const sp<CameraDeviceBase>& cameraDevice) {
1275 ALOGV("%s", __FUNCTION__);
1276
1277 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001278 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001279 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001280 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001281 if (!isSizeSupported) {
1282 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1283 __FUNCTION__, width, height);
1284 return BAD_VALUE;
1285 }
1286
1287 // Create Looper for MediaCodec.
1288 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1289 mCodecLooper = new ALooper;
1290 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1291 status_t res = mCodecLooper->start(
1292 false, // runOnCallingThread
1293 false, // canCallJava
1294 PRIORITY_AUDIO);
1295 if (res != OK) {
1296 ALOGE("%s: Failed to start codec looper: %s (%d)",
1297 __FUNCTION__, strerror(-res), res);
1298 return NO_INIT;
1299 }
1300
1301 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001302 if (mUseHeic) {
1303 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1304 } else {
1305 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1306 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001307 if (mCodec == nullptr) {
1308 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1309 return NO_INIT;
1310 }
1311
1312 // Create Looper and handler for Codec callback.
1313 mCodecCallbackHandler = new CodecCallbackHandler(this);
1314 if (mCodecCallbackHandler == nullptr) {
1315 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1316 return NO_MEMORY;
1317 }
1318 mCallbackLooper = new ALooper;
1319 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1320 res = mCallbackLooper->start(
1321 false, // runOnCallingThread
1322 false, // canCallJava
1323 PRIORITY_AUDIO);
1324 if (res != OK) {
1325 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1326 __FUNCTION__, strerror(-res), res);
1327 return NO_INIT;
1328 }
1329 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1330
1331 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1332 res = mCodec->setCallback(mAsyncNotify);
1333 if (res != OK) {
1334 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1335 strerror(-res), res);
1336 return res;
1337 }
1338
1339 // Create output format and configure the Codec.
1340 sp<AMessage> outputFormat = new AMessage();
1341 outputFormat->setString(KEY_MIME, desiredMime);
1342 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1343 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1344 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001345 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001346
1347 int32_t gridWidth, gridHeight, gridRows, gridCols;
1348 if (useGrid || mUseHeic) {
1349 gridWidth = HeicEncoderInfoManager::kGridWidth;
1350 gridHeight = HeicEncoderInfoManager::kGridHeight;
1351 gridRows = (height + gridHeight - 1)/gridHeight;
1352 gridCols = (width + gridWidth - 1)/gridWidth;
1353
1354 if (mUseHeic) {
1355 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1356 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1357 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1358 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1359 }
1360
1361 } else {
1362 gridWidth = width;
1363 gridHeight = height;
1364 gridRows = 1;
1365 gridCols = 1;
1366 }
1367
1368 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1369 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1370 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1371 outputFormat->setInt32(KEY_COLOR_FORMAT,
1372 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001373 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001374 // This only serves as a hint to encoder when encoding is not real-time.
1375 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1376
1377 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1378 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1379 if (res != OK) {
1380 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1381 strerror(-res), res);
1382 return res;
1383 }
1384
1385 mGridWidth = gridWidth;
1386 mGridHeight = gridHeight;
1387 mGridRows = gridRows;
1388 mGridCols = gridCols;
1389 mUseGrid = useGrid;
1390 mOutputWidth = width;
1391 mOutputHeight = height;
1392 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001393 mMaxHeicBufferSize =
1394 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1395 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001396
1397 return OK;
1398}
1399
1400void HeicCompositeStream::deinitCodec() {
1401 ALOGV("%s", __FUNCTION__);
1402 if (mCodec != nullptr) {
1403 mCodec->stop();
1404 mCodec->release();
1405 mCodec.clear();
1406 }
1407
1408 if (mCodecLooper != nullptr) {
1409 mCodecLooper->stop();
1410 mCodecLooper.clear();
1411 }
1412
1413 if (mCallbackLooper != nullptr) {
1414 mCallbackLooper->stop();
1415 mCallbackLooper.clear();
1416 }
1417
1418 mAsyncNotify.clear();
1419 mFormat.clear();
1420}
1421
1422// Return the size of the complete list of app segment, 0 indicates failure
1423size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1424 size_t maxSize, size_t *app1SegmentSize) {
1425 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1426 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1427 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1428 return 0;
1429 }
1430
1431 size_t expectedSize = 0;
1432 // First check for EXIF transport header at the end of the buffer
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001433 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(CameraBlob));
1434 const CameraBlob *blob = (const CameraBlob*)(header);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001435 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001436 ALOGE("%s: Invalid EXIF blobId %d", __FUNCTION__, blob->blobId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001437 return 0;
1438 }
1439
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001440 expectedSize = blob->blobSizeBytes;
1441 if (expectedSize == 0 || expectedSize > maxSize - sizeof(CameraBlob)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001442 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1443 return 0;
1444 }
1445
1446 uint32_t totalSize = 0;
1447
1448 // Verify APP1 marker (mandatory)
1449 uint8_t app1Marker[] = {0xFF, 0xE1};
1450 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1451 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1452 appSegmentBuffer[0], appSegmentBuffer[1]);
1453 return 0;
1454 }
1455 totalSize += sizeof(app1Marker);
1456
1457 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1458 appSegmentBuffer[totalSize+1];
1459 totalSize += app1Size;
1460
1461 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1462 __FUNCTION__, expectedSize, app1Size);
1463 while (totalSize < expectedSize) {
1464 if (appSegmentBuffer[totalSize] != 0xFF ||
1465 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1466 appSegmentBuffer[totalSize+1] > 0xEF) {
1467 // Invalid APPn marker
1468 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1469 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1470 return 0;
1471 }
1472 totalSize += 2;
1473
1474 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1475 appSegmentBuffer[totalSize+1];
1476 totalSize += appnSize;
1477 }
1478
1479 if (totalSize != expectedSize) {
1480 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1481 __FUNCTION__, totalSize, expectedSize);
1482 return 0;
1483 }
1484
1485 *app1SegmentSize = app1Size + sizeof(app1Marker);
1486 return expectedSize;
1487}
1488
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001489status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1490 const CpuConsumer::LockedBuffer& yuvBuffer,
1491 size_t top, size_t left, size_t width, size_t height) {
1492 ATRACE_CALL();
1493
1494 // Get stride information for codecBuffer
1495 sp<ABuffer> imageData;
1496 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1497 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1498 return BAD_VALUE;
1499 }
1500 if (imageData->size() != sizeof(MediaImage2)) {
1501 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1502 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1503 return BAD_VALUE;
1504 }
1505 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1506 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1507 imageInfo->mBitDepth != 8 ||
1508 imageInfo->mBitDepthAllocated != 8 ||
1509 imageInfo->mNumPlanes != 3) {
1510 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1511 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1512 imageInfo->mType, imageInfo->mBitDepth,
1513 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1514 return BAD_VALUE;
1515 }
1516
1517 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1518 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1519 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1520 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1521 imageInfo->mPlane[MediaImage2::V].mOffset,
1522 imageInfo->mPlane[MediaImage2::U].mRowInc,
1523 imageInfo->mPlane[MediaImage2::V].mRowInc,
1524 imageInfo->mPlane[MediaImage2::U].mColInc,
1525 imageInfo->mPlane[MediaImage2::V].mColInc);
1526
1527 // Y
1528 for (auto row = top; row < top+height; row++) {
1529 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1530 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001531 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001532 }
1533
1534 // U is Cb, V is Cr
1535 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1536 imageInfo->mPlane[MediaImage2::U].mOffset;
1537 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1538 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1539 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1540 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1541 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1542 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1543 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1544 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1545 bool isCodecUvPlannar =
1546 ((codecUPlaneFirst && codecUvOffsetDiff >=
1547 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1548 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1549 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1550 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1551 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1552 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1553
1554 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1555 (codecUPlaneFirst == cameraUPlaneFirst)) {
1556 // UV semiplannar
1557 // The chrome plane could be either Cb first, or Cr first. Take the
1558 // smaller address.
1559 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1560 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1561 for (auto row = top/2; row < (top+height)/2; row++) {
1562 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1563 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001564 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001565 }
1566 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1567 // U plane
1568 for (auto row = top/2; row < (top+height)/2; row++) {
1569 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1570 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001571 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001572 }
1573
1574 // V plane
1575 for (auto row = top/2; row < (top+height)/2; row++) {
1576 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1577 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001578 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001579 }
1580 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001581 // Convert between semiplannar and plannar, or when UV orders are
1582 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001583 uint8_t *dst = codecBuffer->data();
1584 for (auto row = top/2; row < (top+height)/2; row++) {
1585 for (auto col = left/2; col < (left+width)/2; col++) {
1586 // U/Cb
1587 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1588 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1589 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1590 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1591 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1592
1593 // V/Cr
1594 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1595 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1596 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1597 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1598 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1599 }
1600 }
1601 }
1602 return OK;
1603}
1604
Shuzhen Wang219c2992019-02-15 17:24:28 -08001605void HeicCompositeStream::initCopyRowFunction(int32_t width)
1606{
1607 using namespace libyuv;
1608
1609 mFnCopyRow = CopyRow_C;
1610#if defined(HAS_COPYROW_SSE2)
1611 if (TestCpuFlag(kCpuHasSSE2)) {
1612 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1613 }
1614#endif
1615#if defined(HAS_COPYROW_AVX)
1616 if (TestCpuFlag(kCpuHasAVX)) {
1617 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1618 }
1619#endif
1620#if defined(HAS_COPYROW_ERMS)
1621 if (TestCpuFlag(kCpuHasERMS)) {
1622 mFnCopyRow = CopyRow_ERMS;
1623 }
1624#endif
1625#if defined(HAS_COPYROW_NEON)
1626 if (TestCpuFlag(kCpuHasNEON)) {
1627 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1628 }
1629#endif
1630#if defined(HAS_COPYROW_MIPS)
1631 if (TestCpuFlag(kCpuHasMIPS)) {
1632 mFnCopyRow = CopyRow_MIPS;
1633 }
1634#endif
1635}
1636
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001637size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1638 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1639 size_t maxAppsSegment = 1;
1640 if (entry.count > 0) {
1641 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1642 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1643 }
Jayant Chowdharyc67af1b2022-04-07 18:05:04 +00001644 return maxAppsSegment * (2 + 0xFFFF) + sizeof(CameraBlob);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001645}
1646
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001647void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1648 if (quality != mQuality) {
1649 sp<AMessage> qualityParams = new AMessage;
1650 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1651 status_t res = mCodec->setParameters(qualityParams);
1652 if (res != OK) {
1653 ALOGE("%s: Failed to set codec quality: %s (%d)",
1654 __FUNCTION__, strerror(-res), res);
1655 } else {
1656 mQuality = quality;
1657 }
1658 }
1659}
1660
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001661bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001662 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001663 bool newInputAvailable = false;
1664
1665 {
1666 Mutex::Autolock l(mMutex);
1667 if (mErrorState) {
1668 // In case we landed in error state, return any pending buffers and
1669 // halt all further processing.
1670 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001671 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001672 return false;
1673 }
1674
1675
1676 while (!newInputAvailable) {
1677 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001678 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001679
1680 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001681 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001682 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001683 releaseInputFrameLocked(failingFrameNumber,
1684 &mPendingInputFrames[failingFrameNumber]);
1685
1686 // It's okay to remove the entry from mPendingInputFrames
1687 // because:
1688 // 1. Only one internal stream (main input) is critical in
1689 // backing the output stream.
1690 // 2. If captureResult/appSegment arrives after the entry is
1691 // removed, they are simply skipped.
1692 mPendingInputFrames.erase(failingFrameNumber);
1693 if (mPendingInputFrames.size() == 0) {
1694 markTrackerIdle();
1695 }
1696 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001697 }
1698
1699 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1700 if (ret == TIMED_OUT) {
1701 return true;
1702 } else if (ret != OK) {
1703 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1704 strerror(-ret), ret);
1705 return false;
1706 }
1707 }
1708 }
1709 }
1710
Shuzhen Wange8675782019-12-05 09:12:14 -08001711 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001712 Mutex::Autolock l(mMutex);
1713 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001714 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1715 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1716 frameNumber, strerror(-res), res);
1717 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001718 }
1719
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001720 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001721
1722 return true;
1723}
1724
Shuzhen Wange8675782019-12-05 09:12:14 -08001725void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1726 Mutex::Autolock l(mMutex);
1727 mExifErrorFrameNumbers.emplace(frameNumber);
1728 mInputReadyCondition.signal();
1729}
1730
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001731bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1732 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001733 int64_t frameNumber = resultExtras.frameNumber;
1734
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001735 // Buffer errors concerning internal composite streams should not be directly visible to
1736 // camera clients. They must only receive a single buffer error with the public composite
1737 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001738 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1739 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1740 flagAnExifErrorFrameNumber(frameNumber);
1741 res = true;
1742 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1743 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1744 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001745 res = true;
1746 }
1747
1748 return res;
1749}
1750
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001751void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1752 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1753 // simply skip using the capture result metadata to override EXIF.
1754 Mutex::Autolock l(mMutex);
1755
1756 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001757 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001758 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001759 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001760 break;
1761 }
1762 }
1763 if (timestamp == -1) {
1764 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001765 if (inputFrame.first == resultExtras.frameNumber) {
1766 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001767 break;
1768 }
1769 }
1770 }
1771
1772 if (timestamp == -1) {
1773 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1774 return;
1775 }
1776
1777 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001778 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1779 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001780 mInputReadyCondition.signal();
1781}
1782
Shuzhen Wange8675782019-12-05 09:12:14 -08001783void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1784 auto frameNumber = resultExtras.frameNumber;
1785 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1786 Mutex::Autolock l(mMutex);
1787 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1788 if (numRequests == 0) {
1789 // Pending request has been populated into mPendingInputFrames
1790 mErrorFrameNumbers.emplace(frameNumber);
1791 mInputReadyCondition.signal();
1792 } else {
1793 // REQUEST_ERROR was received without onShutter.
1794 }
1795}
1796
1797void HeicCompositeStream::markTrackerIdle() {
1798 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1799 if (statusTracker != nullptr) {
1800 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1801 ALOGV("%s: Mark component as idle", __FUNCTION__);
1802 }
1803}
1804
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001805void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1806 sp<HeicCompositeStream> parent = mParent.promote();
1807 if (parent == nullptr) return;
1808
1809 switch (msg->what()) {
1810 case kWhatCallbackNotify: {
1811 int32_t cbID;
1812 if (!msg->findInt32("callbackID", &cbID)) {
1813 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1814 break;
1815 }
1816
1817 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1818
1819 switch (cbID) {
1820 case MediaCodec::CB_INPUT_AVAILABLE: {
1821 int32_t index;
1822 if (!msg->findInt32("index", &index)) {
1823 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1824 break;
1825 }
1826 parent->onHeicInputFrameAvailable(index);
1827 break;
1828 }
1829
1830 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1831 int32_t index;
1832 size_t offset;
1833 size_t size;
1834 int64_t timeUs;
1835 int32_t flags;
1836
1837 if (!msg->findInt32("index", &index)) {
1838 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1839 break;
1840 }
1841 if (!msg->findSize("offset", &offset)) {
1842 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1843 break;
1844 }
1845 if (!msg->findSize("size", &size)) {
1846 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1847 break;
1848 }
1849 if (!msg->findInt64("timeUs", &timeUs)) {
1850 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1851 break;
1852 }
1853 if (!msg->findInt32("flags", &flags)) {
1854 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1855 break;
1856 }
1857
1858 CodecOutputBufferInfo bufferInfo = {
1859 index,
1860 (int32_t)offset,
1861 (int32_t)size,
1862 timeUs,
1863 (uint32_t)flags};
1864
1865 parent->onHeicOutputFrameAvailable(bufferInfo);
1866 break;
1867 }
1868
1869 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1870 sp<AMessage> format;
1871 if (!msg->findMessage("format", &format)) {
1872 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1873 break;
1874 }
Chong Zhang860eff12019-09-16 16:15:00 -07001875 // Here format is MediaCodec's internal copy of output format.
1876 // Make a copy since onHeicFormatChanged() might modify it.
1877 sp<AMessage> formatCopy;
1878 if (format != nullptr) {
1879 formatCopy = format->dup();
1880 }
1881 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001882 break;
1883 }
1884
1885 case MediaCodec::CB_ERROR: {
1886 status_t err;
1887 int32_t actionCode;
1888 AString detail;
1889 if (!msg->findInt32("err", &err)) {
1890 ALOGE("CB_ERROR: err is expected.");
1891 break;
1892 }
1893 if (!msg->findInt32("action", &actionCode)) {
1894 ALOGE("CB_ERROR: action is expected.");
1895 break;
1896 }
1897 msg->findString("detail", &detail);
1898 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1899 err, actionCode, detail.c_str());
1900
1901 parent->onHeicCodecError();
1902 break;
1903 }
1904
1905 default: {
1906 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1907 break;
1908 }
1909 }
1910 break;
1911 }
1912
1913 default:
1914 ALOGE("shouldn't be here");
1915 break;
1916 }
1917}
1918
1919}; // namespace camera3
1920}; // namespace android