blob: 60584295b3125dc5d809ae123f25e2f8ca84c377 [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);
444 }
445 }
446 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
447
448 int32_t gridRows, gridCols;
449 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
450 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
451 mNumOutputTiles = gridRows * gridCols;
452 } else {
453 mNumOutputTiles = 1;
454 }
455
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800456 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700457
458 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
459 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800460}
461
462void HeicCompositeStream::onHeicCodecError() {
463 Mutex::Autolock l(mMutex);
464 mErrorState = true;
465}
466
467status_t HeicCompositeStream::configureStream() {
468 if (isRunning()) {
469 // Processing thread is already running, nothing more to do.
470 return NO_ERROR;
471 }
472
473 if (mOutputSurface.get() == nullptr) {
474 ALOGE("%s: No valid output surface set!", __FUNCTION__);
475 return NO_INIT;
476 }
477
478 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
479 if (res != OK) {
480 ALOGE("%s: Unable to connect to native window for stream %d",
481 __FUNCTION__, mMainImageStreamId);
482 return res;
483 }
484
485 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
486 != OK) {
487 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
488 mMainImageStreamId);
489 return res;
490 }
491
492 ANativeWindow *anwConsumer = mOutputSurface.get();
493 int maxConsumerBuffers;
494 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
495 &maxConsumerBuffers)) != OK) {
496 ALOGE("%s: Unable to query consumer undequeued"
497 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
498 return res;
499 }
500
501 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
502 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800503 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700504 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800505 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
506 return res;
507 }
508
509 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
510 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
511 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
512 return res;
513 }
514
Shuzhen Wange8675782019-12-05 09:12:14 -0800515 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
516 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700517 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
518 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800519 }
520
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800521 run("HeicCompositeStreamProc");
522
523 return NO_ERROR;
524}
525
526status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
527 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
528 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800529 outputStreamIds->push_back(mAppSegmentStreamId);
530 }
531 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
532
533 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800534 outputStreamIds->push_back(mMainImageStreamId);
535 }
536 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
537
538 if (currentStreamId != nullptr) {
539 *currentStreamId = mMainImageStreamId;
540 }
541
542 return NO_ERROR;
543}
544
Emilian Peev4697b642019-11-19 17:11:14 -0800545status_t HeicCompositeStream::insertCompositeStreamIds(
546 std::vector<int32_t>* compositeStreamIds /*out*/) {
547 if (compositeStreamIds == nullptr) {
548 return BAD_VALUE;
549 }
550
551 compositeStreamIds->push_back(mAppSegmentStreamId);
552 compositeStreamIds->push_back(mMainImageStreamId);
553
554 return OK;
555}
556
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800557void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
558 Mutex::Autolock l(mMutex);
559 if (mErrorState) {
560 return;
561 }
562
563 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800564 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
565 resultExtras.frameNumber, timestamp, resultExtras.requestId);
566 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
567 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
568 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800569 mInputReadyCondition.signal();
570 }
571}
572
573void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800574 auto i = mSettingsByFrameNumber.begin();
575 while (i != mSettingsByFrameNumber.end()) {
576 if (i->second.shutterNotified) {
577 mPendingInputFrames[i->first].orientation = i->second.orientation;
578 mPendingInputFrames[i->first].quality = i->second.quality;
579 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
580 mPendingInputFrames[i->first].requestId = i->second.requestId;
581 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
582 i->first, i->second.timestamp);
583 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700584
Shuzhen Wange8675782019-12-05 09:12:14 -0800585 // Set encoder quality if no inflight encoding
586 if (mPendingInputFrames.size() == 1) {
587 sp<StatusTracker> statusTracker = mStatusTracker.promote();
588 if (statusTracker != nullptr) {
589 statusTracker->markComponentActive(mStatusId);
590 ALOGV("%s: Mark component as active", __FUNCTION__);
591 }
592
593 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
594 updateCodecQualityLocked(newQuality);
595 }
596 } else {
597 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700598 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800599 }
600
Shuzhen Wange8675782019-12-05 09:12:14 -0800601 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800602 CpuConsumer::LockedBuffer imgBuffer;
603 auto it = mInputAppSegmentBuffers.begin();
604 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
605 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700606 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800607 break;
608 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
609 if (res != OK) {
610 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
611 strerror(-res), res);
612 } else {
613 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
614 " received buffer with time stamp: %" PRId64, __FUNCTION__,
615 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700616 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800617 }
618 mPendingInputFrames[*it].error = true;
619 mInputAppSegmentBuffers.erase(it);
620 continue;
621 }
622
Shuzhen Wange8675782019-12-05 09:12:14 -0800623 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
624 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
625 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700626 mInputAppSegmentBuffers.erase(it);
627 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800628 continue;
629 }
630
631 int64_t frameNumber = mAppSegmentFrameNumbers.front();
632 // If mPendingInputFrames doesn't contain the expected frame number, the captured
633 // input app segment frame must have been dropped via a buffer error. Simply
634 // return the buffer to the buffer queue.
635 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
636 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800637 mAppSegmentConsumer->unlockBuffer(imgBuffer);
638 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800639 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800640 }
641 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800642 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800643 }
644
Shuzhen Wange8675782019-12-05 09:12:14 -0800645 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800646 CpuConsumer::LockedBuffer imgBuffer;
647 auto it = mInputYuvBuffers.begin();
648 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
649 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700650 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800651 break;
652 } else if (res != OK) {
653 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
654 strerror(-res), res);
655 mPendingInputFrames[*it].error = true;
656 mInputYuvBuffers.erase(it);
657 continue;
658 } else if (*it != imgBuffer.timestamp) {
659 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
660 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
661 mPendingInputFrames[*it].error = true;
662 mInputYuvBuffers.erase(it);
663 continue;
664 }
665
Shuzhen Wange8675782019-12-05 09:12:14 -0800666 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
667 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
668 mMainImageFrameNumbers.front());
669 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700670 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800671 continue;
672 }
673
674 int64_t frameNumber = mMainImageFrameNumbers.front();
675 // If mPendingInputFrames doesn't contain the expected frame number, the captured
676 // input main image must have been dropped via a buffer error. Simply
677 // return the buffer to the buffer queue.
678 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
679 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800680 mMainImageConsumer->unlockBuffer(imgBuffer);
681 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800682 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800683 mYuvBufferAcquired = true;
684 }
685 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800686 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800687 }
688
689 while (!mCodecOutputBuffers.empty()) {
690 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800691 // Assume encoder input to output is FIFO, use a queue to look up
692 // frameNumber when handling codec outputs.
693 int64_t bufferFrameNumber = -1;
694 if (mCodecOutputBufferFrameNumbers.empty()) {
695 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700696 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800697 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800698 // Direct mapping between camera frame number and codec timestamp (in us).
699 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700700 mCodecOutputCounter++;
701 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800702 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700703 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800704 }
705
Shuzhen Wange8675782019-12-05 09:12:14 -0800706 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
707 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
708 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800709 }
710 mCodecOutputBuffers.erase(it);
711 }
712
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800713 while (!mCaptureResults.empty()) {
714 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800715 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800716 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800717 int64_t frameNumber = std::get<0>(it->second);
718 if (it->first >= 0 &&
719 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
720 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
721 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800722 std::make_unique<CameraMetadata>(std::get<1>(it->second));
723 } else {
724 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800725 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
726 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
727 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800728 }
729 }
730 mCaptureResults.erase(it);
731 }
732
733 // mErrorFrameNumbers stores frame number of dropped buffers.
734 auto it = mErrorFrameNumbers.begin();
735 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800736 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
737 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800738 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800739 //Error callback is guaranteed to arrive after shutter notify, which
740 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800741 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
742 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800743 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800744 it = mErrorFrameNumbers.erase(it);
745 }
746
747 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
748 it = mExifErrorFrameNumbers.begin();
749 while (it != mExifErrorFrameNumbers.end()) {
750 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
751 mPendingInputFrames[*it].exifError = true;
752 }
753 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800754 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800755
756 // Distribute codec input buffers to be filled out from YUV output
757 for (auto it = mPendingInputFrames.begin();
758 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
759 InputFrame& inputFrame(it->second);
760 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
761 // Available input tiles that are required for the current input
762 // image.
763 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
764 mGridRows * mGridCols - inputFrame.codecInputCounter);
765 for (size_t i = 0; i < newInputTiles; i++) {
766 CodecInputBufferInfo inputInfo =
767 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
768 inputFrame.codecInputBuffers.push_back(inputInfo);
769
770 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
771 inputFrame.codecInputCounter++;
772 }
773 break;
774 }
775 }
776}
777
Shuzhen Wange8675782019-12-05 09:12:14 -0800778bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
779 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800780 return false;
781 }
782
783 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700784 for (auto& it : mPendingInputFrames) {
785 // New input is considered to be available only if:
786 // 1. input buffers are ready, or
787 // 2. App segment and muxer is created, or
788 // 3. A codec output tile is ready, and an output buffer is available.
789 // This makes sure that muxer gets created only when an output tile is
790 // generated, because right now we only handle 1 HEIC output buffer at a
791 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800792 bool appSegmentReady =
793 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700794 !it.second.appSegmentWritten && it.second.result != nullptr &&
795 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800796 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
797 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
798 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700799 bool hasOutputBuffer = it.second.muxer != nullptr ||
800 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800801 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700802 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800803 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700804 if (it.second.format == nullptr && mFormat != nullptr) {
805 it.second.format = mFormat->dup();
806 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800807 newInputAvailable = true;
808 break;
809 }
810 }
811
812 return newInputAvailable;
813}
814
Shuzhen Wange8675782019-12-05 09:12:14 -0800815int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800816 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800817
818 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800819 if (it.second.error) {
820 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800821 break;
822 }
823 }
824
825 return res;
826}
827
Shuzhen Wange8675782019-12-05 09:12:14 -0800828status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800829 InputFrame &inputFrame) {
830 ATRACE_CALL();
831 status_t res = OK;
832
Shuzhen Wange8675782019-12-05 09:12:14 -0800833 bool appSegmentReady =
834 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700835 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
836 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800837 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
838 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700839 !inputFrame.codecInputBuffers.empty();
840 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
841 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800842
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700843 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800844 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
845 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
846 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800847
848 // Handle inputs for Hevc tiling
849 if (codecInputReady) {
850 res = processCodecInputFrame(inputFrame);
851 if (res != OK) {
852 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
853 strerror(-res), res);
854 return res;
855 }
856 }
857
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700858 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
859 return OK;
860 }
861
862 // Initialize and start muxer if not yet done so. In this case,
863 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
864 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800865 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800866 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800867 if (res != OK) {
868 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
869 strerror(-res), res);
870 return res;
871 }
872 }
873
874 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700875 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800876 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800877 if (res != OK) {
878 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
879 strerror(-res), res);
880 return res;
881 }
882 }
883
884 // Write media codec bitstream buffers to muxer.
885 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800886 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800887 if (res != OK) {
888 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
889 strerror(-res), res);
890 return res;
891 }
892 }
893
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700894 if (inputFrame.pendingOutputTiles == 0) {
895 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800896 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700897 if (res != OK) {
898 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
899 strerror(-res), res);
900 return res;
901 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800902 }
903 }
904
905 return res;
906}
907
Shuzhen Wange8675782019-12-05 09:12:14 -0800908status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800909 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800910
911 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
912 if (res != OK) {
913 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
914 res);
915 return res;
916 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700917 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800918
919 // Combine current thread id, stream id and timestamp to uniquely identify image.
920 std::ostringstream tempOutputFile;
921 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800922 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800923 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
924 if (inputFrame.fileFd < 0) {
925 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
926 tempOutputFile.str().c_str(), errno);
927 return NO_INIT;
928 }
929 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
930 if (inputFrame.muxer == nullptr) {
931 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
932 __FUNCTION__, inputFrame.fileFd);
933 return NO_INIT;
934 }
935
936 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
937 if (res != OK) {
938 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
939 strerror(-res), res);
940 return res;
941 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800942
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700943 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800944 if (trackId < 0) {
945 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
946 return NO_INIT;
947 }
948
949 inputFrame.trackIndex = trackId;
950 inputFrame.pendingOutputTiles = mNumOutputTiles;
951
952 res = inputFrame.muxer->start();
953 if (res != OK) {
954 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
955 __FUNCTION__, strerror(-res), res);
956 return res;
957 }
958
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700959 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800960 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800961 return OK;
962}
963
Shuzhen Wange8675782019-12-05 09:12:14 -0800964status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800965 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800966 size_t appSegmentSize = 0;
967 if (!inputFrame.exifError) {
968 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
969 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
970 &app1Size);
971 if (appSegmentSize == 0) {
972 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
973 return NO_INIT;
974 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800975 }
976
977 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800978 auto exifRes = inputFrame.exifError ?
979 exifUtils->initializeEmpty() :
980 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800981 if (!exifRes) {
982 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
983 return BAD_VALUE;
984 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800985 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
986 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800987 if (!exifRes) {
988 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
989 return BAD_VALUE;
990 }
991 exifRes = exifUtils->setOrientation(inputFrame.orientation);
992 if (!exifRes) {
993 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
994 return BAD_VALUE;
995 }
996 exifRes = exifUtils->generateApp1();
997 if (!exifRes) {
998 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
999 return BAD_VALUE;
1000 }
1001
1002 unsigned int newApp1Length = exifUtils->getApp1Length();
1003 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1004
1005 //Assemble the APP1 marker buffer required by MediaCodec
1006 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1007 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1008 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1009 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1010 appSegmentSize - app1Size + newApp1Length;
1011 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1012 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1013 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1014 if (appSegmentSize - app1Size > 0) {
1015 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1016 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1017 }
1018
1019 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1020 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001021 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001022 delete[] appSegmentBuffer;
1023
1024 if (res != OK) {
1025 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1026 __FUNCTION__, strerror(-res), res);
1027 return res;
1028 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001029
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001030 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001031 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001032 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001033
1034 inputFrame.appSegmentWritten = true;
1035 // Release the buffer now so any pending input app segments can be processed
1036 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1037 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001038 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001039
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001040 return OK;
1041}
1042
1043status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1044 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1045 sp<MediaCodecBuffer> buffer;
1046 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1047 if (res != OK) {
1048 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1049 strerror(-res), res);
1050 return res;
1051 }
1052
1053 // Copy one tile from source to destination.
1054 size_t tileX = inputBuffer.tileIndex % mGridCols;
1055 size_t tileY = inputBuffer.tileIndex / mGridCols;
1056 size_t top = mGridHeight * tileY;
1057 size_t left = mGridWidth * tileX;
1058 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1059 mOutputWidth - tileX * mGridWidth : mGridWidth;
1060 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1061 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001062 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1063 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1064 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001065
1066 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1067 if (res != OK) {
1068 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1069 strerror(-res), res);
1070 return res;
1071 }
1072
1073 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1074 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1075 if (res != OK) {
1076 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1077 __FUNCTION__, strerror(-res), res);
1078 return res;
1079 }
1080 }
1081
1082 inputFrame.codecInputBuffers.clear();
1083 return OK;
1084}
1085
Shuzhen Wange8675782019-12-05 09:12:14 -08001086status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001087 InputFrame &inputFrame) {
1088 auto it = inputFrame.codecOutputBuffers.begin();
1089 sp<MediaCodecBuffer> buffer;
1090 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1091 if (res != OK) {
1092 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1093 __FUNCTION__, it->index, strerror(-res), res);
1094 return res;
1095 }
1096 if (buffer == nullptr) {
1097 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1098 __FUNCTION__, it->index);
1099 return BAD_VALUE;
1100 }
1101
1102 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1103 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001104 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001105 if (res != OK) {
1106 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1107 __FUNCTION__, it->index, strerror(-res), res);
1108 return res;
1109 }
1110
1111 mCodec->releaseOutputBuffer(it->index);
1112 if (inputFrame.pendingOutputTiles == 0) {
1113 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1114 } else {
1115 inputFrame.pendingOutputTiles--;
1116 }
1117
1118 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001119
1120 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001121 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001122 return OK;
1123}
1124
Shuzhen Wange8675782019-12-05 09:12:14 -08001125status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001126 InputFrame &inputFrame) {
1127 sp<ANativeWindow> outputANW = mOutputSurface;
1128 inputFrame.muxer->stop();
1129
1130 // Copy the content of the file to memory.
1131 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1132 void* dstBuffer;
Shuzhen Wangc87315d2022-03-17 00:11:20 +00001133 GraphicBufferLocker gbLocker(gb);
1134 auto res = gbLocker.lockAsync(&dstBuffer, inputFrame.fenceFd);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001135 if (res != OK) {
1136 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1137 strerror(-res), res);
1138 return res;
1139 }
1140
1141 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1142 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1143 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1144 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1145 return BAD_VALUE;
1146 }
1147
1148 lseek(inputFrame.fileFd, 0, SEEK_SET);
1149 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1150 if (bytesRead < fSize) {
1151 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1152 return BAD_VALUE;
1153 }
1154
1155 close(inputFrame.fileFd);
1156 inputFrame.fileFd = -1;
1157
1158 // Fill in HEIC header
1159 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1160 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
1161 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
1162 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
1163 blobHeader->blobSize = fSize;
1164
Shuzhen Wange8675782019-12-05 09:12:14 -08001165 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001166 if (res != OK) {
1167 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1168 __FUNCTION__, getStreamId(), strerror(-res), res);
1169 return res;
1170 }
1171
1172 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1173 if (res != OK) {
1174 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1175 strerror(-res), res);
1176 return res;
1177 }
1178 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001179 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001180
Shuzhen Wange8675782019-12-05 09:12:14 -08001181 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1182 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001183 return OK;
1184}
1185
1186
Shuzhen Wange8675782019-12-05 09:12:14 -08001187void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1188 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001189 if (inputFrame == nullptr) {
1190 return;
1191 }
1192
1193 if (inputFrame->appSegmentBuffer.data != nullptr) {
1194 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1195 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001196 }
1197
1198 while (!inputFrame->codecOutputBuffers.empty()) {
1199 auto it = inputFrame->codecOutputBuffers.begin();
1200 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1201 mCodec->releaseOutputBuffer(it->index);
1202 inputFrame->codecOutputBuffers.erase(it);
1203 }
1204
1205 if (inputFrame->yuvBuffer.data != nullptr) {
1206 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1207 inputFrame->yuvBuffer.data = nullptr;
1208 mYuvBufferAcquired = false;
1209 }
1210
1211 while (!inputFrame->codecInputBuffers.empty()) {
1212 auto it = inputFrame->codecInputBuffers.begin();
1213 inputFrame->codecInputBuffers.erase(it);
1214 }
1215
Shuzhen Wange8675782019-12-05 09:12:14 -08001216 if (inputFrame->error || mErrorState) {
1217 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1218 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001219 }
1220
1221 if (inputFrame->fileFd >= 0) {
1222 close(inputFrame->fileFd);
1223 inputFrame->fileFd = -1;
1224 }
1225
1226 if (inputFrame->anb != nullptr) {
1227 sp<ANativeWindow> outputANW = mOutputSurface;
1228 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1229 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001230
1231 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001232 }
1233}
1234
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001235void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001236 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001237 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001238 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001239 auto& inputFrame = it->second;
1240 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001241 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1242 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001243 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001244 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001245 } else {
1246 it++;
1247 }
1248 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001249
1250 // Update codec quality based on first upcoming input frame.
1251 // Note that when encoding is in surface mode, currently there is no
1252 // way for camera service to synchronize quality setting on a per-frame
1253 // basis: we don't get notification when codec is ready to consume a new
1254 // input frame. So we update codec quality on a best-effort basis.
1255 if (inputFrameDone) {
1256 auto firstPendingFrame = mPendingInputFrames.begin();
1257 if (firstPendingFrame != mPendingInputFrames.end()) {
1258 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001259 } else {
1260 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001261 }
1262 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001263}
1264
1265status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1266 const sp<CameraDeviceBase>& cameraDevice) {
1267 ALOGV("%s", __FUNCTION__);
1268
1269 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001270 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001271 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001272 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001273 if (!isSizeSupported) {
1274 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1275 __FUNCTION__, width, height);
1276 return BAD_VALUE;
1277 }
1278
1279 // Create Looper for MediaCodec.
1280 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1281 mCodecLooper = new ALooper;
1282 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1283 status_t res = mCodecLooper->start(
1284 false, // runOnCallingThread
1285 false, // canCallJava
1286 PRIORITY_AUDIO);
1287 if (res != OK) {
1288 ALOGE("%s: Failed to start codec looper: %s (%d)",
1289 __FUNCTION__, strerror(-res), res);
1290 return NO_INIT;
1291 }
1292
1293 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001294 if (mUseHeic) {
1295 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1296 } else {
1297 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1298 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001299 if (mCodec == nullptr) {
1300 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1301 return NO_INIT;
1302 }
1303
1304 // Create Looper and handler for Codec callback.
1305 mCodecCallbackHandler = new CodecCallbackHandler(this);
1306 if (mCodecCallbackHandler == nullptr) {
1307 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1308 return NO_MEMORY;
1309 }
1310 mCallbackLooper = new ALooper;
1311 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1312 res = mCallbackLooper->start(
1313 false, // runOnCallingThread
1314 false, // canCallJava
1315 PRIORITY_AUDIO);
1316 if (res != OK) {
1317 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1318 __FUNCTION__, strerror(-res), res);
1319 return NO_INIT;
1320 }
1321 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1322
1323 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1324 res = mCodec->setCallback(mAsyncNotify);
1325 if (res != OK) {
1326 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1327 strerror(-res), res);
1328 return res;
1329 }
1330
1331 // Create output format and configure the Codec.
1332 sp<AMessage> outputFormat = new AMessage();
1333 outputFormat->setString(KEY_MIME, desiredMime);
1334 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1335 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1336 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001337 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001338
1339 int32_t gridWidth, gridHeight, gridRows, gridCols;
1340 if (useGrid || mUseHeic) {
1341 gridWidth = HeicEncoderInfoManager::kGridWidth;
1342 gridHeight = HeicEncoderInfoManager::kGridHeight;
1343 gridRows = (height + gridHeight - 1)/gridHeight;
1344 gridCols = (width + gridWidth - 1)/gridWidth;
1345
1346 if (mUseHeic) {
1347 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1348 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1349 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1350 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1351 }
1352
1353 } else {
1354 gridWidth = width;
1355 gridHeight = height;
1356 gridRows = 1;
1357 gridCols = 1;
1358 }
1359
1360 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1361 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1362 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1363 outputFormat->setInt32(KEY_COLOR_FORMAT,
1364 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001365 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001366 // This only serves as a hint to encoder when encoding is not real-time.
1367 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1368
1369 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1370 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1371 if (res != OK) {
1372 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1373 strerror(-res), res);
1374 return res;
1375 }
1376
1377 mGridWidth = gridWidth;
1378 mGridHeight = gridHeight;
1379 mGridRows = gridRows;
1380 mGridCols = gridCols;
1381 mUseGrid = useGrid;
1382 mOutputWidth = width;
1383 mOutputHeight = height;
1384 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
Susmitha Gummallae911f2e2020-11-23 09:57:03 -08001385 mMaxHeicBufferSize =
1386 ALIGN(mOutputWidth, HeicEncoderInfoManager::kGridWidth) *
1387 ALIGN(mOutputHeight, HeicEncoderInfoManager::kGridHeight) * 3 / 2 + mAppSegmentMaxSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001388
1389 return OK;
1390}
1391
1392void HeicCompositeStream::deinitCodec() {
1393 ALOGV("%s", __FUNCTION__);
1394 if (mCodec != nullptr) {
1395 mCodec->stop();
1396 mCodec->release();
1397 mCodec.clear();
1398 }
1399
1400 if (mCodecLooper != nullptr) {
1401 mCodecLooper->stop();
1402 mCodecLooper.clear();
1403 }
1404
1405 if (mCallbackLooper != nullptr) {
1406 mCallbackLooper->stop();
1407 mCallbackLooper.clear();
1408 }
1409
1410 mAsyncNotify.clear();
1411 mFormat.clear();
1412}
1413
1414// Return the size of the complete list of app segment, 0 indicates failure
1415size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1416 size_t maxSize, size_t *app1SegmentSize) {
1417 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1418 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1419 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1420 return 0;
1421 }
1422
1423 size_t expectedSize = 0;
1424 // First check for EXIF transport header at the end of the buffer
1425 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1426 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1427 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1428 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1429 return 0;
1430 }
1431
1432 expectedSize = blob->blobSize;
1433 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1434 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1435 return 0;
1436 }
1437
1438 uint32_t totalSize = 0;
1439
1440 // Verify APP1 marker (mandatory)
1441 uint8_t app1Marker[] = {0xFF, 0xE1};
1442 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1443 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1444 appSegmentBuffer[0], appSegmentBuffer[1]);
1445 return 0;
1446 }
1447 totalSize += sizeof(app1Marker);
1448
1449 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1450 appSegmentBuffer[totalSize+1];
1451 totalSize += app1Size;
1452
1453 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1454 __FUNCTION__, expectedSize, app1Size);
1455 while (totalSize < expectedSize) {
1456 if (appSegmentBuffer[totalSize] != 0xFF ||
1457 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1458 appSegmentBuffer[totalSize+1] > 0xEF) {
1459 // Invalid APPn marker
1460 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1461 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1462 return 0;
1463 }
1464 totalSize += 2;
1465
1466 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1467 appSegmentBuffer[totalSize+1];
1468 totalSize += appnSize;
1469 }
1470
1471 if (totalSize != expectedSize) {
1472 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1473 __FUNCTION__, totalSize, expectedSize);
1474 return 0;
1475 }
1476
1477 *app1SegmentSize = app1Size + sizeof(app1Marker);
1478 return expectedSize;
1479}
1480
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001481status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1482 const CpuConsumer::LockedBuffer& yuvBuffer,
1483 size_t top, size_t left, size_t width, size_t height) {
1484 ATRACE_CALL();
1485
1486 // Get stride information for codecBuffer
1487 sp<ABuffer> imageData;
1488 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1489 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1490 return BAD_VALUE;
1491 }
1492 if (imageData->size() != sizeof(MediaImage2)) {
1493 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1494 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1495 return BAD_VALUE;
1496 }
1497 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1498 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1499 imageInfo->mBitDepth != 8 ||
1500 imageInfo->mBitDepthAllocated != 8 ||
1501 imageInfo->mNumPlanes != 3) {
1502 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1503 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1504 imageInfo->mType, imageInfo->mBitDepth,
1505 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1506 return BAD_VALUE;
1507 }
1508
1509 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1510 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1511 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1512 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1513 imageInfo->mPlane[MediaImage2::V].mOffset,
1514 imageInfo->mPlane[MediaImage2::U].mRowInc,
1515 imageInfo->mPlane[MediaImage2::V].mRowInc,
1516 imageInfo->mPlane[MediaImage2::U].mColInc,
1517 imageInfo->mPlane[MediaImage2::V].mColInc);
1518
1519 // Y
1520 for (auto row = top; row < top+height; row++) {
1521 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1522 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001523 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001524 }
1525
1526 // U is Cb, V is Cr
1527 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1528 imageInfo->mPlane[MediaImage2::U].mOffset;
1529 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1530 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1531 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1532 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1533 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1534 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1535 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1536 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1537 bool isCodecUvPlannar =
1538 ((codecUPlaneFirst && codecUvOffsetDiff >=
1539 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1540 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1541 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1542 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1543 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1544 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1545
1546 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1547 (codecUPlaneFirst == cameraUPlaneFirst)) {
1548 // UV semiplannar
1549 // The chrome plane could be either Cb first, or Cr first. Take the
1550 // smaller address.
1551 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1552 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1553 for (auto row = top/2; row < (top+height)/2; row++) {
1554 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1555 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001556 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001557 }
1558 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1559 // U plane
1560 for (auto row = top/2; row < (top+height)/2; row++) {
1561 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1562 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001563 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001564 }
1565
1566 // V plane
1567 for (auto row = top/2; row < (top+height)/2; row++) {
1568 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1569 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001570 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001571 }
1572 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001573 // Convert between semiplannar and plannar, or when UV orders are
1574 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001575 uint8_t *dst = codecBuffer->data();
1576 for (auto row = top/2; row < (top+height)/2; row++) {
1577 for (auto col = left/2; col < (left+width)/2; col++) {
1578 // U/Cb
1579 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1580 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1581 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1582 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1583 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1584
1585 // V/Cr
1586 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1587 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1588 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1589 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1590 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1591 }
1592 }
1593 }
1594 return OK;
1595}
1596
Shuzhen Wang219c2992019-02-15 17:24:28 -08001597void HeicCompositeStream::initCopyRowFunction(int32_t width)
1598{
1599 using namespace libyuv;
1600
1601 mFnCopyRow = CopyRow_C;
1602#if defined(HAS_COPYROW_SSE2)
1603 if (TestCpuFlag(kCpuHasSSE2)) {
1604 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1605 }
1606#endif
1607#if defined(HAS_COPYROW_AVX)
1608 if (TestCpuFlag(kCpuHasAVX)) {
1609 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1610 }
1611#endif
1612#if defined(HAS_COPYROW_ERMS)
1613 if (TestCpuFlag(kCpuHasERMS)) {
1614 mFnCopyRow = CopyRow_ERMS;
1615 }
1616#endif
1617#if defined(HAS_COPYROW_NEON)
1618 if (TestCpuFlag(kCpuHasNEON)) {
1619 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1620 }
1621#endif
1622#if defined(HAS_COPYROW_MIPS)
1623 if (TestCpuFlag(kCpuHasMIPS)) {
1624 mFnCopyRow = CopyRow_MIPS;
1625 }
1626#endif
1627}
1628
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001629size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1630 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1631 size_t maxAppsSegment = 1;
1632 if (entry.count > 0) {
1633 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1634 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1635 }
1636 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1637}
1638
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001639void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1640 if (quality != mQuality) {
1641 sp<AMessage> qualityParams = new AMessage;
1642 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1643 status_t res = mCodec->setParameters(qualityParams);
1644 if (res != OK) {
1645 ALOGE("%s: Failed to set codec quality: %s (%d)",
1646 __FUNCTION__, strerror(-res), res);
1647 } else {
1648 mQuality = quality;
1649 }
1650 }
1651}
1652
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001653bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001654 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001655 bool newInputAvailable = false;
1656
1657 {
1658 Mutex::Autolock l(mMutex);
1659 if (mErrorState) {
1660 // In case we landed in error state, return any pending buffers and
1661 // halt all further processing.
1662 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001663 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001664 return false;
1665 }
1666
1667
1668 while (!newInputAvailable) {
1669 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001670 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001671
1672 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001673 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001674 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001675 releaseInputFrameLocked(failingFrameNumber,
1676 &mPendingInputFrames[failingFrameNumber]);
1677
1678 // It's okay to remove the entry from mPendingInputFrames
1679 // because:
1680 // 1. Only one internal stream (main input) is critical in
1681 // backing the output stream.
1682 // 2. If captureResult/appSegment arrives after the entry is
1683 // removed, they are simply skipped.
1684 mPendingInputFrames.erase(failingFrameNumber);
1685 if (mPendingInputFrames.size() == 0) {
1686 markTrackerIdle();
1687 }
1688 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001689 }
1690
1691 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1692 if (ret == TIMED_OUT) {
1693 return true;
1694 } else if (ret != OK) {
1695 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1696 strerror(-ret), ret);
1697 return false;
1698 }
1699 }
1700 }
1701 }
1702
Shuzhen Wange8675782019-12-05 09:12:14 -08001703 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001704 Mutex::Autolock l(mMutex);
1705 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001706 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1707 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1708 frameNumber, strerror(-res), res);
1709 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001710 }
1711
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001712 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001713
1714 return true;
1715}
1716
Shuzhen Wange8675782019-12-05 09:12:14 -08001717void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1718 Mutex::Autolock l(mMutex);
1719 mExifErrorFrameNumbers.emplace(frameNumber);
1720 mInputReadyCondition.signal();
1721}
1722
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001723bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1724 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001725 int64_t frameNumber = resultExtras.frameNumber;
1726
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001727 // Buffer errors concerning internal composite streams should not be directly visible to
1728 // camera clients. They must only receive a single buffer error with the public composite
1729 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001730 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1731 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1732 flagAnExifErrorFrameNumber(frameNumber);
1733 res = true;
1734 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1735 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1736 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001737 res = true;
1738 }
1739
1740 return res;
1741}
1742
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001743void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1744 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1745 // simply skip using the capture result metadata to override EXIF.
1746 Mutex::Autolock l(mMutex);
1747
1748 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001749 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001750 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001751 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001752 break;
1753 }
1754 }
1755 if (timestamp == -1) {
1756 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001757 if (inputFrame.first == resultExtras.frameNumber) {
1758 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001759 break;
1760 }
1761 }
1762 }
1763
1764 if (timestamp == -1) {
1765 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1766 return;
1767 }
1768
1769 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001770 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1771 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001772 mInputReadyCondition.signal();
1773}
1774
Shuzhen Wange8675782019-12-05 09:12:14 -08001775void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1776 auto frameNumber = resultExtras.frameNumber;
1777 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1778 Mutex::Autolock l(mMutex);
1779 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1780 if (numRequests == 0) {
1781 // Pending request has been populated into mPendingInputFrames
1782 mErrorFrameNumbers.emplace(frameNumber);
1783 mInputReadyCondition.signal();
1784 } else {
1785 // REQUEST_ERROR was received without onShutter.
1786 }
1787}
1788
1789void HeicCompositeStream::markTrackerIdle() {
1790 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1791 if (statusTracker != nullptr) {
1792 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1793 ALOGV("%s: Mark component as idle", __FUNCTION__);
1794 }
1795}
1796
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001797void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1798 sp<HeicCompositeStream> parent = mParent.promote();
1799 if (parent == nullptr) return;
1800
1801 switch (msg->what()) {
1802 case kWhatCallbackNotify: {
1803 int32_t cbID;
1804 if (!msg->findInt32("callbackID", &cbID)) {
1805 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1806 break;
1807 }
1808
1809 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1810
1811 switch (cbID) {
1812 case MediaCodec::CB_INPUT_AVAILABLE: {
1813 int32_t index;
1814 if (!msg->findInt32("index", &index)) {
1815 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1816 break;
1817 }
1818 parent->onHeicInputFrameAvailable(index);
1819 break;
1820 }
1821
1822 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1823 int32_t index;
1824 size_t offset;
1825 size_t size;
1826 int64_t timeUs;
1827 int32_t flags;
1828
1829 if (!msg->findInt32("index", &index)) {
1830 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1831 break;
1832 }
1833 if (!msg->findSize("offset", &offset)) {
1834 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1835 break;
1836 }
1837 if (!msg->findSize("size", &size)) {
1838 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1839 break;
1840 }
1841 if (!msg->findInt64("timeUs", &timeUs)) {
1842 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1843 break;
1844 }
1845 if (!msg->findInt32("flags", &flags)) {
1846 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1847 break;
1848 }
1849
1850 CodecOutputBufferInfo bufferInfo = {
1851 index,
1852 (int32_t)offset,
1853 (int32_t)size,
1854 timeUs,
1855 (uint32_t)flags};
1856
1857 parent->onHeicOutputFrameAvailable(bufferInfo);
1858 break;
1859 }
1860
1861 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1862 sp<AMessage> format;
1863 if (!msg->findMessage("format", &format)) {
1864 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1865 break;
1866 }
Chong Zhang860eff12019-09-16 16:15:00 -07001867 // Here format is MediaCodec's internal copy of output format.
1868 // Make a copy since onHeicFormatChanged() might modify it.
1869 sp<AMessage> formatCopy;
1870 if (format != nullptr) {
1871 formatCopy = format->dup();
1872 }
1873 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001874 break;
1875 }
1876
1877 case MediaCodec::CB_ERROR: {
1878 status_t err;
1879 int32_t actionCode;
1880 AString detail;
1881 if (!msg->findInt32("err", &err)) {
1882 ALOGE("CB_ERROR: err is expected.");
1883 break;
1884 }
1885 if (!msg->findInt32("action", &actionCode)) {
1886 ALOGE("CB_ERROR: action is expected.");
1887 break;
1888 }
1889 msg->findString("detail", &detail);
1890 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1891 err, actionCode, detail.c_str());
1892
1893 parent->onHeicCodecError();
1894 break;
1895 }
1896
1897 default: {
1898 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1899 break;
1900 }
1901 }
1902 break;
1903 }
1904
1905 default:
1906 ALOGE("shouldn't be here");
1907 break;
1908 }
1909}
1910
1911}; // namespace camera3
1912}; // namespace android