blob: 5da77d6984922add24d73740ba66714d154e8104 [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
26#include <android/hardware/camera/device/3.5/types.h>
Shuzhen Wang219c2992019-02-15 17:24:28 -080027#include <libyuv.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080028#include <gui/Surface.h>
29#include <utils/Log.h>
30#include <utils/Trace.h>
31
Marco Nelissen13aa1a42019-09-27 10:21:55 -070032#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080033#include <media/MediaCodecBuffer.h>
34#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080035#include <media/stagefright/foundation/MediaDefs.h>
36#include <media/stagefright/MediaCodecConstants.h>
37
38#include "common/CameraDeviceBase.h"
39#include "utils/ExifUtils.h"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080040#include "utils/SessionConfigurationUtils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080041#include "HeicEncoderInfoManager.h"
42#include "HeicCompositeStream.h"
43
44using android::hardware::camera::device::V3_5::CameraBlob;
45using android::hardware::camera::device::V3_5::CameraBlobId;
46
47namespace android {
48namespace camera3 {
49
Shuzhen Wange8675782019-12-05 09:12:14 -080050HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080051 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
52 CompositeStream(device, cb),
53 mUseHeic(false),
54 mNumOutputTiles(1),
55 mOutputWidth(0),
56 mOutputHeight(0),
57 mMaxHeicBufferSize(0),
58 mGridWidth(HeicEncoderInfoManager::kGridWidth),
59 mGridHeight(HeicEncoderInfoManager::kGridHeight),
60 mGridRows(1),
61 mGridCols(1),
62 mUseGrid(false),
63 mAppSegmentStreamId(-1),
64 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080065 mMainImageStreamId(-1),
66 mMainImageSurfaceId(-1),
67 mYuvBufferAcquired(false),
68 mProducerListener(new ProducerListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070069 mDequeuedOutputBufferCnt(0),
70 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070071 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080072 mGridTimestampUs(0),
73 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080074}
75
76HeicCompositeStream::~HeicCompositeStream() {
77 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
78 // memory/resource leak.
79 deinitCodec();
80
81 mInputAppSegmentBuffers.clear();
82 mCodecOutputBuffers.clear();
83
84 mAppSegmentStreamId = -1;
85 mAppSegmentSurfaceId = -1;
86 mAppSegmentConsumer.clear();
87 mAppSegmentSurface.clear();
88
89 mMainImageStreamId = -1;
90 mMainImageSurfaceId = -1;
91 mMainImageConsumer.clear();
92 mMainImageSurface.clear();
93}
94
95bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
96 ANativeWindow *anw = surface.get();
97 status_t err;
98 int format;
99 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
100 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
101 err);
102 ALOGE("%s: %s", __FUNCTION__, msg.string());
103 return false;
104 }
105
106 int dataspace;
107 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
108 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
109 err);
110 ALOGE("%s: %s", __FUNCTION__, msg.string());
111 return false;
112 }
113
114 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
115}
116
117status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
118 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
Emilian Peevf4816702020-04-03 15:44:51 -0700119 camera_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800120 const std::unordered_set<int32_t> &sensorPixelModesUsed,
121 std::vector<int> *surfaceIds,
122 int /*streamSetId*/, bool /*isShared*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800123
124 sp<CameraDeviceBase> device = mDevice.promote();
125 if (!device.get()) {
126 ALOGE("%s: Invalid camera device!", __FUNCTION__);
127 return NO_INIT;
128 }
129
130 status_t res = initializeCodec(width, height, device);
131 if (res != OK) {
132 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
133 __FUNCTION__, strerror(-res), res);
134 return NO_INIT;
135 }
136
137 sp<IGraphicBufferProducer> producer;
138 sp<IGraphicBufferConsumer> consumer;
139 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700140 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800141 mAppSegmentConsumer->setFrameAvailableListener(this);
142 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
143 mAppSegmentSurface = new Surface(producer);
144
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800145 mStaticInfo = device->info();
146
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800147 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800148 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
149 sensorPixelModesUsed,surfaceIds);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800150 if (res == OK) {
151 mAppSegmentSurfaceId = (*surfaceIds)[0];
152 } else {
153 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
154 strerror(-res), res);
155 return res;
156 }
157
158 if (!mUseGrid) {
159 res = mCodec->createInputSurface(&producer);
160 if (res != OK) {
161 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
162 __FUNCTION__, strerror(-res), res);
163 return res;
164 }
165 } else {
166 BufferQueue::createBufferQueue(&producer, &consumer);
167 mMainImageConsumer = new CpuConsumer(consumer, 1);
168 mMainImageConsumer->setFrameAvailableListener(this);
169 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
170 }
171 mMainImageSurface = new Surface(producer);
172
173 res = mCodec->start();
174 if (res != OK) {
175 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
176 strerror(-res), res);
177 return res;
178 }
179
180 std::vector<int> sourceSurfaceId;
181 //Use YUV_888 format if framework tiling is needed.
182 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
183 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
184 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800185 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800186 if (res == OK) {
187 mMainImageSurfaceId = sourceSurfaceId[0];
188 mMainImageStreamId = *id;
189 } else {
190 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
191 strerror(-res), res);
192 return res;
193 }
194
195 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800196 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800197 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800198 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
199 strerror(-res), res);
200 return res;
201 }
202
203 res = registerCompositeStreamListener(mAppSegmentStreamId);
204 if (res != OK) {
205 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
206 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800207 return res;
208 }
209
Shuzhen Wang219c2992019-02-15 17:24:28 -0800210 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800211 return res;
212}
213
214status_t HeicCompositeStream::deleteInternalStreams() {
215 requestExit();
216 auto res = join();
217 if (res != OK) {
218 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
219 strerror(-res), res);
220 }
221
222 deinitCodec();
223
224 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700225 // Camera devices may not be valid after switching to offline mode.
226 // In this case, all offline streams including internal composite streams
227 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800228 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700229 if (device.get() != nullptr) {
230 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800231 }
232
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800233 mAppSegmentStreamId = -1;
234 }
235
Shuzhen Wang2c545042019-02-07 10:27:35 -0800236 if (mOutputSurface != nullptr) {
237 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
238 mOutputSurface.clear();
239 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800240
241 sp<StatusTracker> statusTracker = mStatusTracker.promote();
242 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
243 statusTracker->removeComponent(mStatusId);
244 mStatusId = StatusTracker::NO_STATUS_ID;
245 }
246
247 if (mPendingInputFrames.size() > 0) {
248 ALOGW("%s: mPendingInputFrames has %zu stale entries",
249 __FUNCTION__, mPendingInputFrames.size());
250 mPendingInputFrames.clear();
251 }
252
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800253 return res;
254}
255
256void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
257 Mutex::Autolock l(mMutex);
258
259 if (bufferInfo.mError) return;
260
Shuzhen Wange8675782019-12-05 09:12:14 -0800261 if (bufferInfo.mStreamId == mMainImageStreamId) {
262 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
263 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
264 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
265 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
266 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
267 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
268 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
269 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
270 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800271}
272
273// We need to get the settings early to handle the case where the codec output
274// arrives earlier than result metadata.
275void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
276 const CameraMetadata& settings) {
277 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
278
279 Mutex::Autolock l(mMutex);
280 if (mErrorState || (streamId != getStreamId())) {
281 return;
282 }
283
284 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
285
286 camera_metadata_ro_entry entry;
287
288 int32_t orientation = 0;
289 entry = settings.find(ANDROID_JPEG_ORIENTATION);
290 if (entry.count == 1) {
291 orientation = entry.data.i32[0];
292 }
293
294 int32_t quality = kDefaultJpegQuality;
295 entry = settings.find(ANDROID_JPEG_QUALITY);
296 if (entry.count == 1) {
297 quality = entry.data.i32[0];
298 }
299
Shuzhen Wange8675782019-12-05 09:12:14 -0800300 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800301}
302
303void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
304 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
305 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
306 __func__, ns2ms(item.mTimestamp));
307
308 Mutex::Autolock l(mMutex);
309 if (!mErrorState) {
310 mInputAppSegmentBuffers.push_back(item.mTimestamp);
311 mInputReadyCondition.signal();
312 }
313 } else if (item.mDataSpace == kHeifDataSpace) {
314 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
315 __func__, ns2ms(item.mTimestamp));
316
317 Mutex::Autolock l(mMutex);
318 if (!mUseGrid) {
319 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
320 __FUNCTION__);
321 return;
322 }
323 if (!mErrorState) {
324 mInputYuvBuffers.push_back(item.mTimestamp);
325 mInputReadyCondition.signal();
326 }
327 } else {
328 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
329 }
330}
331
332status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
333 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
334 if (compositeOutput == nullptr) {
335 return BAD_VALUE;
336 }
337
338 compositeOutput->clear();
339
340 bool useGrid, useHeic;
341 bool isSizeSupported = isSizeSupportedByHeifEncoder(
342 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
343 if (!isSizeSupported) {
344 // Size is not supported by either encoder.
345 return OK;
346 }
347
348 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
349
350 // JPEG APPS segments Blob stream info
351 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
352 (*compositeOutput)[0].height = 1;
353 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
354 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
355 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
356
357 // YUV/IMPLEMENTATION_DEFINED stream info
358 (*compositeOutput)[1].width = streamInfo.width;
359 (*compositeOutput)[1].height = streamInfo.height;
360 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
361 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
362 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
363 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
364 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
365
366 return NO_ERROR;
367}
368
369bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700370 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800371 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700372 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800373}
374
375bool HeicCompositeStream::isInMemoryTempFileSupported() {
376 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
377 if (memfd == -1) {
378 if (errno != ENOSYS) {
379 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
380 }
381 return false;
382 }
383 close(memfd);
384 return true;
385}
386
387void HeicCompositeStream::onHeicOutputFrameAvailable(
388 const CodecOutputBufferInfo& outputBufferInfo) {
389 Mutex::Autolock l(mMutex);
390
391 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
392 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
393 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
394
395 if (!mErrorState) {
396 if ((outputBufferInfo.size > 0) &&
397 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
398 mCodecOutputBuffers.push_back(outputBufferInfo);
399 mInputReadyCondition.signal();
400 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700401 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
402 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800403 mCodec->releaseOutputBuffer(outputBufferInfo.index);
404 }
405 } else {
406 mCodec->releaseOutputBuffer(outputBufferInfo.index);
407 }
408}
409
410void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
411 Mutex::Autolock l(mMutex);
412
413 if (!mUseGrid) {
414 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
415 return;
416 }
417
418 mCodecInputBuffers.push_back(index);
419 mInputReadyCondition.signal();
420}
421
422void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
423 if (newFormat == nullptr) {
424 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
425 return;
426 }
427
428 Mutex::Autolock l(mMutex);
429
430 AString mime;
431 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
432 newFormat->findString(KEY_MIME, &mime);
433 if (mime != mimeHeic) {
434 // For HEVC codec, below keys need to be filled out or overwritten so that the
435 // muxer can handle them as HEIC output image.
436 newFormat->setString(KEY_MIME, mimeHeic);
437 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
438 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
439 if (mUseGrid) {
440 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
441 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
442 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
443 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
dan.shen60fa4b92022-04-12 18:57:43 +0800444 int32_t left, top, right, bottom;
445 if (newFormat->findRect("crop", &left, &top, &right, &bottom)) {
446 newFormat->setRect("crop", 0, 0, mOutputWidth - 1, mOutputHeight - 1);
447 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800448 }
449 }
450 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
451
452 int32_t gridRows, gridCols;
453 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
454 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
455 mNumOutputTiles = gridRows * gridCols;
456 } else {
457 mNumOutputTiles = 1;
458 }
459
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800460 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700461
462 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
463 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800464}
465
466void HeicCompositeStream::onHeicCodecError() {
467 Mutex::Autolock l(mMutex);
468 mErrorState = true;
469}
470
471status_t HeicCompositeStream::configureStream() {
472 if (isRunning()) {
473 // Processing thread is already running, nothing more to do.
474 return NO_ERROR;
475 }
476
477 if (mOutputSurface.get() == nullptr) {
478 ALOGE("%s: No valid output surface set!", __FUNCTION__);
479 return NO_INIT;
480 }
481
482 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
483 if (res != OK) {
484 ALOGE("%s: Unable to connect to native window for stream %d",
485 __FUNCTION__, mMainImageStreamId);
486 return res;
487 }
488
489 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
490 != OK) {
491 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
492 mMainImageStreamId);
493 return res;
494 }
495
496 ANativeWindow *anwConsumer = mOutputSurface.get();
497 int maxConsumerBuffers;
498 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
499 &maxConsumerBuffers)) != OK) {
500 ALOGE("%s: Unable to query consumer undequeued"
501 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
502 return res;
503 }
504
505 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
506 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800507 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700508 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800509 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
510 return res;
511 }
512
513 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
514 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
515 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
516 return res;
517 }
518
Shuzhen Wange8675782019-12-05 09:12:14 -0800519 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
520 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700521 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
522 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800523 }
524
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800525 run("HeicCompositeStreamProc");
526
527 return NO_ERROR;
528}
529
530status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
531 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
532 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800533 outputStreamIds->push_back(mAppSegmentStreamId);
534 }
535 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
536
537 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800538 outputStreamIds->push_back(mMainImageStreamId);
539 }
540 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
541
542 if (currentStreamId != nullptr) {
543 *currentStreamId = mMainImageStreamId;
544 }
545
546 return NO_ERROR;
547}
548
Emilian Peev4697b642019-11-19 17:11:14 -0800549status_t HeicCompositeStream::insertCompositeStreamIds(
550 std::vector<int32_t>* compositeStreamIds /*out*/) {
551 if (compositeStreamIds == nullptr) {
552 return BAD_VALUE;
553 }
554
555 compositeStreamIds->push_back(mAppSegmentStreamId);
556 compositeStreamIds->push_back(mMainImageStreamId);
557
558 return OK;
559}
560
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800561void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
562 Mutex::Autolock l(mMutex);
563 if (mErrorState) {
564 return;
565 }
566
567 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800568 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
569 resultExtras.frameNumber, timestamp, resultExtras.requestId);
570 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
571 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
572 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800573 mInputReadyCondition.signal();
574 }
575}
576
577void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800578 auto i = mSettingsByFrameNumber.begin();
579 while (i != mSettingsByFrameNumber.end()) {
580 if (i->second.shutterNotified) {
581 mPendingInputFrames[i->first].orientation = i->second.orientation;
582 mPendingInputFrames[i->first].quality = i->second.quality;
583 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
584 mPendingInputFrames[i->first].requestId = i->second.requestId;
585 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
586 i->first, i->second.timestamp);
587 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700588
Shuzhen Wange8675782019-12-05 09:12:14 -0800589 // Set encoder quality if no inflight encoding
590 if (mPendingInputFrames.size() == 1) {
591 sp<StatusTracker> statusTracker = mStatusTracker.promote();
592 if (statusTracker != nullptr) {
593 statusTracker->markComponentActive(mStatusId);
594 ALOGV("%s: Mark component as active", __FUNCTION__);
595 }
596
597 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
598 updateCodecQualityLocked(newQuality);
599 }
600 } else {
601 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700602 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800603 }
604
Shuzhen Wange8675782019-12-05 09:12:14 -0800605 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800606 CpuConsumer::LockedBuffer imgBuffer;
607 auto it = mInputAppSegmentBuffers.begin();
608 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
609 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700610 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800611 break;
612 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
613 if (res != OK) {
614 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
615 strerror(-res), res);
616 } else {
617 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
618 " received buffer with time stamp: %" PRId64, __FUNCTION__,
619 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700620 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800621 }
622 mPendingInputFrames[*it].error = true;
623 mInputAppSegmentBuffers.erase(it);
624 continue;
625 }
626
Shuzhen Wange8675782019-12-05 09:12:14 -0800627 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
628 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
629 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700630 mInputAppSegmentBuffers.erase(it);
631 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800632 continue;
633 }
634
635 int64_t frameNumber = mAppSegmentFrameNumbers.front();
636 // If mPendingInputFrames doesn't contain the expected frame number, the captured
637 // input app segment frame must have been dropped via a buffer error. Simply
638 // return the buffer to the buffer queue.
639 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
640 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800641 mAppSegmentConsumer->unlockBuffer(imgBuffer);
642 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800643 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800644 }
645 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800646 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800647 }
648
Shuzhen Wange8675782019-12-05 09:12:14 -0800649 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800650 CpuConsumer::LockedBuffer imgBuffer;
651 auto it = mInputYuvBuffers.begin();
652 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
653 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700654 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800655 break;
656 } else if (res != OK) {
657 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
658 strerror(-res), res);
659 mPendingInputFrames[*it].error = true;
660 mInputYuvBuffers.erase(it);
661 continue;
662 } else if (*it != imgBuffer.timestamp) {
663 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
664 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
665 mPendingInputFrames[*it].error = true;
666 mInputYuvBuffers.erase(it);
667 continue;
668 }
669
Shuzhen Wange8675782019-12-05 09:12:14 -0800670 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
671 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
672 mMainImageFrameNumbers.front());
673 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700674 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800675 continue;
676 }
677
678 int64_t frameNumber = mMainImageFrameNumbers.front();
679 // If mPendingInputFrames doesn't contain the expected frame number, the captured
680 // input main image must have been dropped via a buffer error. Simply
681 // return the buffer to the buffer queue.
682 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
683 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800684 mMainImageConsumer->unlockBuffer(imgBuffer);
685 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800686 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800687 mYuvBufferAcquired = true;
688 }
689 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800690 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800691 }
692
693 while (!mCodecOutputBuffers.empty()) {
694 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800695 // Assume encoder input to output is FIFO, use a queue to look up
696 // frameNumber when handling codec outputs.
697 int64_t bufferFrameNumber = -1;
698 if (mCodecOutputBufferFrameNumbers.empty()) {
699 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700700 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800701 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800702 // Direct mapping between camera frame number and codec timestamp (in us).
703 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700704 mCodecOutputCounter++;
705 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800706 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700707 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800708 }
709
Shuzhen Wange8675782019-12-05 09:12:14 -0800710 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
711 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
712 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800713 }
714 mCodecOutputBuffers.erase(it);
715 }
716
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800717 while (!mCaptureResults.empty()) {
718 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800719 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800720 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800721 int64_t frameNumber = std::get<0>(it->second);
722 if (it->first >= 0 &&
723 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
724 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
725 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800726 std::make_unique<CameraMetadata>(std::get<1>(it->second));
727 } else {
728 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800729 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
730 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
731 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800732 }
733 }
734 mCaptureResults.erase(it);
735 }
736
737 // mErrorFrameNumbers stores frame number of dropped buffers.
738 auto it = mErrorFrameNumbers.begin();
739 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800740 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
741 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800742 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800743 //Error callback is guaranteed to arrive after shutter notify, which
744 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800745 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
746 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800747 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800748 it = mErrorFrameNumbers.erase(it);
749 }
750
751 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
752 it = mExifErrorFrameNumbers.begin();
753 while (it != mExifErrorFrameNumbers.end()) {
754 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
755 mPendingInputFrames[*it].exifError = true;
756 }
757 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800758 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800759
760 // Distribute codec input buffers to be filled out from YUV output
761 for (auto it = mPendingInputFrames.begin();
762 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
763 InputFrame& inputFrame(it->second);
764 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
765 // Available input tiles that are required for the current input
766 // image.
767 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
768 mGridRows * mGridCols - inputFrame.codecInputCounter);
769 for (size_t i = 0; i < newInputTiles; i++) {
770 CodecInputBufferInfo inputInfo =
771 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
772 inputFrame.codecInputBuffers.push_back(inputInfo);
773
774 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
775 inputFrame.codecInputCounter++;
776 }
777 break;
778 }
779 }
780}
781
Shuzhen Wange8675782019-12-05 09:12:14 -0800782bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
783 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800784 return false;
785 }
786
787 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700788 for (auto& it : mPendingInputFrames) {
789 // New input is considered to be available only if:
790 // 1. input buffers are ready, or
791 // 2. App segment and muxer is created, or
792 // 3. A codec output tile is ready, and an output buffer is available.
793 // This makes sure that muxer gets created only when an output tile is
794 // generated, because right now we only handle 1 HEIC output buffer at a
795 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800796 bool appSegmentReady =
797 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700798 !it.second.appSegmentWritten && it.second.result != nullptr &&
799 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800800 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
801 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
802 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700803 bool hasOutputBuffer = it.second.muxer != nullptr ||
804 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800805 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700806 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800807 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700808 if (it.second.format == nullptr && mFormat != nullptr) {
809 it.second.format = mFormat->dup();
810 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800811 newInputAvailable = true;
812 break;
813 }
814 }
815
816 return newInputAvailable;
817}
818
Shuzhen Wange8675782019-12-05 09:12:14 -0800819int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800820 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800821
822 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800823 if (it.second.error) {
824 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800825 break;
826 }
827 }
828
829 return res;
830}
831
Shuzhen Wange8675782019-12-05 09:12:14 -0800832status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800833 InputFrame &inputFrame) {
834 ATRACE_CALL();
835 status_t res = OK;
836
Shuzhen Wange8675782019-12-05 09:12:14 -0800837 bool appSegmentReady =
838 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700839 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
840 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800841 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
842 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700843 !inputFrame.codecInputBuffers.empty();
844 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
845 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800846
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700847 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800848 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
849 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
850 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800851
852 // Handle inputs for Hevc tiling
853 if (codecInputReady) {
854 res = processCodecInputFrame(inputFrame);
855 if (res != OK) {
856 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
857 strerror(-res), res);
858 return res;
859 }
860 }
861
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700862 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
863 return OK;
864 }
865
866 // Initialize and start muxer if not yet done so. In this case,
867 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
868 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800869 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800870 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800871 if (res != OK) {
872 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
873 strerror(-res), res);
874 return res;
875 }
876 }
877
878 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700879 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800880 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800881 if (res != OK) {
882 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
883 strerror(-res), res);
884 return res;
885 }
886 }
887
888 // Write media codec bitstream buffers to muxer.
889 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800890 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800891 if (res != OK) {
892 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
893 strerror(-res), res);
894 return res;
895 }
896 }
897
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700898 if (inputFrame.pendingOutputTiles == 0) {
899 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800900 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700901 if (res != OK) {
902 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
903 strerror(-res), res);
904 return res;
905 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800906 }
907 }
908
909 return res;
910}
911
Shuzhen Wange8675782019-12-05 09:12:14 -0800912status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800913 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800914
915 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
916 if (res != OK) {
917 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
918 res);
919 return res;
920 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700921 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800922
923 // Combine current thread id, stream id and timestamp to uniquely identify image.
924 std::ostringstream tempOutputFile;
925 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800926 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800927 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
928 if (inputFrame.fileFd < 0) {
929 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
930 tempOutputFile.str().c_str(), errno);
931 return NO_INIT;
932 }
933 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
934 if (inputFrame.muxer == nullptr) {
935 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
936 __FUNCTION__, inputFrame.fileFd);
937 return NO_INIT;
938 }
939
940 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
941 if (res != OK) {
942 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
943 strerror(-res), res);
944 return res;
945 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800946
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700947 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800948 if (trackId < 0) {
949 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
950 return NO_INIT;
951 }
952
953 inputFrame.trackIndex = trackId;
954 inputFrame.pendingOutputTiles = mNumOutputTiles;
955
956 res = inputFrame.muxer->start();
957 if (res != OK) {
958 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
959 __FUNCTION__, strerror(-res), res);
960 return res;
961 }
962
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700963 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800964 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800965 return OK;
966}
967
Shuzhen Wange8675782019-12-05 09:12:14 -0800968status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800969 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800970 size_t appSegmentSize = 0;
971 if (!inputFrame.exifError) {
972 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
973 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
974 &app1Size);
975 if (appSegmentSize == 0) {
976 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
977 return NO_INIT;
978 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800979 }
980
981 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800982 auto exifRes = inputFrame.exifError ?
983 exifUtils->initializeEmpty() :
984 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800985 if (!exifRes) {
986 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
987 return BAD_VALUE;
988 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800989 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
990 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800991 if (!exifRes) {
992 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
993 return BAD_VALUE;
994 }
995 exifRes = exifUtils->setOrientation(inputFrame.orientation);
996 if (!exifRes) {
997 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
998 return BAD_VALUE;
999 }
1000 exifRes = exifUtils->generateApp1();
1001 if (!exifRes) {
1002 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1003 return BAD_VALUE;
1004 }
1005
1006 unsigned int newApp1Length = exifUtils->getApp1Length();
1007 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1008
1009 //Assemble the APP1 marker buffer required by MediaCodec
1010 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1011 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1012 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1013 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1014 appSegmentSize - app1Size + newApp1Length;
1015 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1016 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1017 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1018 if (appSegmentSize - app1Size > 0) {
1019 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1020 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1021 }
1022
1023 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1024 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001025 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001026 delete[] appSegmentBuffer;
1027
1028 if (res != OK) {
1029 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1030 __FUNCTION__, strerror(-res), res);
1031 return res;
1032 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001033
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001034 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001035 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001036 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001037
1038 inputFrame.appSegmentWritten = true;
1039 // Release the buffer now so any pending input app segments can be processed
1040 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1041 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001042 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001043
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001044 return OK;
1045}
1046
1047status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1048 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1049 sp<MediaCodecBuffer> buffer;
1050 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1051 if (res != OK) {
1052 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1053 strerror(-res), res);
1054 return res;
1055 }
1056
1057 // Copy one tile from source to destination.
1058 size_t tileX = inputBuffer.tileIndex % mGridCols;
1059 size_t tileY = inputBuffer.tileIndex / mGridCols;
1060 size_t top = mGridHeight * tileY;
1061 size_t left = mGridWidth * tileX;
1062 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1063 mOutputWidth - tileX * mGridWidth : mGridWidth;
1064 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1065 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001066 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1067 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1068 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001069
1070 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1071 if (res != OK) {
1072 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1073 strerror(-res), res);
1074 return res;
1075 }
1076
1077 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1078 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1079 if (res != OK) {
1080 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1081 __FUNCTION__, strerror(-res), res);
1082 return res;
1083 }
1084 }
1085
1086 inputFrame.codecInputBuffers.clear();
1087 return OK;
1088}
1089
Shuzhen Wange8675782019-12-05 09:12:14 -08001090status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001091 InputFrame &inputFrame) {
1092 auto it = inputFrame.codecOutputBuffers.begin();
1093 sp<MediaCodecBuffer> buffer;
1094 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1095 if (res != OK) {
1096 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1097 __FUNCTION__, it->index, strerror(-res), res);
1098 return res;
1099 }
1100 if (buffer == nullptr) {
1101 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1102 __FUNCTION__, it->index);
1103 return BAD_VALUE;
1104 }
1105
1106 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1107 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001108 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001109 if (res != OK) {
1110 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1111 __FUNCTION__, it->index, strerror(-res), res);
1112 return res;
1113 }
1114
1115 mCodec->releaseOutputBuffer(it->index);
1116 if (inputFrame.pendingOutputTiles == 0) {
1117 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1118 } else {
1119 inputFrame.pendingOutputTiles--;
1120 }
1121
1122 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001123
1124 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001125 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001126 return OK;
1127}
1128
Shuzhen Wange8675782019-12-05 09:12:14 -08001129status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001130 InputFrame &inputFrame) {
1131 sp<ANativeWindow> outputANW = mOutputSurface;
1132 inputFrame.muxer->stop();
1133
1134 // Copy the content of the file to memory.
1135 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1136 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001137 GraphicBufferLocker gbLocker(gb);
1138 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001139 if (res != OK) {
1140 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1141 strerror(-res), res);
1142 return res;
1143 }
1144
1145 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1146 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1147 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1148 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1149 return BAD_VALUE;
1150 }
1151
1152 lseek(inputFrame.fileFd, 0, SEEK_SET);
1153 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1154 if (bytesRead < fSize) {
1155 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1156 return BAD_VALUE;
1157 }
1158
1159 close(inputFrame.fileFd);
1160 inputFrame.fileFd = -1;
1161
1162 // Fill in HEIC header
1163 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1164 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
1165 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
1166 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
1167 blobHeader->blobSize = fSize;
1168
Shuzhen Wange8675782019-12-05 09:12:14 -08001169 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001170 if (res != OK) {
1171 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1172 __FUNCTION__, getStreamId(), strerror(-res), res);
1173 return res;
1174 }
1175
1176 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1177 if (res != OK) {
1178 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1179 strerror(-res), res);
1180 return res;
1181 }
1182 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001183 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001184
Shuzhen Wange8675782019-12-05 09:12:14 -08001185 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1186 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001187 return OK;
1188}
1189
1190
Shuzhen Wange8675782019-12-05 09:12:14 -08001191void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1192 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001193 if (inputFrame == nullptr) {
1194 return;
1195 }
1196
1197 if (inputFrame->appSegmentBuffer.data != nullptr) {
1198 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1199 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001200 }
1201
1202 while (!inputFrame->codecOutputBuffers.empty()) {
1203 auto it = inputFrame->codecOutputBuffers.begin();
1204 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1205 mCodec->releaseOutputBuffer(it->index);
1206 inputFrame->codecOutputBuffers.erase(it);
1207 }
1208
1209 if (inputFrame->yuvBuffer.data != nullptr) {
1210 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1211 inputFrame->yuvBuffer.data = nullptr;
1212 mYuvBufferAcquired = false;
1213 }
1214
1215 while (!inputFrame->codecInputBuffers.empty()) {
1216 auto it = inputFrame->codecInputBuffers.begin();
1217 inputFrame->codecInputBuffers.erase(it);
1218 }
1219
Shuzhen Wange8675782019-12-05 09:12:14 -08001220 if (inputFrame->error || mErrorState) {
1221 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1222 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001223 }
1224
1225 if (inputFrame->fileFd >= 0) {
1226 close(inputFrame->fileFd);
1227 inputFrame->fileFd = -1;
1228 }
1229
1230 if (inputFrame->anb != nullptr) {
1231 sp<ANativeWindow> outputANW = mOutputSurface;
1232 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1233 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001234
1235 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001236 }
1237}
1238
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001239void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001240 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001241 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001242 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001243 auto& inputFrame = it->second;
1244 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001245 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1246 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001247 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001248 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001249 } else {
1250 it++;
1251 }
1252 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001253
1254 // Update codec quality based on first upcoming input frame.
1255 // Note that when encoding is in surface mode, currently there is no
1256 // way for camera service to synchronize quality setting on a per-frame
1257 // basis: we don't get notification when codec is ready to consume a new
1258 // input frame. So we update codec quality on a best-effort basis.
1259 if (inputFrameDone) {
1260 auto firstPendingFrame = mPendingInputFrames.begin();
1261 if (firstPendingFrame != mPendingInputFrames.end()) {
1262 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001263 } else {
1264 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001265 }
1266 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001267}
1268
1269status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1270 const sp<CameraDeviceBase>& cameraDevice) {
1271 ALOGV("%s", __FUNCTION__);
1272
1273 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001274 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001275 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001276 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001277 if (!isSizeSupported) {
1278 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1279 __FUNCTION__, width, height);
1280 return BAD_VALUE;
1281 }
1282
1283 // Create Looper for MediaCodec.
1284 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1285 mCodecLooper = new ALooper;
1286 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1287 status_t res = mCodecLooper->start(
1288 false, // runOnCallingThread
1289 false, // canCallJava
1290 PRIORITY_AUDIO);
1291 if (res != OK) {
1292 ALOGE("%s: Failed to start codec looper: %s (%d)",
1293 __FUNCTION__, strerror(-res), res);
1294 return NO_INIT;
1295 }
1296
1297 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001298 if (mUseHeic) {
1299 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1300 } else {
1301 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1302 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001303 if (mCodec == nullptr) {
1304 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1305 return NO_INIT;
1306 }
1307
1308 // Create Looper and handler for Codec callback.
1309 mCodecCallbackHandler = new CodecCallbackHandler(this);
1310 if (mCodecCallbackHandler == nullptr) {
1311 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1312 return NO_MEMORY;
1313 }
1314 mCallbackLooper = new ALooper;
1315 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1316 res = mCallbackLooper->start(
1317 false, // runOnCallingThread
1318 false, // canCallJava
1319 PRIORITY_AUDIO);
1320 if (res != OK) {
1321 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1322 __FUNCTION__, strerror(-res), res);
1323 return NO_INIT;
1324 }
1325 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1326
1327 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1328 res = mCodec->setCallback(mAsyncNotify);
1329 if (res != OK) {
1330 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1331 strerror(-res), res);
1332 return res;
1333 }
1334
1335 // Create output format and configure the Codec.
1336 sp<AMessage> outputFormat = new AMessage();
1337 outputFormat->setString(KEY_MIME, desiredMime);
1338 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1339 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1340 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001341 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001342
1343 int32_t gridWidth, gridHeight, gridRows, gridCols;
1344 if (useGrid || mUseHeic) {
1345 gridWidth = HeicEncoderInfoManager::kGridWidth;
1346 gridHeight = HeicEncoderInfoManager::kGridHeight;
1347 gridRows = (height + gridHeight - 1)/gridHeight;
1348 gridCols = (width + gridWidth - 1)/gridWidth;
1349
1350 if (mUseHeic) {
1351 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1352 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1353 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1354 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1355 }
1356
1357 } else {
1358 gridWidth = width;
1359 gridHeight = height;
1360 gridRows = 1;
1361 gridCols = 1;
1362 }
1363
1364 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1365 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1366 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1367 outputFormat->setInt32(KEY_COLOR_FORMAT,
1368 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001369 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001370 // This only serves as a hint to encoder when encoding is not real-time.
1371 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1372
1373 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1374 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1375 if (res != OK) {
1376 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1377 strerror(-res), res);
1378 return res;
1379 }
1380
1381 mGridWidth = gridWidth;
1382 mGridHeight = gridHeight;
1383 mGridRows = gridRows;
1384 mGridCols = gridCols;
1385 mUseGrid = useGrid;
1386 mOutputWidth = width;
1387 mOutputHeight = height;
1388 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001389 mMaxHeicBufferSize =
1390 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1391 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001392
1393 return OK;
1394}
1395
1396void HeicCompositeStream::deinitCodec() {
1397 ALOGV("%s", __FUNCTION__);
1398 if (mCodec != nullptr) {
1399 mCodec->stop();
1400 mCodec->release();
1401 mCodec.clear();
1402 }
1403
1404 if (mCodecLooper != nullptr) {
1405 mCodecLooper->stop();
1406 mCodecLooper.clear();
1407 }
1408
1409 if (mCallbackLooper != nullptr) {
1410 mCallbackLooper->stop();
1411 mCallbackLooper.clear();
1412 }
1413
1414 mAsyncNotify.clear();
1415 mFormat.clear();
1416}
1417
1418// Return the size of the complete list of app segment, 0 indicates failure
1419size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1420 size_t maxSize, size_t *app1SegmentSize) {
1421 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1422 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1423 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1424 return 0;
1425 }
1426
1427 size_t expectedSize = 0;
1428 // First check for EXIF transport header at the end of the buffer
1429 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1430 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1431 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1432 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1433 return 0;
1434 }
1435
1436 expectedSize = blob->blobSize;
1437 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1438 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1439 return 0;
1440 }
1441
1442 uint32_t totalSize = 0;
1443
1444 // Verify APP1 marker (mandatory)
1445 uint8_t app1Marker[] = {0xFF, 0xE1};
1446 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1447 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1448 appSegmentBuffer[0], appSegmentBuffer[1]);
1449 return 0;
1450 }
1451 totalSize += sizeof(app1Marker);
1452
1453 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1454 appSegmentBuffer[totalSize+1];
1455 totalSize += app1Size;
1456
1457 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1458 __FUNCTION__, expectedSize, app1Size);
1459 while (totalSize < expectedSize) {
1460 if (appSegmentBuffer[totalSize] != 0xFF ||
1461 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1462 appSegmentBuffer[totalSize+1] > 0xEF) {
1463 // Invalid APPn marker
1464 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1465 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1466 return 0;
1467 }
1468 totalSize += 2;
1469
1470 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1471 appSegmentBuffer[totalSize+1];
1472 totalSize += appnSize;
1473 }
1474
1475 if (totalSize != expectedSize) {
1476 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1477 __FUNCTION__, totalSize, expectedSize);
1478 return 0;
1479 }
1480
1481 *app1SegmentSize = app1Size + sizeof(app1Marker);
1482 return expectedSize;
1483}
1484
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001485status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1486 const CpuConsumer::LockedBuffer& yuvBuffer,
1487 size_t top, size_t left, size_t width, size_t height) {
1488 ATRACE_CALL();
1489
1490 // Get stride information for codecBuffer
1491 sp<ABuffer> imageData;
1492 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1493 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1494 return BAD_VALUE;
1495 }
1496 if (imageData->size() != sizeof(MediaImage2)) {
1497 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1498 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1499 return BAD_VALUE;
1500 }
1501 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1502 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1503 imageInfo->mBitDepth != 8 ||
1504 imageInfo->mBitDepthAllocated != 8 ||
1505 imageInfo->mNumPlanes != 3) {
1506 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1507 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1508 imageInfo->mType, imageInfo->mBitDepth,
1509 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1510 return BAD_VALUE;
1511 }
1512
1513 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1514 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1515 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1516 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1517 imageInfo->mPlane[MediaImage2::V].mOffset,
1518 imageInfo->mPlane[MediaImage2::U].mRowInc,
1519 imageInfo->mPlane[MediaImage2::V].mRowInc,
1520 imageInfo->mPlane[MediaImage2::U].mColInc,
1521 imageInfo->mPlane[MediaImage2::V].mColInc);
1522
1523 // Y
1524 for (auto row = top; row < top+height; row++) {
1525 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1526 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001527 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001528 }
1529
1530 // U is Cb, V is Cr
1531 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1532 imageInfo->mPlane[MediaImage2::U].mOffset;
1533 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1534 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1535 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1536 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1537 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1538 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1539 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1540 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1541 bool isCodecUvPlannar =
1542 ((codecUPlaneFirst && codecUvOffsetDiff >=
1543 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1544 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1545 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1546 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1547 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1548 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1549
1550 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1551 (codecUPlaneFirst == cameraUPlaneFirst)) {
1552 // UV semiplannar
1553 // The chrome plane could be either Cb first, or Cr first. Take the
1554 // smaller address.
1555 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1556 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1557 for (auto row = top/2; row < (top+height)/2; row++) {
1558 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1559 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001560 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001561 }
1562 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1563 // U plane
1564 for (auto row = top/2; row < (top+height)/2; row++) {
1565 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1566 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001567 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001568 }
1569
1570 // V plane
1571 for (auto row = top/2; row < (top+height)/2; row++) {
1572 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1573 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001574 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001575 }
1576 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001577 // Convert between semiplannar and plannar, or when UV orders are
1578 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001579 uint8_t *dst = codecBuffer->data();
1580 for (auto row = top/2; row < (top+height)/2; row++) {
1581 for (auto col = left/2; col < (left+width)/2; col++) {
1582 // U/Cb
1583 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1584 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1585 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1586 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1587 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1588
1589 // V/Cr
1590 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1591 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1592 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1593 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1594 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1595 }
1596 }
1597 }
1598 return OK;
1599}
1600
Shuzhen Wang219c2992019-02-15 17:24:28 -08001601void HeicCompositeStream::initCopyRowFunction(int32_t width)
1602{
1603 using namespace libyuv;
1604
1605 mFnCopyRow = CopyRow_C;
1606#if defined(HAS_COPYROW_SSE2)
1607 if (TestCpuFlag(kCpuHasSSE2)) {
1608 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1609 }
1610#endif
1611#if defined(HAS_COPYROW_AVX)
1612 if (TestCpuFlag(kCpuHasAVX)) {
1613 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1614 }
1615#endif
1616#if defined(HAS_COPYROW_ERMS)
1617 if (TestCpuFlag(kCpuHasERMS)) {
1618 mFnCopyRow = CopyRow_ERMS;
1619 }
1620#endif
1621#if defined(HAS_COPYROW_NEON)
1622 if (TestCpuFlag(kCpuHasNEON)) {
1623 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1624 }
1625#endif
1626#if defined(HAS_COPYROW_MIPS)
1627 if (TestCpuFlag(kCpuHasMIPS)) {
1628 mFnCopyRow = CopyRow_MIPS;
1629 }
1630#endif
1631}
1632
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001633size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1634 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1635 size_t maxAppsSegment = 1;
1636 if (entry.count > 0) {
1637 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1638 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1639 }
1640 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1641}
1642
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001643void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1644 if (quality != mQuality) {
1645 sp<AMessage> qualityParams = new AMessage;
1646 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1647 status_t res = mCodec->setParameters(qualityParams);
1648 if (res != OK) {
1649 ALOGE("%s: Failed to set codec quality: %s (%d)",
1650 __FUNCTION__, strerror(-res), res);
1651 } else {
1652 mQuality = quality;
1653 }
1654 }
1655}
1656
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001657bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001658 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001659 bool newInputAvailable = false;
1660
1661 {
1662 Mutex::Autolock l(mMutex);
1663 if (mErrorState) {
1664 // In case we landed in error state, return any pending buffers and
1665 // halt all further processing.
1666 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001667 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001668 return false;
1669 }
1670
1671
1672 while (!newInputAvailable) {
1673 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001674 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001675
1676 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001677 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001678 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001679 releaseInputFrameLocked(failingFrameNumber,
1680 &mPendingInputFrames[failingFrameNumber]);
1681
1682 // It's okay to remove the entry from mPendingInputFrames
1683 // because:
1684 // 1. Only one internal stream (main input) is critical in
1685 // backing the output stream.
1686 // 2. If captureResult/appSegment arrives after the entry is
1687 // removed, they are simply skipped.
1688 mPendingInputFrames.erase(failingFrameNumber);
1689 if (mPendingInputFrames.size() == 0) {
1690 markTrackerIdle();
1691 }
1692 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001693 }
1694
1695 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1696 if (ret == TIMED_OUT) {
1697 return true;
1698 } else if (ret != OK) {
1699 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1700 strerror(-ret), ret);
1701 return false;
1702 }
1703 }
1704 }
1705 }
1706
Shuzhen Wange8675782019-12-05 09:12:14 -08001707 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001708 Mutex::Autolock l(mMutex);
1709 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001710 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1711 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1712 frameNumber, strerror(-res), res);
1713 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001714 }
1715
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001716 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001717
1718 return true;
1719}
1720
Shuzhen Wange8675782019-12-05 09:12:14 -08001721void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1722 Mutex::Autolock l(mMutex);
1723 mExifErrorFrameNumbers.emplace(frameNumber);
1724 mInputReadyCondition.signal();
1725}
1726
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001727bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1728 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001729 int64_t frameNumber = resultExtras.frameNumber;
1730
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001731 // Buffer errors concerning internal composite streams should not be directly visible to
1732 // camera clients. They must only receive a single buffer error with the public composite
1733 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001734 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1735 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1736 flagAnExifErrorFrameNumber(frameNumber);
1737 res = true;
1738 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1739 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1740 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001741 res = true;
1742 }
1743
1744 return res;
1745}
1746
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001747void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1748 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1749 // simply skip using the capture result metadata to override EXIF.
1750 Mutex::Autolock l(mMutex);
1751
1752 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001753 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001754 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001755 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001756 break;
1757 }
1758 }
1759 if (timestamp == -1) {
1760 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001761 if (inputFrame.first == resultExtras.frameNumber) {
1762 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001763 break;
1764 }
1765 }
1766 }
1767
1768 if (timestamp == -1) {
1769 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1770 return;
1771 }
1772
1773 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001774 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1775 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001776 mInputReadyCondition.signal();
1777}
1778
Shuzhen Wange8675782019-12-05 09:12:14 -08001779void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1780 auto frameNumber = resultExtras.frameNumber;
1781 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1782 Mutex::Autolock l(mMutex);
1783 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1784 if (numRequests == 0) {
1785 // Pending request has been populated into mPendingInputFrames
1786 mErrorFrameNumbers.emplace(frameNumber);
1787 mInputReadyCondition.signal();
1788 } else {
1789 // REQUEST_ERROR was received without onShutter.
1790 }
1791}
1792
1793void HeicCompositeStream::markTrackerIdle() {
1794 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1795 if (statusTracker != nullptr) {
1796 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1797 ALOGV("%s: Mark component as idle", __FUNCTION__);
1798 }
1799}
1800
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001801void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1802 sp<HeicCompositeStream> parent = mParent.promote();
1803 if (parent == nullptr) return;
1804
1805 switch (msg->what()) {
1806 case kWhatCallbackNotify: {
1807 int32_t cbID;
1808 if (!msg->findInt32("callbackID", &cbID)) {
1809 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1810 break;
1811 }
1812
1813 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1814
1815 switch (cbID) {
1816 case MediaCodec::CB_INPUT_AVAILABLE: {
1817 int32_t index;
1818 if (!msg->findInt32("index", &index)) {
1819 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1820 break;
1821 }
1822 parent->onHeicInputFrameAvailable(index);
1823 break;
1824 }
1825
1826 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1827 int32_t index;
1828 size_t offset;
1829 size_t size;
1830 int64_t timeUs;
1831 int32_t flags;
1832
1833 if (!msg->findInt32("index", &index)) {
1834 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1835 break;
1836 }
1837 if (!msg->findSize("offset", &offset)) {
1838 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1839 break;
1840 }
1841 if (!msg->findSize("size", &size)) {
1842 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1843 break;
1844 }
1845 if (!msg->findInt64("timeUs", &timeUs)) {
1846 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1847 break;
1848 }
1849 if (!msg->findInt32("flags", &flags)) {
1850 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1851 break;
1852 }
1853
1854 CodecOutputBufferInfo bufferInfo = {
1855 index,
1856 (int32_t)offset,
1857 (int32_t)size,
1858 timeUs,
1859 (uint32_t)flags};
1860
1861 parent->onHeicOutputFrameAvailable(bufferInfo);
1862 break;
1863 }
1864
1865 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1866 sp<AMessage> format;
1867 if (!msg->findMessage("format", &format)) {
1868 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1869 break;
1870 }
Chong Zhang860eff12019-09-16 16:15:00 -07001871 // Here format is MediaCodec's internal copy of output format.
1872 // Make a copy since onHeicFormatChanged() might modify it.
1873 sp<AMessage> formatCopy;
1874 if (format != nullptr) {
1875 formatCopy = format->dup();
1876 }
1877 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001878 break;
1879 }
1880
1881 case MediaCodec::CB_ERROR: {
1882 status_t err;
1883 int32_t actionCode;
1884 AString detail;
1885 if (!msg->findInt32("err", &err)) {
1886 ALOGE("CB_ERROR: err is expected.");
1887 break;
1888 }
1889 if (!msg->findInt32("action", &actionCode)) {
1890 ALOGE("CB_ERROR: action is expected.");
1891 break;
1892 }
1893 msg->findString("detail", &detail);
1894 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1895 err, actionCode, detail.c_str());
1896
1897 parent->onHeicCodecError();
1898 break;
1899 }
1900
1901 default: {
1902 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1903 break;
1904 }
1905 }
1906 break;
1907 }
1908
1909 default:
1910 ALOGE("shouldn't be here");
1911 break;
1912 }
1913}
1914
1915}; // namespace camera3
1916}; // namespace android