blob: 4fe5adfe16186e848948e3b932e5b7b34a302da8 [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
19//#define LOG_NDEBUG 0
20
21#include <linux/memfd.h>
22#include <pthread.h>
23#include <sys/syscall.h>
24
25#include <android/hardware/camera/device/3.5/types.h>
Shuzhen Wang219c2992019-02-15 17:24:28 -080026#include <libyuv.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080027#include <gui/Surface.h>
28#include <utils/Log.h>
29#include <utils/Trace.h>
30
Marco Nelissen13aa1a42019-09-27 10:21:55 -070031#include <mediadrm/ICrypto.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080032#include <media/MediaCodecBuffer.h>
33#include <media/stagefright/foundation/ABuffer.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080034#include <media/stagefright/foundation/MediaDefs.h>
35#include <media/stagefright/MediaCodecConstants.h>
36
37#include "common/CameraDeviceBase.h"
38#include "utils/ExifUtils.h"
39#include "HeicEncoderInfoManager.h"
40#include "HeicCompositeStream.h"
41
42using android::hardware::camera::device::V3_5::CameraBlob;
43using android::hardware::camera::device::V3_5::CameraBlobId;
44
45namespace android {
46namespace camera3 {
47
Shuzhen Wange8675782019-12-05 09:12:14 -080048HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080049 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
50 CompositeStream(device, cb),
51 mUseHeic(false),
52 mNumOutputTiles(1),
53 mOutputWidth(0),
54 mOutputHeight(0),
55 mMaxHeicBufferSize(0),
56 mGridWidth(HeicEncoderInfoManager::kGridWidth),
57 mGridHeight(HeicEncoderInfoManager::kGridHeight),
58 mGridRows(1),
59 mGridCols(1),
60 mUseGrid(false),
61 mAppSegmentStreamId(-1),
62 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080063 mMainImageStreamId(-1),
64 mMainImageSurfaceId(-1),
65 mYuvBufferAcquired(false),
66 mProducerListener(new ProducerListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070067 mDequeuedOutputBufferCnt(0),
Michael Gonzalezb5986a32019-10-09 15:38:17 -070068 mLockedAppSegmentBufferCnt(0),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070069 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070070 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080071 mGridTimestampUs(0),
72 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080073}
74
75HeicCompositeStream::~HeicCompositeStream() {
76 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
77 // memory/resource leak.
78 deinitCodec();
79
80 mInputAppSegmentBuffers.clear();
81 mCodecOutputBuffers.clear();
82
83 mAppSegmentStreamId = -1;
84 mAppSegmentSurfaceId = -1;
85 mAppSegmentConsumer.clear();
86 mAppSegmentSurface.clear();
87
88 mMainImageStreamId = -1;
89 mMainImageSurfaceId = -1;
90 mMainImageConsumer.clear();
91 mMainImageSurface.clear();
92}
93
94bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
95 ANativeWindow *anw = surface.get();
96 status_t err;
97 int format;
98 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
99 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
100 err);
101 ALOGE("%s: %s", __FUNCTION__, msg.string());
102 return false;
103 }
104
105 int dataspace;
106 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
107 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
108 err);
109 ALOGE("%s: %s", __FUNCTION__, msg.string());
110 return false;
111 }
112
113 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
114}
115
116status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
117 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
118 camera3_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
119 std::vector<int> *surfaceIds, int /*streamSetId*/, bool /*isShared*/) {
120
121 sp<CameraDeviceBase> device = mDevice.promote();
122 if (!device.get()) {
123 ALOGE("%s: Invalid camera device!", __FUNCTION__);
124 return NO_INIT;
125 }
126
127 status_t res = initializeCodec(width, height, device);
128 if (res != OK) {
129 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
130 __FUNCTION__, strerror(-res), res);
131 return NO_INIT;
132 }
133
134 sp<IGraphicBufferProducer> producer;
135 sp<IGraphicBufferConsumer> consumer;
136 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700137 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800138 mAppSegmentConsumer->setFrameAvailableListener(this);
139 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
140 mAppSegmentSurface = new Surface(producer);
141
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800142 mStaticInfo = device->info();
143
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800144 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
145 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId, surfaceIds);
146 if (res == OK) {
147 mAppSegmentSurfaceId = (*surfaceIds)[0];
148 } else {
149 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
150 strerror(-res), res);
151 return res;
152 }
153
154 if (!mUseGrid) {
155 res = mCodec->createInputSurface(&producer);
156 if (res != OK) {
157 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
158 __FUNCTION__, strerror(-res), res);
159 return res;
160 }
161 } else {
162 BufferQueue::createBufferQueue(&producer, &consumer);
163 mMainImageConsumer = new CpuConsumer(consumer, 1);
164 mMainImageConsumer->setFrameAvailableListener(this);
165 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
166 }
167 mMainImageSurface = new Surface(producer);
168
169 res = mCodec->start();
170 if (res != OK) {
171 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
172 strerror(-res), res);
173 return res;
174 }
175
176 std::vector<int> sourceSurfaceId;
177 //Use YUV_888 format if framework tiling is needed.
178 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
179 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
180 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
181 rotation, id, physicalCameraId, &sourceSurfaceId);
182 if (res == OK) {
183 mMainImageSurfaceId = sourceSurfaceId[0];
184 mMainImageStreamId = *id;
185 } else {
186 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
187 strerror(-res), res);
188 return res;
189 }
190
191 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800192 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800193 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800194 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
195 strerror(-res), res);
196 return res;
197 }
198
199 res = registerCompositeStreamListener(mAppSegmentStreamId);
200 if (res != OK) {
201 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
202 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800203 return res;
204 }
205
Shuzhen Wang219c2992019-02-15 17:24:28 -0800206 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800207 return res;
208}
209
210status_t HeicCompositeStream::deleteInternalStreams() {
211 requestExit();
212 auto res = join();
213 if (res != OK) {
214 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
215 strerror(-res), res);
216 }
217
218 deinitCodec();
219
220 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700221 // Camera devices may not be valid after switching to offline mode.
222 // In this case, all offline streams including internal composite streams
223 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800224 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700225 if (device.get() != nullptr) {
226 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800227 }
228
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800229 mAppSegmentStreamId = -1;
230 }
231
Shuzhen Wang2c545042019-02-07 10:27:35 -0800232 if (mOutputSurface != nullptr) {
233 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
234 mOutputSurface.clear();
235 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800236
237 sp<StatusTracker> statusTracker = mStatusTracker.promote();
238 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
239 statusTracker->removeComponent(mStatusId);
240 mStatusId = StatusTracker::NO_STATUS_ID;
241 }
242
243 if (mPendingInputFrames.size() > 0) {
244 ALOGW("%s: mPendingInputFrames has %zu stale entries",
245 __FUNCTION__, mPendingInputFrames.size());
246 mPendingInputFrames.clear();
247 }
248
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800249 return res;
250}
251
252void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
253 Mutex::Autolock l(mMutex);
254
255 if (bufferInfo.mError) return;
256
Shuzhen Wange8675782019-12-05 09:12:14 -0800257 if (bufferInfo.mStreamId == mMainImageStreamId) {
258 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
259 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
260 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
261 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
262 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
263 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
264 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
265 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
266 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800267}
268
269// We need to get the settings early to handle the case where the codec output
270// arrives earlier than result metadata.
271void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
272 const CameraMetadata& settings) {
273 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
274
275 Mutex::Autolock l(mMutex);
276 if (mErrorState || (streamId != getStreamId())) {
277 return;
278 }
279
280 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
281
282 camera_metadata_ro_entry entry;
283
284 int32_t orientation = 0;
285 entry = settings.find(ANDROID_JPEG_ORIENTATION);
286 if (entry.count == 1) {
287 orientation = entry.data.i32[0];
288 }
289
290 int32_t quality = kDefaultJpegQuality;
291 entry = settings.find(ANDROID_JPEG_QUALITY);
292 if (entry.count == 1) {
293 quality = entry.data.i32[0];
294 }
295
Shuzhen Wange8675782019-12-05 09:12:14 -0800296 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800297}
298
299void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
300 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
301 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
302 __func__, ns2ms(item.mTimestamp));
303
304 Mutex::Autolock l(mMutex);
305 if (!mErrorState) {
306 mInputAppSegmentBuffers.push_back(item.mTimestamp);
307 mInputReadyCondition.signal();
308 }
309 } else if (item.mDataSpace == kHeifDataSpace) {
310 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
311 __func__, ns2ms(item.mTimestamp));
312
313 Mutex::Autolock l(mMutex);
314 if (!mUseGrid) {
315 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
316 __FUNCTION__);
317 return;
318 }
319 if (!mErrorState) {
320 mInputYuvBuffers.push_back(item.mTimestamp);
321 mInputReadyCondition.signal();
322 }
323 } else {
324 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
325 }
326}
327
328status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
329 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
330 if (compositeOutput == nullptr) {
331 return BAD_VALUE;
332 }
333
334 compositeOutput->clear();
335
336 bool useGrid, useHeic;
337 bool isSizeSupported = isSizeSupportedByHeifEncoder(
338 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
339 if (!isSizeSupported) {
340 // Size is not supported by either encoder.
341 return OK;
342 }
343
344 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
345
346 // JPEG APPS segments Blob stream info
347 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
348 (*compositeOutput)[0].height = 1;
349 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
350 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
351 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
352
353 // YUV/IMPLEMENTATION_DEFINED stream info
354 (*compositeOutput)[1].width = streamInfo.width;
355 (*compositeOutput)[1].height = streamInfo.height;
356 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
357 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
358 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
359 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
360 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
361
362 return NO_ERROR;
363}
364
365bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700366 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800367 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700368 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800369}
370
371bool HeicCompositeStream::isInMemoryTempFileSupported() {
372 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
373 if (memfd == -1) {
374 if (errno != ENOSYS) {
375 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
376 }
377 return false;
378 }
379 close(memfd);
380 return true;
381}
382
383void HeicCompositeStream::onHeicOutputFrameAvailable(
384 const CodecOutputBufferInfo& outputBufferInfo) {
385 Mutex::Autolock l(mMutex);
386
387 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
388 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
389 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
390
391 if (!mErrorState) {
392 if ((outputBufferInfo.size > 0) &&
393 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
394 mCodecOutputBuffers.push_back(outputBufferInfo);
395 mInputReadyCondition.signal();
396 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700397 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
398 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800399 mCodec->releaseOutputBuffer(outputBufferInfo.index);
400 }
401 } else {
402 mCodec->releaseOutputBuffer(outputBufferInfo.index);
403 }
404}
405
406void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
407 Mutex::Autolock l(mMutex);
408
409 if (!mUseGrid) {
410 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
411 return;
412 }
413
414 mCodecInputBuffers.push_back(index);
415 mInputReadyCondition.signal();
416}
417
418void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
419 if (newFormat == nullptr) {
420 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
421 return;
422 }
423
424 Mutex::Autolock l(mMutex);
425
426 AString mime;
427 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
428 newFormat->findString(KEY_MIME, &mime);
429 if (mime != mimeHeic) {
430 // For HEVC codec, below keys need to be filled out or overwritten so that the
431 // muxer can handle them as HEIC output image.
432 newFormat->setString(KEY_MIME, mimeHeic);
433 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
434 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
435 if (mUseGrid) {
436 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
437 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
438 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
439 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
440 }
441 }
442 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
443
444 int32_t gridRows, gridCols;
445 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
446 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
447 mNumOutputTiles = gridRows * gridCols;
448 } else {
449 mNumOutputTiles = 1;
450 }
451
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800452 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700453
454 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
455 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800456}
457
458void HeicCompositeStream::onHeicCodecError() {
459 Mutex::Autolock l(mMutex);
460 mErrorState = true;
461}
462
463status_t HeicCompositeStream::configureStream() {
464 if (isRunning()) {
465 // Processing thread is already running, nothing more to do.
466 return NO_ERROR;
467 }
468
469 if (mOutputSurface.get() == nullptr) {
470 ALOGE("%s: No valid output surface set!", __FUNCTION__);
471 return NO_INIT;
472 }
473
474 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
475 if (res != OK) {
476 ALOGE("%s: Unable to connect to native window for stream %d",
477 __FUNCTION__, mMainImageStreamId);
478 return res;
479 }
480
481 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
482 != OK) {
483 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
484 mMainImageStreamId);
485 return res;
486 }
487
488 ANativeWindow *anwConsumer = mOutputSurface.get();
489 int maxConsumerBuffers;
490 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
491 &maxConsumerBuffers)) != OK) {
492 ALOGE("%s: Unable to query consumer undequeued"
493 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
494 return res;
495 }
496
497 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
498 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800499 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700500 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800501 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
502 return res;
503 }
504
505 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
506 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
507 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
508 return res;
509 }
510
Shuzhen Wange8675782019-12-05 09:12:14 -0800511 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
512 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700513 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
514 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800515 }
516
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800517 run("HeicCompositeStreamProc");
518
519 return NO_ERROR;
520}
521
522status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
523 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
524 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
525 (*outSurfaceMap)[mAppSegmentStreamId] = std::vector<size_t>();
526 outputStreamIds->push_back(mAppSegmentStreamId);
527 }
528 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
529
530 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
531 (*outSurfaceMap)[mMainImageStreamId] = std::vector<size_t>();
532 outputStreamIds->push_back(mMainImageStreamId);
533 }
534 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
535
536 if (currentStreamId != nullptr) {
537 *currentStreamId = mMainImageStreamId;
538 }
539
540 return NO_ERROR;
541}
542
Emilian Peev4697b642019-11-19 17:11:14 -0800543status_t HeicCompositeStream::insertCompositeStreamIds(
544 std::vector<int32_t>* compositeStreamIds /*out*/) {
545 if (compositeStreamIds == nullptr) {
546 return BAD_VALUE;
547 }
548
549 compositeStreamIds->push_back(mAppSegmentStreamId);
550 compositeStreamIds->push_back(mMainImageStreamId);
551
552 return OK;
553}
554
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800555void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
556 Mutex::Autolock l(mMutex);
557 if (mErrorState) {
558 return;
559 }
560
561 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800562 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
563 resultExtras.frameNumber, timestamp, resultExtras.requestId);
564 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
565 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
566 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800567 mInputReadyCondition.signal();
568 }
569}
570
571void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800572 auto i = mSettingsByFrameNumber.begin();
573 while (i != mSettingsByFrameNumber.end()) {
574 if (i->second.shutterNotified) {
575 mPendingInputFrames[i->first].orientation = i->second.orientation;
576 mPendingInputFrames[i->first].quality = i->second.quality;
577 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
578 mPendingInputFrames[i->first].requestId = i->second.requestId;
579 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
580 i->first, i->second.timestamp);
581 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700582
Shuzhen Wange8675782019-12-05 09:12:14 -0800583 // Set encoder quality if no inflight encoding
584 if (mPendingInputFrames.size() == 1) {
585 sp<StatusTracker> statusTracker = mStatusTracker.promote();
586 if (statusTracker != nullptr) {
587 statusTracker->markComponentActive(mStatusId);
588 ALOGV("%s: Mark component as active", __FUNCTION__);
589 }
590
591 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
592 updateCodecQualityLocked(newQuality);
593 }
594 } else {
595 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700596 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800597 }
598
Shuzhen Wange8675782019-12-05 09:12:14 -0800599 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800600 CpuConsumer::LockedBuffer imgBuffer;
601 auto it = mInputAppSegmentBuffers.begin();
602 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
603 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700604 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800605 break;
606 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
607 if (res != OK) {
608 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
609 strerror(-res), res);
610 } else {
611 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
612 " received buffer with time stamp: %" PRId64, __FUNCTION__,
613 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700614 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800615 }
616 mPendingInputFrames[*it].error = true;
617 mInputAppSegmentBuffers.erase(it);
618 continue;
619 }
620
Shuzhen Wange8675782019-12-05 09:12:14 -0800621 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
622 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
623 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700624 mInputAppSegmentBuffers.erase(it);
625 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800626 continue;
627 }
628
629 int64_t frameNumber = mAppSegmentFrameNumbers.front();
630 // If mPendingInputFrames doesn't contain the expected frame number, the captured
631 // input app segment frame must have been dropped via a buffer error. Simply
632 // return the buffer to the buffer queue.
633 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
634 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800635 mAppSegmentConsumer->unlockBuffer(imgBuffer);
636 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800637 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700638 mLockedAppSegmentBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800639 }
640 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800641 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800642 }
643
Shuzhen Wange8675782019-12-05 09:12:14 -0800644 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800645 CpuConsumer::LockedBuffer imgBuffer;
646 auto it = mInputYuvBuffers.begin();
647 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
648 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700649 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800650 break;
651 } else if (res != OK) {
652 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
653 strerror(-res), res);
654 mPendingInputFrames[*it].error = true;
655 mInputYuvBuffers.erase(it);
656 continue;
657 } else if (*it != imgBuffer.timestamp) {
658 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
659 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
660 mPendingInputFrames[*it].error = true;
661 mInputYuvBuffers.erase(it);
662 continue;
663 }
664
Shuzhen Wange8675782019-12-05 09:12:14 -0800665 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
666 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
667 mMainImageFrameNumbers.front());
668 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700669 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800670 continue;
671 }
672
673 int64_t frameNumber = mMainImageFrameNumbers.front();
674 // If mPendingInputFrames doesn't contain the expected frame number, the captured
675 // input main image must have been dropped via a buffer error. Simply
676 // return the buffer to the buffer queue.
677 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
678 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800679 mMainImageConsumer->unlockBuffer(imgBuffer);
680 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800681 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800682 mYuvBufferAcquired = true;
683 }
684 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800685 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800686 }
687
688 while (!mCodecOutputBuffers.empty()) {
689 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800690 // Assume encoder input to output is FIFO, use a queue to look up
691 // frameNumber when handling codec outputs.
692 int64_t bufferFrameNumber = -1;
693 if (mCodecOutputBufferFrameNumbers.empty()) {
694 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700695 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800696 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800697 // Direct mapping between camera frame number and codec timestamp (in us).
698 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700699 mCodecOutputCounter++;
700 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800701 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700702 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800703 }
704
Shuzhen Wange8675782019-12-05 09:12:14 -0800705 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
706 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
707 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800708 }
709 mCodecOutputBuffers.erase(it);
710 }
711
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800712 while (!mCaptureResults.empty()) {
713 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800714 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800715 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800716 int64_t frameNumber = std::get<0>(it->second);
717 if (it->first >= 0 &&
718 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
719 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
720 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800721 std::make_unique<CameraMetadata>(std::get<1>(it->second));
722 } else {
723 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800724 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
725 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
726 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800727 }
728 }
729 mCaptureResults.erase(it);
730 }
731
732 // mErrorFrameNumbers stores frame number of dropped buffers.
733 auto it = mErrorFrameNumbers.begin();
734 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800735 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
736 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800737 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800738 //Error callback is guaranteed to arrive after shutter notify, which
739 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800740 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
741 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800742 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800743 it = mErrorFrameNumbers.erase(it);
744 }
745
746 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
747 it = mExifErrorFrameNumbers.begin();
748 while (it != mExifErrorFrameNumbers.end()) {
749 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
750 mPendingInputFrames[*it].exifError = true;
751 }
752 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800753 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800754
755 // Distribute codec input buffers to be filled out from YUV output
756 for (auto it = mPendingInputFrames.begin();
757 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
758 InputFrame& inputFrame(it->second);
759 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
760 // Available input tiles that are required for the current input
761 // image.
762 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
763 mGridRows * mGridCols - inputFrame.codecInputCounter);
764 for (size_t i = 0; i < newInputTiles; i++) {
765 CodecInputBufferInfo inputInfo =
766 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
767 inputFrame.codecInputBuffers.push_back(inputInfo);
768
769 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
770 inputFrame.codecInputCounter++;
771 }
772 break;
773 }
774 }
775}
776
Shuzhen Wange8675782019-12-05 09:12:14 -0800777bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
778 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800779 return false;
780 }
781
782 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700783 for (auto& it : mPendingInputFrames) {
784 // New input is considered to be available only if:
785 // 1. input buffers are ready, or
786 // 2. App segment and muxer is created, or
787 // 3. A codec output tile is ready, and an output buffer is available.
788 // This makes sure that muxer gets created only when an output tile is
789 // generated, because right now we only handle 1 HEIC output buffer at a
790 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800791 bool appSegmentReady =
792 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700793 !it.second.appSegmentWritten && it.second.result != nullptr &&
794 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800795 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
796 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
797 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700798 bool hasOutputBuffer = it.second.muxer != nullptr ||
799 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800800 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700801 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800802 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700803 if (it.second.format == nullptr && mFormat != nullptr) {
804 it.second.format = mFormat->dup();
805 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800806 newInputAvailable = true;
807 break;
808 }
809 }
810
811 return newInputAvailable;
812}
813
Shuzhen Wange8675782019-12-05 09:12:14 -0800814int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800815 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800816
817 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800818 if (it.second.error) {
819 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800820 break;
821 }
822 }
823
824 return res;
825}
826
Shuzhen Wange8675782019-12-05 09:12:14 -0800827status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800828 InputFrame &inputFrame) {
829 ATRACE_CALL();
830 status_t res = OK;
831
Shuzhen Wange8675782019-12-05 09:12:14 -0800832 bool appSegmentReady =
833 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700834 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
835 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800836 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
837 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700838 !inputFrame.codecInputBuffers.empty();
839 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
840 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800841
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700842 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800843 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
844 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
845 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800846
847 // Handle inputs for Hevc tiling
848 if (codecInputReady) {
849 res = processCodecInputFrame(inputFrame);
850 if (res != OK) {
851 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
852 strerror(-res), res);
853 return res;
854 }
855 }
856
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700857 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
858 return OK;
859 }
860
861 // Initialize and start muxer if not yet done so. In this case,
862 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
863 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800864 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800865 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800866 if (res != OK) {
867 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
868 strerror(-res), res);
869 return res;
870 }
871 }
872
873 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700874 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800875 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800876 if (res != OK) {
877 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
878 strerror(-res), res);
879 return res;
880 }
881 }
882
883 // Write media codec bitstream buffers to muxer.
884 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800885 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800886 if (res != OK) {
887 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
888 strerror(-res), res);
889 return res;
890 }
891 }
892
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700893 if (inputFrame.pendingOutputTiles == 0) {
894 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800895 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700896 if (res != OK) {
897 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
898 strerror(-res), res);
899 return res;
900 }
901 } else if (mLockedAppSegmentBufferCnt == kMaxAcquiredAppSegment) {
902 ALOGE("%s: Out-of-order app segment buffers reaches limit %u", __FUNCTION__,
903 kMaxAcquiredAppSegment);
904 return INVALID_OPERATION;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800905 }
906 }
907
908 return res;
909}
910
Shuzhen Wange8675782019-12-05 09:12:14 -0800911status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800912 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800913
914 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
915 if (res != OK) {
916 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
917 res);
918 return res;
919 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700920 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800921
922 // Combine current thread id, stream id and timestamp to uniquely identify image.
923 std::ostringstream tempOutputFile;
924 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800925 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800926 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
927 if (inputFrame.fileFd < 0) {
928 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
929 tempOutputFile.str().c_str(), errno);
930 return NO_INIT;
931 }
932 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
933 if (inputFrame.muxer == nullptr) {
934 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
935 __FUNCTION__, inputFrame.fileFd);
936 return NO_INIT;
937 }
938
939 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
940 if (res != OK) {
941 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
942 strerror(-res), res);
943 return res;
944 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800945
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700946 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800947 if (trackId < 0) {
948 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
949 return NO_INIT;
950 }
951
952 inputFrame.trackIndex = trackId;
953 inputFrame.pendingOutputTiles = mNumOutputTiles;
954
955 res = inputFrame.muxer->start();
956 if (res != OK) {
957 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
958 __FUNCTION__, strerror(-res), res);
959 return res;
960 }
961
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700962 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800963 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800964 return OK;
965}
966
Shuzhen Wange8675782019-12-05 09:12:14 -0800967status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800968 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800969 size_t appSegmentSize = 0;
970 if (!inputFrame.exifError) {
971 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
972 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
973 &app1Size);
974 if (appSegmentSize == 0) {
975 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
976 return NO_INIT;
977 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800978 }
979
980 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800981 auto exifRes = inputFrame.exifError ?
982 exifUtils->initializeEmpty() :
983 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800984 if (!exifRes) {
985 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
986 return BAD_VALUE;
987 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800988 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
989 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800990 if (!exifRes) {
991 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
992 return BAD_VALUE;
993 }
994 exifRes = exifUtils->setOrientation(inputFrame.orientation);
995 if (!exifRes) {
996 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
997 return BAD_VALUE;
998 }
999 exifRes = exifUtils->generateApp1();
1000 if (!exifRes) {
1001 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
1002 return BAD_VALUE;
1003 }
1004
1005 unsigned int newApp1Length = exifUtils->getApp1Length();
1006 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1007
1008 //Assemble the APP1 marker buffer required by MediaCodec
1009 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1010 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1011 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1012 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1013 appSegmentSize - app1Size + newApp1Length;
1014 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1015 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1016 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1017 if (appSegmentSize - app1Size > 0) {
1018 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1019 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1020 }
1021
1022 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1023 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001024 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001025 delete[] appSegmentBuffer;
1026
1027 if (res != OK) {
1028 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1029 __FUNCTION__, strerror(-res), res);
1030 return res;
1031 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001032
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001033 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001034 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001035 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001036
1037 inputFrame.appSegmentWritten = true;
1038 // Release the buffer now so any pending input app segments can be processed
1039 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1040 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001041 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001042 mLockedAppSegmentBufferCnt--;
1043
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;
1137 auto res = gb->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &dstBuffer, inputFrame.fenceFd);
1138 if (res != OK) {
1139 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1140 strerror(-res), res);
1141 return res;
1142 }
1143
1144 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1145 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1146 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1147 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1148 return BAD_VALUE;
1149 }
1150
1151 lseek(inputFrame.fileFd, 0, SEEK_SET);
1152 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1153 if (bytesRead < fSize) {
1154 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1155 return BAD_VALUE;
1156 }
1157
1158 close(inputFrame.fileFd);
1159 inputFrame.fileFd = -1;
1160
1161 // Fill in HEIC header
1162 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1163 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
1164 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
1165 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
1166 blobHeader->blobSize = fSize;
1167
Shuzhen Wange8675782019-12-05 09:12:14 -08001168 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001169 if (res != OK) {
1170 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1171 __FUNCTION__, getStreamId(), strerror(-res), res);
1172 return res;
1173 }
1174
1175 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1176 if (res != OK) {
1177 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1178 strerror(-res), res);
1179 return res;
1180 }
1181 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001182 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001183
Shuzhen Wange8675782019-12-05 09:12:14 -08001184 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1185 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001186 return OK;
1187}
1188
1189
Shuzhen Wange8675782019-12-05 09:12:14 -08001190void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1191 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001192 if (inputFrame == nullptr) {
1193 return;
1194 }
1195
1196 if (inputFrame->appSegmentBuffer.data != nullptr) {
1197 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1198 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001199 }
1200
1201 while (!inputFrame->codecOutputBuffers.empty()) {
1202 auto it = inputFrame->codecOutputBuffers.begin();
1203 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1204 mCodec->releaseOutputBuffer(it->index);
1205 inputFrame->codecOutputBuffers.erase(it);
1206 }
1207
1208 if (inputFrame->yuvBuffer.data != nullptr) {
1209 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1210 inputFrame->yuvBuffer.data = nullptr;
1211 mYuvBufferAcquired = false;
1212 }
1213
1214 while (!inputFrame->codecInputBuffers.empty()) {
1215 auto it = inputFrame->codecInputBuffers.begin();
1216 inputFrame->codecInputBuffers.erase(it);
1217 }
1218
Shuzhen Wange8675782019-12-05 09:12:14 -08001219 if (inputFrame->error || mErrorState) {
1220 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1221 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001222 }
1223
1224 if (inputFrame->fileFd >= 0) {
1225 close(inputFrame->fileFd);
1226 inputFrame->fileFd = -1;
1227 }
1228
1229 if (inputFrame->anb != nullptr) {
1230 sp<ANativeWindow> outputANW = mOutputSurface;
1231 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1232 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001233
1234 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001235 }
1236}
1237
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001238void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001239 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001240 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001241 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001242 auto& inputFrame = it->second;
1243 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001244 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1245 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001246 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001247 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001248 } else {
1249 it++;
1250 }
1251 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001252
1253 // Update codec quality based on first upcoming input frame.
1254 // Note that when encoding is in surface mode, currently there is no
1255 // way for camera service to synchronize quality setting on a per-frame
1256 // basis: we don't get notification when codec is ready to consume a new
1257 // input frame. So we update codec quality on a best-effort basis.
1258 if (inputFrameDone) {
1259 auto firstPendingFrame = mPendingInputFrames.begin();
1260 if (firstPendingFrame != mPendingInputFrames.end()) {
1261 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001262 } else {
1263 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001264 }
1265 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001266}
1267
1268status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1269 const sp<CameraDeviceBase>& cameraDevice) {
1270 ALOGV("%s", __FUNCTION__);
1271
1272 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001273 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001274 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001275 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001276 if (!isSizeSupported) {
1277 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1278 __FUNCTION__, width, height);
1279 return BAD_VALUE;
1280 }
1281
1282 // Create Looper for MediaCodec.
1283 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1284 mCodecLooper = new ALooper;
1285 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1286 status_t res = mCodecLooper->start(
1287 false, // runOnCallingThread
1288 false, // canCallJava
1289 PRIORITY_AUDIO);
1290 if (res != OK) {
1291 ALOGE("%s: Failed to start codec looper: %s (%d)",
1292 __FUNCTION__, strerror(-res), res);
1293 return NO_INIT;
1294 }
1295
1296 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001297 if (mUseHeic) {
1298 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1299 } else {
1300 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1301 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001302 if (mCodec == nullptr) {
1303 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1304 return NO_INIT;
1305 }
1306
1307 // Create Looper and handler for Codec callback.
1308 mCodecCallbackHandler = new CodecCallbackHandler(this);
1309 if (mCodecCallbackHandler == nullptr) {
1310 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1311 return NO_MEMORY;
1312 }
1313 mCallbackLooper = new ALooper;
1314 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1315 res = mCallbackLooper->start(
1316 false, // runOnCallingThread
1317 false, // canCallJava
1318 PRIORITY_AUDIO);
1319 if (res != OK) {
1320 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1321 __FUNCTION__, strerror(-res), res);
1322 return NO_INIT;
1323 }
1324 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1325
1326 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1327 res = mCodec->setCallback(mAsyncNotify);
1328 if (res != OK) {
1329 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1330 strerror(-res), res);
1331 return res;
1332 }
1333
1334 // Create output format and configure the Codec.
1335 sp<AMessage> outputFormat = new AMessage();
1336 outputFormat->setString(KEY_MIME, desiredMime);
1337 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1338 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1339 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001340 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001341
1342 int32_t gridWidth, gridHeight, gridRows, gridCols;
1343 if (useGrid || mUseHeic) {
1344 gridWidth = HeicEncoderInfoManager::kGridWidth;
1345 gridHeight = HeicEncoderInfoManager::kGridHeight;
1346 gridRows = (height + gridHeight - 1)/gridHeight;
1347 gridCols = (width + gridWidth - 1)/gridWidth;
1348
1349 if (mUseHeic) {
1350 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1351 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1352 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1353 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1354 }
1355
1356 } else {
1357 gridWidth = width;
1358 gridHeight = height;
1359 gridRows = 1;
1360 gridCols = 1;
1361 }
1362
1363 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1364 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1365 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1366 outputFormat->setInt32(KEY_COLOR_FORMAT,
1367 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001368 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001369 // This only serves as a hint to encoder when encoding is not real-time.
1370 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1371
1372 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1373 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1374 if (res != OK) {
1375 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1376 strerror(-res), res);
1377 return res;
1378 }
1379
1380 mGridWidth = gridWidth;
1381 mGridHeight = gridHeight;
1382 mGridRows = gridRows;
1383 mGridCols = gridCols;
1384 mUseGrid = useGrid;
1385 mOutputWidth = width;
1386 mOutputHeight = height;
1387 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
1388 mMaxHeicBufferSize = mOutputWidth * mOutputHeight * 3 / 2 + mAppSegmentMaxSize;
1389
1390 return OK;
1391}
1392
1393void HeicCompositeStream::deinitCodec() {
1394 ALOGV("%s", __FUNCTION__);
1395 if (mCodec != nullptr) {
1396 mCodec->stop();
1397 mCodec->release();
1398 mCodec.clear();
1399 }
1400
1401 if (mCodecLooper != nullptr) {
1402 mCodecLooper->stop();
1403 mCodecLooper.clear();
1404 }
1405
1406 if (mCallbackLooper != nullptr) {
1407 mCallbackLooper->stop();
1408 mCallbackLooper.clear();
1409 }
1410
1411 mAsyncNotify.clear();
1412 mFormat.clear();
1413}
1414
1415// Return the size of the complete list of app segment, 0 indicates failure
1416size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1417 size_t maxSize, size_t *app1SegmentSize) {
1418 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1419 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1420 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1421 return 0;
1422 }
1423
1424 size_t expectedSize = 0;
1425 // First check for EXIF transport header at the end of the buffer
1426 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1427 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1428 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1429 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1430 return 0;
1431 }
1432
1433 expectedSize = blob->blobSize;
1434 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1435 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1436 return 0;
1437 }
1438
1439 uint32_t totalSize = 0;
1440
1441 // Verify APP1 marker (mandatory)
1442 uint8_t app1Marker[] = {0xFF, 0xE1};
1443 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1444 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1445 appSegmentBuffer[0], appSegmentBuffer[1]);
1446 return 0;
1447 }
1448 totalSize += sizeof(app1Marker);
1449
1450 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1451 appSegmentBuffer[totalSize+1];
1452 totalSize += app1Size;
1453
1454 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1455 __FUNCTION__, expectedSize, app1Size);
1456 while (totalSize < expectedSize) {
1457 if (appSegmentBuffer[totalSize] != 0xFF ||
1458 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1459 appSegmentBuffer[totalSize+1] > 0xEF) {
1460 // Invalid APPn marker
1461 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1462 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1463 return 0;
1464 }
1465 totalSize += 2;
1466
1467 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1468 appSegmentBuffer[totalSize+1];
1469 totalSize += appnSize;
1470 }
1471
1472 if (totalSize != expectedSize) {
1473 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1474 __FUNCTION__, totalSize, expectedSize);
1475 return 0;
1476 }
1477
1478 *app1SegmentSize = app1Size + sizeof(app1Marker);
1479 return expectedSize;
1480}
1481
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001482status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1483 const CpuConsumer::LockedBuffer& yuvBuffer,
1484 size_t top, size_t left, size_t width, size_t height) {
1485 ATRACE_CALL();
1486
1487 // Get stride information for codecBuffer
1488 sp<ABuffer> imageData;
1489 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1490 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1491 return BAD_VALUE;
1492 }
1493 if (imageData->size() != sizeof(MediaImage2)) {
1494 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1495 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1496 return BAD_VALUE;
1497 }
1498 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1499 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1500 imageInfo->mBitDepth != 8 ||
1501 imageInfo->mBitDepthAllocated != 8 ||
1502 imageInfo->mNumPlanes != 3) {
1503 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1504 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1505 imageInfo->mType, imageInfo->mBitDepth,
1506 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1507 return BAD_VALUE;
1508 }
1509
1510 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1511 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1512 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1513 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1514 imageInfo->mPlane[MediaImage2::V].mOffset,
1515 imageInfo->mPlane[MediaImage2::U].mRowInc,
1516 imageInfo->mPlane[MediaImage2::V].mRowInc,
1517 imageInfo->mPlane[MediaImage2::U].mColInc,
1518 imageInfo->mPlane[MediaImage2::V].mColInc);
1519
1520 // Y
1521 for (auto row = top; row < top+height; row++) {
1522 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1523 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001524 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001525 }
1526
1527 // U is Cb, V is Cr
1528 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1529 imageInfo->mPlane[MediaImage2::U].mOffset;
1530 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1531 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1532 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1533 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1534 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1535 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1536 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1537 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1538 bool isCodecUvPlannar =
1539 ((codecUPlaneFirst && codecUvOffsetDiff >=
1540 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1541 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1542 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1543 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1544 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1545 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1546
1547 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1548 (codecUPlaneFirst == cameraUPlaneFirst)) {
1549 // UV semiplannar
1550 // The chrome plane could be either Cb first, or Cr first. Take the
1551 // smaller address.
1552 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1553 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1554 for (auto row = top/2; row < (top+height)/2; row++) {
1555 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1556 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001557 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001558 }
1559 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1560 // U plane
1561 for (auto row = top/2; row < (top+height)/2; row++) {
1562 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1563 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001564 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001565 }
1566
1567 // V plane
1568 for (auto row = top/2; row < (top+height)/2; row++) {
1569 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1570 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001571 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001572 }
1573 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001574 // Convert between semiplannar and plannar, or when UV orders are
1575 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001576 uint8_t *dst = codecBuffer->data();
1577 for (auto row = top/2; row < (top+height)/2; row++) {
1578 for (auto col = left/2; col < (left+width)/2; col++) {
1579 // U/Cb
1580 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1581 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1582 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1583 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1584 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1585
1586 // V/Cr
1587 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1588 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1589 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1590 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1591 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1592 }
1593 }
1594 }
1595 return OK;
1596}
1597
Shuzhen Wang219c2992019-02-15 17:24:28 -08001598void HeicCompositeStream::initCopyRowFunction(int32_t width)
1599{
1600 using namespace libyuv;
1601
1602 mFnCopyRow = CopyRow_C;
1603#if defined(HAS_COPYROW_SSE2)
1604 if (TestCpuFlag(kCpuHasSSE2)) {
1605 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1606 }
1607#endif
1608#if defined(HAS_COPYROW_AVX)
1609 if (TestCpuFlag(kCpuHasAVX)) {
1610 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1611 }
1612#endif
1613#if defined(HAS_COPYROW_ERMS)
1614 if (TestCpuFlag(kCpuHasERMS)) {
1615 mFnCopyRow = CopyRow_ERMS;
1616 }
1617#endif
1618#if defined(HAS_COPYROW_NEON)
1619 if (TestCpuFlag(kCpuHasNEON)) {
1620 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1621 }
1622#endif
1623#if defined(HAS_COPYROW_MIPS)
1624 if (TestCpuFlag(kCpuHasMIPS)) {
1625 mFnCopyRow = CopyRow_MIPS;
1626 }
1627#endif
1628}
1629
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001630size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1631 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1632 size_t maxAppsSegment = 1;
1633 if (entry.count > 0) {
1634 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1635 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1636 }
1637 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1638}
1639
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001640void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1641 if (quality != mQuality) {
1642 sp<AMessage> qualityParams = new AMessage;
1643 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1644 status_t res = mCodec->setParameters(qualityParams);
1645 if (res != OK) {
1646 ALOGE("%s: Failed to set codec quality: %s (%d)",
1647 __FUNCTION__, strerror(-res), res);
1648 } else {
1649 mQuality = quality;
1650 }
1651 }
1652}
1653
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001654bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001655 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001656 bool newInputAvailable = false;
1657
1658 {
1659 Mutex::Autolock l(mMutex);
1660 if (mErrorState) {
1661 // In case we landed in error state, return any pending buffers and
1662 // halt all further processing.
1663 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001664 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001665 return false;
1666 }
1667
1668
1669 while (!newInputAvailable) {
1670 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001671 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001672
1673 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001674 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001675 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001676 releaseInputFrameLocked(failingFrameNumber,
1677 &mPendingInputFrames[failingFrameNumber]);
1678
1679 // It's okay to remove the entry from mPendingInputFrames
1680 // because:
1681 // 1. Only one internal stream (main input) is critical in
1682 // backing the output stream.
1683 // 2. If captureResult/appSegment arrives after the entry is
1684 // removed, they are simply skipped.
1685 mPendingInputFrames.erase(failingFrameNumber);
1686 if (mPendingInputFrames.size() == 0) {
1687 markTrackerIdle();
1688 }
1689 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001690 }
1691
1692 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1693 if (ret == TIMED_OUT) {
1694 return true;
1695 } else if (ret != OK) {
1696 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1697 strerror(-ret), ret);
1698 return false;
1699 }
1700 }
1701 }
1702 }
1703
Shuzhen Wange8675782019-12-05 09:12:14 -08001704 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001705 Mutex::Autolock l(mMutex);
1706 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001707 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1708 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1709 frameNumber, strerror(-res), res);
1710 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001711 }
1712
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001713 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001714
1715 return true;
1716}
1717
Shuzhen Wange8675782019-12-05 09:12:14 -08001718void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1719 Mutex::Autolock l(mMutex);
1720 mExifErrorFrameNumbers.emplace(frameNumber);
1721 mInputReadyCondition.signal();
1722}
1723
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001724bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1725 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001726 int64_t frameNumber = resultExtras.frameNumber;
1727
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001728 // Buffer errors concerning internal composite streams should not be directly visible to
1729 // camera clients. They must only receive a single buffer error with the public composite
1730 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001731 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1732 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1733 flagAnExifErrorFrameNumber(frameNumber);
1734 res = true;
1735 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1736 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1737 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001738 res = true;
1739 }
1740
1741 return res;
1742}
1743
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001744void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1745 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1746 // simply skip using the capture result metadata to override EXIF.
1747 Mutex::Autolock l(mMutex);
1748
1749 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001750 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001751 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001752 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001753 break;
1754 }
1755 }
1756 if (timestamp == -1) {
1757 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001758 if (inputFrame.first == resultExtras.frameNumber) {
1759 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001760 break;
1761 }
1762 }
1763 }
1764
1765 if (timestamp == -1) {
1766 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1767 return;
1768 }
1769
1770 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001771 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1772 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001773 mInputReadyCondition.signal();
1774}
1775
Shuzhen Wange8675782019-12-05 09:12:14 -08001776void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1777 auto frameNumber = resultExtras.frameNumber;
1778 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1779 Mutex::Autolock l(mMutex);
1780 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1781 if (numRequests == 0) {
1782 // Pending request has been populated into mPendingInputFrames
1783 mErrorFrameNumbers.emplace(frameNumber);
1784 mInputReadyCondition.signal();
1785 } else {
1786 // REQUEST_ERROR was received without onShutter.
1787 }
1788}
1789
1790void HeicCompositeStream::markTrackerIdle() {
1791 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1792 if (statusTracker != nullptr) {
1793 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1794 ALOGV("%s: Mark component as idle", __FUNCTION__);
1795 }
1796}
1797
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001798void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1799 sp<HeicCompositeStream> parent = mParent.promote();
1800 if (parent == nullptr) return;
1801
1802 switch (msg->what()) {
1803 case kWhatCallbackNotify: {
1804 int32_t cbID;
1805 if (!msg->findInt32("callbackID", &cbID)) {
1806 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1807 break;
1808 }
1809
1810 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1811
1812 switch (cbID) {
1813 case MediaCodec::CB_INPUT_AVAILABLE: {
1814 int32_t index;
1815 if (!msg->findInt32("index", &index)) {
1816 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1817 break;
1818 }
1819 parent->onHeicInputFrameAvailable(index);
1820 break;
1821 }
1822
1823 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1824 int32_t index;
1825 size_t offset;
1826 size_t size;
1827 int64_t timeUs;
1828 int32_t flags;
1829
1830 if (!msg->findInt32("index", &index)) {
1831 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1832 break;
1833 }
1834 if (!msg->findSize("offset", &offset)) {
1835 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1836 break;
1837 }
1838 if (!msg->findSize("size", &size)) {
1839 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1840 break;
1841 }
1842 if (!msg->findInt64("timeUs", &timeUs)) {
1843 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1844 break;
1845 }
1846 if (!msg->findInt32("flags", &flags)) {
1847 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1848 break;
1849 }
1850
1851 CodecOutputBufferInfo bufferInfo = {
1852 index,
1853 (int32_t)offset,
1854 (int32_t)size,
1855 timeUs,
1856 (uint32_t)flags};
1857
1858 parent->onHeicOutputFrameAvailable(bufferInfo);
1859 break;
1860 }
1861
1862 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1863 sp<AMessage> format;
1864 if (!msg->findMessage("format", &format)) {
1865 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1866 break;
1867 }
Chong Zhang860eff12019-09-16 16:15:00 -07001868 // Here format is MediaCodec's internal copy of output format.
1869 // Make a copy since onHeicFormatChanged() might modify it.
1870 sp<AMessage> formatCopy;
1871 if (format != nullptr) {
1872 formatCopy = format->dup();
1873 }
1874 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001875 break;
1876 }
1877
1878 case MediaCodec::CB_ERROR: {
1879 status_t err;
1880 int32_t actionCode;
1881 AString detail;
1882 if (!msg->findInt32("err", &err)) {
1883 ALOGE("CB_ERROR: err is expected.");
1884 break;
1885 }
1886 if (!msg->findInt32("action", &actionCode)) {
1887 ALOGE("CB_ERROR: action is expected.");
1888 break;
1889 }
1890 msg->findString("detail", &detail);
1891 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1892 err, actionCode, detail.c_str());
1893
1894 parent->onHeicCodecError();
1895 break;
1896 }
1897
1898 default: {
1899 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1900 break;
1901 }
1902 }
1903 break;
1904 }
1905
1906 default:
1907 ALOGE("shouldn't be here");
1908 break;
1909 }
1910}
1911
1912}; // namespace camera3
1913}; // namespace android