blob: 9b5946588a5ede4a1978776f33891edbe7ed7a83 [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),
68 mCodecOutputCounter(0),
Shuzhen Wang62f49ed2019-09-04 14:07:53 -070069 mQuality(-1),
Shuzhen Wange8675782019-12-05 09:12:14 -080070 mGridTimestampUs(0),
71 mStatusId(StatusTracker::NO_STATUS_ID) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080072}
73
74HeicCompositeStream::~HeicCompositeStream() {
75 // Call deinitCodec in case stream hasn't been deleted yet to avoid any
76 // memory/resource leak.
77 deinitCodec();
78
79 mInputAppSegmentBuffers.clear();
80 mCodecOutputBuffers.clear();
81
82 mAppSegmentStreamId = -1;
83 mAppSegmentSurfaceId = -1;
84 mAppSegmentConsumer.clear();
85 mAppSegmentSurface.clear();
86
87 mMainImageStreamId = -1;
88 mMainImageSurfaceId = -1;
89 mMainImageConsumer.clear();
90 mMainImageSurface.clear();
91}
92
93bool HeicCompositeStream::isHeicCompositeStream(const sp<Surface> &surface) {
94 ANativeWindow *anw = surface.get();
95 status_t err;
96 int format;
97 if ((err = anw->query(anw, NATIVE_WINDOW_FORMAT, &format)) != OK) {
98 String8 msg = String8::format("Failed to query Surface format: %s (%d)", strerror(-err),
99 err);
100 ALOGE("%s: %s", __FUNCTION__, msg.string());
101 return false;
102 }
103
104 int dataspace;
105 if ((err = anw->query(anw, NATIVE_WINDOW_DEFAULT_DATASPACE, &dataspace)) != OK) {
106 String8 msg = String8::format("Failed to query Surface dataspace: %s (%d)", strerror(-err),
107 err);
108 ALOGE("%s: %s", __FUNCTION__, msg.string());
109 return false;
110 }
111
112 return ((format == HAL_PIXEL_FORMAT_BLOB) && (dataspace == HAL_DATASPACE_HEIF));
113}
114
115status_t HeicCompositeStream::createInternalStreams(const std::vector<sp<Surface>>& consumers,
116 bool /*hasDeferredConsumer*/, uint32_t width, uint32_t height, int format,
117 camera3_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
118 std::vector<int> *surfaceIds, int /*streamSetId*/, bool /*isShared*/) {
119
120 sp<CameraDeviceBase> device = mDevice.promote();
121 if (!device.get()) {
122 ALOGE("%s: Invalid camera device!", __FUNCTION__);
123 return NO_INIT;
124 }
125
126 status_t res = initializeCodec(width, height, device);
127 if (res != OK) {
128 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
129 __FUNCTION__, strerror(-res), res);
130 return NO_INIT;
131 }
132
133 sp<IGraphicBufferProducer> producer;
134 sp<IGraphicBufferConsumer> consumer;
135 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700136 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800137 mAppSegmentConsumer->setFrameAvailableListener(this);
138 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
139 mAppSegmentSurface = new Surface(producer);
140
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800141 mStaticInfo = device->info();
142
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800143 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
144 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId, surfaceIds);
145 if (res == OK) {
146 mAppSegmentSurfaceId = (*surfaceIds)[0];
147 } else {
148 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
149 strerror(-res), res);
150 return res;
151 }
152
153 if (!mUseGrid) {
154 res = mCodec->createInputSurface(&producer);
155 if (res != OK) {
156 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
157 __FUNCTION__, strerror(-res), res);
158 return res;
159 }
160 } else {
161 BufferQueue::createBufferQueue(&producer, &consumer);
162 mMainImageConsumer = new CpuConsumer(consumer, 1);
163 mMainImageConsumer->setFrameAvailableListener(this);
164 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
165 }
166 mMainImageSurface = new Surface(producer);
167
168 res = mCodec->start();
169 if (res != OK) {
170 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
171 strerror(-res), res);
172 return res;
173 }
174
175 std::vector<int> sourceSurfaceId;
176 //Use YUV_888 format if framework tiling is needed.
177 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
178 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
179 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
180 rotation, id, physicalCameraId, &sourceSurfaceId);
181 if (res == OK) {
182 mMainImageSurfaceId = sourceSurfaceId[0];
183 mMainImageStreamId = *id;
184 } else {
185 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
186 strerror(-res), res);
187 return res;
188 }
189
190 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800191 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800192 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800193 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
194 strerror(-res), res);
195 return res;
196 }
197
198 res = registerCompositeStreamListener(mAppSegmentStreamId);
199 if (res != OK) {
200 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
201 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800202 return res;
203 }
204
Shuzhen Wang219c2992019-02-15 17:24:28 -0800205 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800206 return res;
207}
208
209status_t HeicCompositeStream::deleteInternalStreams() {
210 requestExit();
211 auto res = join();
212 if (res != OK) {
213 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
214 strerror(-res), res);
215 }
216
217 deinitCodec();
218
219 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700220 // Camera devices may not be valid after switching to offline mode.
221 // In this case, all offline streams including internal composite streams
222 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800223 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700224 if (device.get() != nullptr) {
225 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800226 }
227
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800228 mAppSegmentStreamId = -1;
229 }
230
Shuzhen Wang2c545042019-02-07 10:27:35 -0800231 if (mOutputSurface != nullptr) {
232 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
233 mOutputSurface.clear();
234 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800235
236 sp<StatusTracker> statusTracker = mStatusTracker.promote();
237 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
238 statusTracker->removeComponent(mStatusId);
239 mStatusId = StatusTracker::NO_STATUS_ID;
240 }
241
242 if (mPendingInputFrames.size() > 0) {
243 ALOGW("%s: mPendingInputFrames has %zu stale entries",
244 __FUNCTION__, mPendingInputFrames.size());
245 mPendingInputFrames.clear();
246 }
247
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800248 return res;
249}
250
251void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
252 Mutex::Autolock l(mMutex);
253
254 if (bufferInfo.mError) return;
255
Shuzhen Wange8675782019-12-05 09:12:14 -0800256 if (bufferInfo.mStreamId == mMainImageStreamId) {
257 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
258 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
259 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
260 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
261 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
262 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
263 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
264 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
265 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800266}
267
268// We need to get the settings early to handle the case where the codec output
269// arrives earlier than result metadata.
270void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
271 const CameraMetadata& settings) {
272 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
273
274 Mutex::Autolock l(mMutex);
275 if (mErrorState || (streamId != getStreamId())) {
276 return;
277 }
278
279 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
280
281 camera_metadata_ro_entry entry;
282
283 int32_t orientation = 0;
284 entry = settings.find(ANDROID_JPEG_ORIENTATION);
285 if (entry.count == 1) {
286 orientation = entry.data.i32[0];
287 }
288
289 int32_t quality = kDefaultJpegQuality;
290 entry = settings.find(ANDROID_JPEG_QUALITY);
291 if (entry.count == 1) {
292 quality = entry.data.i32[0];
293 }
294
Shuzhen Wange8675782019-12-05 09:12:14 -0800295 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800296}
297
298void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
299 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
300 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
301 __func__, ns2ms(item.mTimestamp));
302
303 Mutex::Autolock l(mMutex);
304 if (!mErrorState) {
305 mInputAppSegmentBuffers.push_back(item.mTimestamp);
306 mInputReadyCondition.signal();
307 }
308 } else if (item.mDataSpace == kHeifDataSpace) {
309 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
310 __func__, ns2ms(item.mTimestamp));
311
312 Mutex::Autolock l(mMutex);
313 if (!mUseGrid) {
314 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
315 __FUNCTION__);
316 return;
317 }
318 if (!mErrorState) {
319 mInputYuvBuffers.push_back(item.mTimestamp);
320 mInputReadyCondition.signal();
321 }
322 } else {
323 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
324 }
325}
326
327status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
328 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
329 if (compositeOutput == nullptr) {
330 return BAD_VALUE;
331 }
332
333 compositeOutput->clear();
334
335 bool useGrid, useHeic;
336 bool isSizeSupported = isSizeSupportedByHeifEncoder(
337 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
338 if (!isSizeSupported) {
339 // Size is not supported by either encoder.
340 return OK;
341 }
342
343 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
344
345 // JPEG APPS segments Blob stream info
346 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
347 (*compositeOutput)[0].height = 1;
348 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
349 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
350 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
351
352 // YUV/IMPLEMENTATION_DEFINED stream info
353 (*compositeOutput)[1].width = streamInfo.width;
354 (*compositeOutput)[1].height = streamInfo.height;
355 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
356 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
357 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
358 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
359 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
360
361 return NO_ERROR;
362}
363
364bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700365 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800366 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700367 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800368}
369
370bool HeicCompositeStream::isInMemoryTempFileSupported() {
371 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
372 if (memfd == -1) {
373 if (errno != ENOSYS) {
374 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
375 }
376 return false;
377 }
378 close(memfd);
379 return true;
380}
381
382void HeicCompositeStream::onHeicOutputFrameAvailable(
383 const CodecOutputBufferInfo& outputBufferInfo) {
384 Mutex::Autolock l(mMutex);
385
386 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
387 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
388 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
389
390 if (!mErrorState) {
391 if ((outputBufferInfo.size > 0) &&
392 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
393 mCodecOutputBuffers.push_back(outputBufferInfo);
394 mInputReadyCondition.signal();
395 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700396 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
397 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800398 mCodec->releaseOutputBuffer(outputBufferInfo.index);
399 }
400 } else {
401 mCodec->releaseOutputBuffer(outputBufferInfo.index);
402 }
403}
404
405void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
406 Mutex::Autolock l(mMutex);
407
408 if (!mUseGrid) {
409 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
410 return;
411 }
412
413 mCodecInputBuffers.push_back(index);
414 mInputReadyCondition.signal();
415}
416
417void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
418 if (newFormat == nullptr) {
419 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
420 return;
421 }
422
423 Mutex::Autolock l(mMutex);
424
425 AString mime;
426 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
427 newFormat->findString(KEY_MIME, &mime);
428 if (mime != mimeHeic) {
429 // For HEVC codec, below keys need to be filled out or overwritten so that the
430 // muxer can handle them as HEIC output image.
431 newFormat->setString(KEY_MIME, mimeHeic);
432 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
433 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
434 if (mUseGrid) {
435 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
436 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
437 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
438 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
439 }
440 }
441 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
442
443 int32_t gridRows, gridCols;
444 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
445 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
446 mNumOutputTiles = gridRows * gridCols;
447 } else {
448 mNumOutputTiles = 1;
449 }
450
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800451 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700452
453 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
454 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800455}
456
457void HeicCompositeStream::onHeicCodecError() {
458 Mutex::Autolock l(mMutex);
459 mErrorState = true;
460}
461
462status_t HeicCompositeStream::configureStream() {
463 if (isRunning()) {
464 // Processing thread is already running, nothing more to do.
465 return NO_ERROR;
466 }
467
468 if (mOutputSurface.get() == nullptr) {
469 ALOGE("%s: No valid output surface set!", __FUNCTION__);
470 return NO_INIT;
471 }
472
473 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
474 if (res != OK) {
475 ALOGE("%s: Unable to connect to native window for stream %d",
476 __FUNCTION__, mMainImageStreamId);
477 return res;
478 }
479
480 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
481 != OK) {
482 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
483 mMainImageStreamId);
484 return res;
485 }
486
487 ANativeWindow *anwConsumer = mOutputSurface.get();
488 int maxConsumerBuffers;
489 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
490 &maxConsumerBuffers)) != OK) {
491 ALOGE("%s: Unable to query consumer undequeued"
492 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
493 return res;
494 }
495
496 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
497 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800498 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700499 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800500 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
501 return res;
502 }
503
504 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
505 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
506 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
507 return res;
508 }
509
Shuzhen Wange8675782019-12-05 09:12:14 -0800510 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
511 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700512 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
513 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800514 }
515
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800516 run("HeicCompositeStreamProc");
517
518 return NO_ERROR;
519}
520
521status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
522 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
523 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800524 outputStreamIds->push_back(mAppSegmentStreamId);
525 }
526 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
527
528 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800529 outputStreamIds->push_back(mMainImageStreamId);
530 }
531 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
532
533 if (currentStreamId != nullptr) {
534 *currentStreamId = mMainImageStreamId;
535 }
536
537 return NO_ERROR;
538}
539
Emilian Peev4697b642019-11-19 17:11:14 -0800540status_t HeicCompositeStream::insertCompositeStreamIds(
541 std::vector<int32_t>* compositeStreamIds /*out*/) {
542 if (compositeStreamIds == nullptr) {
543 return BAD_VALUE;
544 }
545
546 compositeStreamIds->push_back(mAppSegmentStreamId);
547 compositeStreamIds->push_back(mMainImageStreamId);
548
549 return OK;
550}
551
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800552void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
553 Mutex::Autolock l(mMutex);
554 if (mErrorState) {
555 return;
556 }
557
558 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800559 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
560 resultExtras.frameNumber, timestamp, resultExtras.requestId);
561 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
562 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
563 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800564 mInputReadyCondition.signal();
565 }
566}
567
568void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800569 auto i = mSettingsByFrameNumber.begin();
570 while (i != mSettingsByFrameNumber.end()) {
571 if (i->second.shutterNotified) {
572 mPendingInputFrames[i->first].orientation = i->second.orientation;
573 mPendingInputFrames[i->first].quality = i->second.quality;
574 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
575 mPendingInputFrames[i->first].requestId = i->second.requestId;
576 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
577 i->first, i->second.timestamp);
578 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700579
Shuzhen Wange8675782019-12-05 09:12:14 -0800580 // Set encoder quality if no inflight encoding
581 if (mPendingInputFrames.size() == 1) {
582 sp<StatusTracker> statusTracker = mStatusTracker.promote();
583 if (statusTracker != nullptr) {
584 statusTracker->markComponentActive(mStatusId);
585 ALOGV("%s: Mark component as active", __FUNCTION__);
586 }
587
588 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
589 updateCodecQualityLocked(newQuality);
590 }
591 } else {
592 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700593 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800594 }
595
Shuzhen Wange8675782019-12-05 09:12:14 -0800596 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800597 CpuConsumer::LockedBuffer imgBuffer;
598 auto it = mInputAppSegmentBuffers.begin();
599 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
600 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700601 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800602 break;
603 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
604 if (res != OK) {
605 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
606 strerror(-res), res);
607 } else {
608 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
609 " received buffer with time stamp: %" PRId64, __FUNCTION__,
610 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700611 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800612 }
613 mPendingInputFrames[*it].error = true;
614 mInputAppSegmentBuffers.erase(it);
615 continue;
616 }
617
Shuzhen Wange8675782019-12-05 09:12:14 -0800618 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
619 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
620 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700621 mInputAppSegmentBuffers.erase(it);
622 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800623 continue;
624 }
625
626 int64_t frameNumber = mAppSegmentFrameNumbers.front();
627 // If mPendingInputFrames doesn't contain the expected frame number, the captured
628 // input app segment frame must have been dropped via a buffer error. Simply
629 // return the buffer to the buffer queue.
630 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
631 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800632 mAppSegmentConsumer->unlockBuffer(imgBuffer);
633 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800634 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800635 }
636 mInputAppSegmentBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800637 mAppSegmentFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800638 }
639
Shuzhen Wange8675782019-12-05 09:12:14 -0800640 while (!mInputYuvBuffers.empty() && !mYuvBufferAcquired && mMainImageFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800641 CpuConsumer::LockedBuffer imgBuffer;
642 auto it = mInputYuvBuffers.begin();
643 auto res = mMainImageConsumer->lockNextBuffer(&imgBuffer);
644 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700645 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800646 break;
647 } else if (res != OK) {
648 ALOGE("%s: Error locking YUV_888 image buffer: %s (%d)", __FUNCTION__,
649 strerror(-res), res);
650 mPendingInputFrames[*it].error = true;
651 mInputYuvBuffers.erase(it);
652 continue;
653 } else if (*it != imgBuffer.timestamp) {
654 ALOGW("%s: Expecting YUV_888 buffer with time stamp: %" PRId64 " received buffer with "
655 "time stamp: %" PRId64, __FUNCTION__, *it, imgBuffer.timestamp);
656 mPendingInputFrames[*it].error = true;
657 mInputYuvBuffers.erase(it);
658 continue;
659 }
660
Shuzhen Wange8675782019-12-05 09:12:14 -0800661 if (mPendingInputFrames.find(mMainImageFrameNumbers.front()) == mPendingInputFrames.end()) {
662 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
663 mMainImageFrameNumbers.front());
664 mInputYuvBuffers.erase(it);
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700665 mMainImageFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800666 continue;
667 }
668
669 int64_t frameNumber = mMainImageFrameNumbers.front();
670 // If mPendingInputFrames doesn't contain the expected frame number, the captured
671 // input main image must have been dropped via a buffer error. Simply
672 // return the buffer to the buffer queue.
673 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
674 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800675 mMainImageConsumer->unlockBuffer(imgBuffer);
676 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800677 mPendingInputFrames[frameNumber].yuvBuffer = imgBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800678 mYuvBufferAcquired = true;
679 }
680 mInputYuvBuffers.erase(it);
Shuzhen Wange8675782019-12-05 09:12:14 -0800681 mMainImageFrameNumbers.pop();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800682 }
683
684 while (!mCodecOutputBuffers.empty()) {
685 auto it = mCodecOutputBuffers.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800686 // Assume encoder input to output is FIFO, use a queue to look up
687 // frameNumber when handling codec outputs.
688 int64_t bufferFrameNumber = -1;
689 if (mCodecOutputBufferFrameNumbers.empty()) {
690 ALOGV("%s: Failed to find buffer frameNumber for codec output buffer!", __FUNCTION__);
Michael Gonzalez5c103f22019-10-08 14:30:32 -0700691 break;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800692 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800693 // Direct mapping between camera frame number and codec timestamp (in us).
694 bufferFrameNumber = mCodecOutputBufferFrameNumbers.front();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700695 mCodecOutputCounter++;
696 if (mCodecOutputCounter == mNumOutputTiles) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800697 mCodecOutputBufferFrameNumbers.pop();
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700698 mCodecOutputCounter = 0;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800699 }
700
Shuzhen Wange8675782019-12-05 09:12:14 -0800701 mPendingInputFrames[bufferFrameNumber].codecOutputBuffers.push_back(*it);
702 ALOGV("%s: [%" PRId64 "]: Pushing codecOutputBuffers (frameNumber %" PRId64 ")",
703 __FUNCTION__, bufferFrameNumber, it->timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800704 }
705 mCodecOutputBuffers.erase(it);
706 }
707
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800708 while (!mCaptureResults.empty()) {
709 auto it = mCaptureResults.begin();
Shuzhen Wange8675782019-12-05 09:12:14 -0800710 // Negative frame number indicates that something went wrong during the capture result
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800711 // collection process.
Shuzhen Wange8675782019-12-05 09:12:14 -0800712 int64_t frameNumber = std::get<0>(it->second);
713 if (it->first >= 0 &&
714 mPendingInputFrames.find(frameNumber) != mPendingInputFrames.end()) {
715 if (mPendingInputFrames[frameNumber].timestamp == it->first) {
716 mPendingInputFrames[frameNumber].result =
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800717 std::make_unique<CameraMetadata>(std::get<1>(it->second));
718 } else {
719 ALOGE("%s: Capture result frameNumber/timestamp mapping changed between "
Shuzhen Wange8675782019-12-05 09:12:14 -0800720 "shutter and capture result! before: %" PRId64 ", after: %" PRId64,
721 __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
722 it->first);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800723 }
724 }
725 mCaptureResults.erase(it);
726 }
727
728 // mErrorFrameNumbers stores frame number of dropped buffers.
729 auto it = mErrorFrameNumbers.begin();
730 while (it != mErrorFrameNumbers.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800731 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
732 mPendingInputFrames[*it].error = true;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800733 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800734 //Error callback is guaranteed to arrive after shutter notify, which
735 //results in mPendingInputFrames being populated.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800736 ALOGW("%s: Not able to find failing input with frame number: %" PRId64, __FUNCTION__,
737 *it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800738 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800739 it = mErrorFrameNumbers.erase(it);
740 }
741
742 // mExifErrorFrameNumbers stores the frame number of dropped APP_SEGMENT buffers
743 it = mExifErrorFrameNumbers.begin();
744 while (it != mExifErrorFrameNumbers.end()) {
745 if (mPendingInputFrames.find(*it) != mPendingInputFrames.end()) {
746 mPendingInputFrames[*it].exifError = true;
747 }
748 it = mExifErrorFrameNumbers.erase(it);
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800749 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800750
751 // Distribute codec input buffers to be filled out from YUV output
752 for (auto it = mPendingInputFrames.begin();
753 it != mPendingInputFrames.end() && mCodecInputBuffers.size() > 0; it++) {
754 InputFrame& inputFrame(it->second);
755 if (inputFrame.codecInputCounter < mGridRows * mGridCols) {
756 // Available input tiles that are required for the current input
757 // image.
758 size_t newInputTiles = std::min(mCodecInputBuffers.size(),
759 mGridRows * mGridCols - inputFrame.codecInputCounter);
760 for (size_t i = 0; i < newInputTiles; i++) {
761 CodecInputBufferInfo inputInfo =
762 { mCodecInputBuffers[0], mGridTimestampUs++, inputFrame.codecInputCounter };
763 inputFrame.codecInputBuffers.push_back(inputInfo);
764
765 mCodecInputBuffers.erase(mCodecInputBuffers.begin());
766 inputFrame.codecInputCounter++;
767 }
768 break;
769 }
770 }
771}
772
Shuzhen Wange8675782019-12-05 09:12:14 -0800773bool HeicCompositeStream::getNextReadyInputLocked(int64_t *frameNumber /*out*/) {
774 if (frameNumber == nullptr) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800775 return false;
776 }
777
778 bool newInputAvailable = false;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700779 for (auto& it : mPendingInputFrames) {
780 // New input is considered to be available only if:
781 // 1. input buffers are ready, or
782 // 2. App segment and muxer is created, or
783 // 3. A codec output tile is ready, and an output buffer is available.
784 // This makes sure that muxer gets created only when an output tile is
785 // generated, because right now we only handle 1 HEIC output buffer at a
786 // time (max dequeued buffer count is 1).
Shuzhen Wange8675782019-12-05 09:12:14 -0800787 bool appSegmentReady =
788 (it.second.appSegmentBuffer.data != nullptr || it.second.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700789 !it.second.appSegmentWritten && it.second.result != nullptr &&
790 it.second.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800791 bool codecOutputReady = !it.second.codecOutputBuffers.empty();
792 bool codecInputReady = (it.second.yuvBuffer.data != nullptr) &&
793 (!it.second.codecInputBuffers.empty());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700794 bool hasOutputBuffer = it.second.muxer != nullptr ||
795 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800796 if ((!it.second.error) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700797 (appSegmentReady || (codecOutputReady && hasOutputBuffer) || codecInputReady)) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800798 *frameNumber = it.first;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700799 if (it.second.format == nullptr && mFormat != nullptr) {
800 it.second.format = mFormat->dup();
801 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800802 newInputAvailable = true;
803 break;
804 }
805 }
806
807 return newInputAvailable;
808}
809
Shuzhen Wange8675782019-12-05 09:12:14 -0800810int64_t HeicCompositeStream::getNextFailingInputLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800811 int64_t res = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800812
813 for (const auto& it : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800814 if (it.second.error) {
815 res = it.first;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800816 break;
817 }
818 }
819
820 return res;
821}
822
Shuzhen Wange8675782019-12-05 09:12:14 -0800823status_t HeicCompositeStream::processInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800824 InputFrame &inputFrame) {
825 ATRACE_CALL();
826 status_t res = OK;
827
Shuzhen Wange8675782019-12-05 09:12:14 -0800828 bool appSegmentReady =
829 (inputFrame.appSegmentBuffer.data != nullptr || inputFrame.exifError) &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700830 !inputFrame.appSegmentWritten && inputFrame.result != nullptr &&
831 inputFrame.muxer != nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800832 bool codecOutputReady = inputFrame.codecOutputBuffers.size() > 0;
833 bool codecInputReady = inputFrame.yuvBuffer.data != nullptr &&
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700834 !inputFrame.codecInputBuffers.empty();
835 bool hasOutputBuffer = inputFrame.muxer != nullptr ||
836 (mDequeuedOutputBufferCnt < kMaxOutputSurfaceProducerCount);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800837
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700838 ALOGV("%s: [%" PRId64 "]: appSegmentReady %d, codecOutputReady %d, codecInputReady %d,"
Shuzhen Wange8675782019-12-05 09:12:14 -0800839 " dequeuedOutputBuffer %d, timestamp %" PRId64, __FUNCTION__, frameNumber,
840 appSegmentReady, codecOutputReady, codecInputReady, mDequeuedOutputBufferCnt,
841 inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800842
843 // Handle inputs for Hevc tiling
844 if (codecInputReady) {
845 res = processCodecInputFrame(inputFrame);
846 if (res != OK) {
847 ALOGE("%s: Failed to process codec input frame: %s (%d)", __FUNCTION__,
848 strerror(-res), res);
849 return res;
850 }
851 }
852
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700853 if (!(codecOutputReady && hasOutputBuffer) && !appSegmentReady) {
854 return OK;
855 }
856
857 // Initialize and start muxer if not yet done so. In this case,
858 // codecOutputReady must be true. Otherwise, appSegmentReady is guaranteed
859 // to be false, and the function must have returned early.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800860 if (inputFrame.muxer == nullptr) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800861 res = startMuxerForInputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800862 if (res != OK) {
863 ALOGE("%s: Failed to create and start muxer: %s (%d)", __FUNCTION__,
864 strerror(-res), res);
865 return res;
866 }
867 }
868
869 // Write JPEG APP segments data to the muxer.
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700870 if (appSegmentReady) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800871 res = processAppSegment(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800872 if (res != OK) {
873 ALOGE("%s: Failed to process JPEG APP segments: %s (%d)", __FUNCTION__,
874 strerror(-res), res);
875 return res;
876 }
877 }
878
879 // Write media codec bitstream buffers to muxer.
880 while (!inputFrame.codecOutputBuffers.empty()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800881 res = processOneCodecOutputFrame(frameNumber, inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800882 if (res != OK) {
883 ALOGE("%s: Failed to process codec output frame: %s (%d)", __FUNCTION__,
884 strerror(-res), res);
885 return res;
886 }
887 }
888
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700889 if (inputFrame.pendingOutputTiles == 0) {
890 if (inputFrame.appSegmentWritten) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800891 res = processCompletedInputFrame(frameNumber, inputFrame);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700892 if (res != OK) {
893 ALOGE("%s: Failed to process completed input frame: %s (%d)", __FUNCTION__,
894 strerror(-res), res);
895 return res;
896 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800897 }
898 }
899
900 return res;
901}
902
Shuzhen Wange8675782019-12-05 09:12:14 -0800903status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800904 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800905
906 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
907 if (res != OK) {
908 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
909 res);
910 return res;
911 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700912 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800913
914 // Combine current thread id, stream id and timestamp to uniquely identify image.
915 std::ostringstream tempOutputFile;
916 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800917 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800918 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
919 if (inputFrame.fileFd < 0) {
920 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
921 tempOutputFile.str().c_str(), errno);
922 return NO_INIT;
923 }
924 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
925 if (inputFrame.muxer == nullptr) {
926 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
927 __FUNCTION__, inputFrame.fileFd);
928 return NO_INIT;
929 }
930
931 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
932 if (res != OK) {
933 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
934 strerror(-res), res);
935 return res;
936 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800937
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700938 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800939 if (trackId < 0) {
940 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
941 return NO_INIT;
942 }
943
944 inputFrame.trackIndex = trackId;
945 inputFrame.pendingOutputTiles = mNumOutputTiles;
946
947 res = inputFrame.muxer->start();
948 if (res != OK) {
949 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
950 __FUNCTION__, strerror(-res), res);
951 return res;
952 }
953
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700954 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800955 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800956 return OK;
957}
958
Shuzhen Wange8675782019-12-05 09:12:14 -0800959status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800960 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800961 size_t appSegmentSize = 0;
962 if (!inputFrame.exifError) {
963 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
964 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
965 &app1Size);
966 if (appSegmentSize == 0) {
967 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
968 return NO_INIT;
969 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800970 }
971
972 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800973 auto exifRes = inputFrame.exifError ?
974 exifUtils->initializeEmpty() :
975 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800976 if (!exifRes) {
977 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
978 return BAD_VALUE;
979 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800980 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
981 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800982 if (!exifRes) {
983 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
984 return BAD_VALUE;
985 }
986 exifRes = exifUtils->setOrientation(inputFrame.orientation);
987 if (!exifRes) {
988 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
989 return BAD_VALUE;
990 }
991 exifRes = exifUtils->generateApp1();
992 if (!exifRes) {
993 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
994 return BAD_VALUE;
995 }
996
997 unsigned int newApp1Length = exifUtils->getApp1Length();
998 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
999
1000 //Assemble the APP1 marker buffer required by MediaCodec
1001 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1002 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1003 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1004 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1005 appSegmentSize - app1Size + newApp1Length;
1006 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1007 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1008 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1009 if (appSegmentSize - app1Size > 0) {
1010 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1011 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1012 }
1013
1014 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1015 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001016 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001017 delete[] appSegmentBuffer;
1018
1019 if (res != OK) {
1020 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1021 __FUNCTION__, strerror(-res), res);
1022 return res;
1023 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001024
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001025 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001026 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001027 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001028
1029 inputFrame.appSegmentWritten = true;
1030 // Release the buffer now so any pending input app segments can be processed
1031 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1032 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001033 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001034
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001035 return OK;
1036}
1037
1038status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1039 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1040 sp<MediaCodecBuffer> buffer;
1041 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1042 if (res != OK) {
1043 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1044 strerror(-res), res);
1045 return res;
1046 }
1047
1048 // Copy one tile from source to destination.
1049 size_t tileX = inputBuffer.tileIndex % mGridCols;
1050 size_t tileY = inputBuffer.tileIndex / mGridCols;
1051 size_t top = mGridHeight * tileY;
1052 size_t left = mGridWidth * tileX;
1053 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1054 mOutputWidth - tileX * mGridWidth : mGridWidth;
1055 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1056 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001057 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1058 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1059 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001060
1061 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1062 if (res != OK) {
1063 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1064 strerror(-res), res);
1065 return res;
1066 }
1067
1068 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1069 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1070 if (res != OK) {
1071 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1072 __FUNCTION__, strerror(-res), res);
1073 return res;
1074 }
1075 }
1076
1077 inputFrame.codecInputBuffers.clear();
1078 return OK;
1079}
1080
Shuzhen Wange8675782019-12-05 09:12:14 -08001081status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001082 InputFrame &inputFrame) {
1083 auto it = inputFrame.codecOutputBuffers.begin();
1084 sp<MediaCodecBuffer> buffer;
1085 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1086 if (res != OK) {
1087 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1088 __FUNCTION__, it->index, strerror(-res), res);
1089 return res;
1090 }
1091 if (buffer == nullptr) {
1092 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1093 __FUNCTION__, it->index);
1094 return BAD_VALUE;
1095 }
1096
1097 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1098 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001099 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001100 if (res != OK) {
1101 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1102 __FUNCTION__, it->index, strerror(-res), res);
1103 return res;
1104 }
1105
1106 mCodec->releaseOutputBuffer(it->index);
1107 if (inputFrame.pendingOutputTiles == 0) {
1108 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1109 } else {
1110 inputFrame.pendingOutputTiles--;
1111 }
1112
1113 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001114
1115 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001116 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001117 return OK;
1118}
1119
Shuzhen Wange8675782019-12-05 09:12:14 -08001120status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001121 InputFrame &inputFrame) {
1122 sp<ANativeWindow> outputANW = mOutputSurface;
1123 inputFrame.muxer->stop();
1124
1125 // Copy the content of the file to memory.
1126 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1127 void* dstBuffer;
1128 auto res = gb->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &dstBuffer, inputFrame.fenceFd);
1129 if (res != OK) {
1130 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1131 strerror(-res), res);
1132 return res;
1133 }
1134
1135 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1136 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1137 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1138 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1139 return BAD_VALUE;
1140 }
1141
1142 lseek(inputFrame.fileFd, 0, SEEK_SET);
1143 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1144 if (bytesRead < fSize) {
1145 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1146 return BAD_VALUE;
1147 }
1148
1149 close(inputFrame.fileFd);
1150 inputFrame.fileFd = -1;
1151
1152 // Fill in HEIC header
1153 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1154 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
1155 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
1156 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
1157 blobHeader->blobSize = fSize;
1158
Shuzhen Wange8675782019-12-05 09:12:14 -08001159 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001160 if (res != OK) {
1161 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1162 __FUNCTION__, getStreamId(), strerror(-res), res);
1163 return res;
1164 }
1165
1166 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1167 if (res != OK) {
1168 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1169 strerror(-res), res);
1170 return res;
1171 }
1172 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001173 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001174
Shuzhen Wange8675782019-12-05 09:12:14 -08001175 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1176 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001177 return OK;
1178}
1179
1180
Shuzhen Wange8675782019-12-05 09:12:14 -08001181void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1182 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001183 if (inputFrame == nullptr) {
1184 return;
1185 }
1186
1187 if (inputFrame->appSegmentBuffer.data != nullptr) {
1188 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1189 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001190 }
1191
1192 while (!inputFrame->codecOutputBuffers.empty()) {
1193 auto it = inputFrame->codecOutputBuffers.begin();
1194 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1195 mCodec->releaseOutputBuffer(it->index);
1196 inputFrame->codecOutputBuffers.erase(it);
1197 }
1198
1199 if (inputFrame->yuvBuffer.data != nullptr) {
1200 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1201 inputFrame->yuvBuffer.data = nullptr;
1202 mYuvBufferAcquired = false;
1203 }
1204
1205 while (!inputFrame->codecInputBuffers.empty()) {
1206 auto it = inputFrame->codecInputBuffers.begin();
1207 inputFrame->codecInputBuffers.erase(it);
1208 }
1209
Shuzhen Wange8675782019-12-05 09:12:14 -08001210 if (inputFrame->error || mErrorState) {
1211 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1212 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001213 }
1214
1215 if (inputFrame->fileFd >= 0) {
1216 close(inputFrame->fileFd);
1217 inputFrame->fileFd = -1;
1218 }
1219
1220 if (inputFrame->anb != nullptr) {
1221 sp<ANativeWindow> outputANW = mOutputSurface;
1222 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1223 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001224
1225 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001226 }
1227}
1228
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001229void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001230 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001231 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001232 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001233 auto& inputFrame = it->second;
1234 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001235 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1236 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001237 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001238 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001239 } else {
1240 it++;
1241 }
1242 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001243
1244 // Update codec quality based on first upcoming input frame.
1245 // Note that when encoding is in surface mode, currently there is no
1246 // way for camera service to synchronize quality setting on a per-frame
1247 // basis: we don't get notification when codec is ready to consume a new
1248 // input frame. So we update codec quality on a best-effort basis.
1249 if (inputFrameDone) {
1250 auto firstPendingFrame = mPendingInputFrames.begin();
1251 if (firstPendingFrame != mPendingInputFrames.end()) {
1252 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001253 } else {
1254 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001255 }
1256 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001257}
1258
1259status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1260 const sp<CameraDeviceBase>& cameraDevice) {
1261 ALOGV("%s", __FUNCTION__);
1262
1263 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001264 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001265 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001266 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001267 if (!isSizeSupported) {
1268 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1269 __FUNCTION__, width, height);
1270 return BAD_VALUE;
1271 }
1272
1273 // Create Looper for MediaCodec.
1274 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1275 mCodecLooper = new ALooper;
1276 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1277 status_t res = mCodecLooper->start(
1278 false, // runOnCallingThread
1279 false, // canCallJava
1280 PRIORITY_AUDIO);
1281 if (res != OK) {
1282 ALOGE("%s: Failed to start codec looper: %s (%d)",
1283 __FUNCTION__, strerror(-res), res);
1284 return NO_INIT;
1285 }
1286
1287 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001288 if (mUseHeic) {
1289 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1290 } else {
1291 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1292 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001293 if (mCodec == nullptr) {
1294 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1295 return NO_INIT;
1296 }
1297
1298 // Create Looper and handler for Codec callback.
1299 mCodecCallbackHandler = new CodecCallbackHandler(this);
1300 if (mCodecCallbackHandler == nullptr) {
1301 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1302 return NO_MEMORY;
1303 }
1304 mCallbackLooper = new ALooper;
1305 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1306 res = mCallbackLooper->start(
1307 false, // runOnCallingThread
1308 false, // canCallJava
1309 PRIORITY_AUDIO);
1310 if (res != OK) {
1311 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1312 __FUNCTION__, strerror(-res), res);
1313 return NO_INIT;
1314 }
1315 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1316
1317 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1318 res = mCodec->setCallback(mAsyncNotify);
1319 if (res != OK) {
1320 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1321 strerror(-res), res);
1322 return res;
1323 }
1324
1325 // Create output format and configure the Codec.
1326 sp<AMessage> outputFormat = new AMessage();
1327 outputFormat->setString(KEY_MIME, desiredMime);
1328 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1329 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1330 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001331 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001332
1333 int32_t gridWidth, gridHeight, gridRows, gridCols;
1334 if (useGrid || mUseHeic) {
1335 gridWidth = HeicEncoderInfoManager::kGridWidth;
1336 gridHeight = HeicEncoderInfoManager::kGridHeight;
1337 gridRows = (height + gridHeight - 1)/gridHeight;
1338 gridCols = (width + gridWidth - 1)/gridWidth;
1339
1340 if (mUseHeic) {
1341 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1342 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1343 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1344 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1345 }
1346
1347 } else {
1348 gridWidth = width;
1349 gridHeight = height;
1350 gridRows = 1;
1351 gridCols = 1;
1352 }
1353
1354 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1355 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1356 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1357 outputFormat->setInt32(KEY_COLOR_FORMAT,
1358 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001359 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001360 // This only serves as a hint to encoder when encoding is not real-time.
1361 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1362
1363 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1364 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1365 if (res != OK) {
1366 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1367 strerror(-res), res);
1368 return res;
1369 }
1370
1371 mGridWidth = gridWidth;
1372 mGridHeight = gridHeight;
1373 mGridRows = gridRows;
1374 mGridCols = gridCols;
1375 mUseGrid = useGrid;
1376 mOutputWidth = width;
1377 mOutputHeight = height;
1378 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
1379 mMaxHeicBufferSize = mOutputWidth * mOutputHeight * 3 / 2 + mAppSegmentMaxSize;
1380
1381 return OK;
1382}
1383
1384void HeicCompositeStream::deinitCodec() {
1385 ALOGV("%s", __FUNCTION__);
1386 if (mCodec != nullptr) {
1387 mCodec->stop();
1388 mCodec->release();
1389 mCodec.clear();
1390 }
1391
1392 if (mCodecLooper != nullptr) {
1393 mCodecLooper->stop();
1394 mCodecLooper.clear();
1395 }
1396
1397 if (mCallbackLooper != nullptr) {
1398 mCallbackLooper->stop();
1399 mCallbackLooper.clear();
1400 }
1401
1402 mAsyncNotify.clear();
1403 mFormat.clear();
1404}
1405
1406// Return the size of the complete list of app segment, 0 indicates failure
1407size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1408 size_t maxSize, size_t *app1SegmentSize) {
1409 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1410 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1411 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1412 return 0;
1413 }
1414
1415 size_t expectedSize = 0;
1416 // First check for EXIF transport header at the end of the buffer
1417 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1418 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1419 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1420 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1421 return 0;
1422 }
1423
1424 expectedSize = blob->blobSize;
1425 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1426 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1427 return 0;
1428 }
1429
1430 uint32_t totalSize = 0;
1431
1432 // Verify APP1 marker (mandatory)
1433 uint8_t app1Marker[] = {0xFF, 0xE1};
1434 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1435 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1436 appSegmentBuffer[0], appSegmentBuffer[1]);
1437 return 0;
1438 }
1439 totalSize += sizeof(app1Marker);
1440
1441 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1442 appSegmentBuffer[totalSize+1];
1443 totalSize += app1Size;
1444
1445 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1446 __FUNCTION__, expectedSize, app1Size);
1447 while (totalSize < expectedSize) {
1448 if (appSegmentBuffer[totalSize] != 0xFF ||
1449 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1450 appSegmentBuffer[totalSize+1] > 0xEF) {
1451 // Invalid APPn marker
1452 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1453 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1454 return 0;
1455 }
1456 totalSize += 2;
1457
1458 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1459 appSegmentBuffer[totalSize+1];
1460 totalSize += appnSize;
1461 }
1462
1463 if (totalSize != expectedSize) {
1464 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1465 __FUNCTION__, totalSize, expectedSize);
1466 return 0;
1467 }
1468
1469 *app1SegmentSize = app1Size + sizeof(app1Marker);
1470 return expectedSize;
1471}
1472
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001473status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1474 const CpuConsumer::LockedBuffer& yuvBuffer,
1475 size_t top, size_t left, size_t width, size_t height) {
1476 ATRACE_CALL();
1477
1478 // Get stride information for codecBuffer
1479 sp<ABuffer> imageData;
1480 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1481 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1482 return BAD_VALUE;
1483 }
1484 if (imageData->size() != sizeof(MediaImage2)) {
1485 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1486 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1487 return BAD_VALUE;
1488 }
1489 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1490 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1491 imageInfo->mBitDepth != 8 ||
1492 imageInfo->mBitDepthAllocated != 8 ||
1493 imageInfo->mNumPlanes != 3) {
1494 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1495 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1496 imageInfo->mType, imageInfo->mBitDepth,
1497 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1498 return BAD_VALUE;
1499 }
1500
1501 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1502 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1503 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1504 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1505 imageInfo->mPlane[MediaImage2::V].mOffset,
1506 imageInfo->mPlane[MediaImage2::U].mRowInc,
1507 imageInfo->mPlane[MediaImage2::V].mRowInc,
1508 imageInfo->mPlane[MediaImage2::U].mColInc,
1509 imageInfo->mPlane[MediaImage2::V].mColInc);
1510
1511 // Y
1512 for (auto row = top; row < top+height; row++) {
1513 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1514 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001515 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001516 }
1517
1518 // U is Cb, V is Cr
1519 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1520 imageInfo->mPlane[MediaImage2::U].mOffset;
1521 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1522 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1523 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1524 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1525 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1526 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1527 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1528 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1529 bool isCodecUvPlannar =
1530 ((codecUPlaneFirst && codecUvOffsetDiff >=
1531 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1532 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1533 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1534 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1535 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1536 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1537
1538 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1539 (codecUPlaneFirst == cameraUPlaneFirst)) {
1540 // UV semiplannar
1541 // The chrome plane could be either Cb first, or Cr first. Take the
1542 // smaller address.
1543 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1544 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1545 for (auto row = top/2; row < (top+height)/2; row++) {
1546 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1547 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001548 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001549 }
1550 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1551 // U plane
1552 for (auto row = top/2; row < (top+height)/2; row++) {
1553 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1554 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001555 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001556 }
1557
1558 // V plane
1559 for (auto row = top/2; row < (top+height)/2; row++) {
1560 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1561 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001562 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001563 }
1564 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001565 // Convert between semiplannar and plannar, or when UV orders are
1566 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001567 uint8_t *dst = codecBuffer->data();
1568 for (auto row = top/2; row < (top+height)/2; row++) {
1569 for (auto col = left/2; col < (left+width)/2; col++) {
1570 // U/Cb
1571 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1572 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1573 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1574 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1575 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1576
1577 // V/Cr
1578 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1579 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1580 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1581 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1582 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1583 }
1584 }
1585 }
1586 return OK;
1587}
1588
Shuzhen Wang219c2992019-02-15 17:24:28 -08001589void HeicCompositeStream::initCopyRowFunction(int32_t width)
1590{
1591 using namespace libyuv;
1592
1593 mFnCopyRow = CopyRow_C;
1594#if defined(HAS_COPYROW_SSE2)
1595 if (TestCpuFlag(kCpuHasSSE2)) {
1596 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1597 }
1598#endif
1599#if defined(HAS_COPYROW_AVX)
1600 if (TestCpuFlag(kCpuHasAVX)) {
1601 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1602 }
1603#endif
1604#if defined(HAS_COPYROW_ERMS)
1605 if (TestCpuFlag(kCpuHasERMS)) {
1606 mFnCopyRow = CopyRow_ERMS;
1607 }
1608#endif
1609#if defined(HAS_COPYROW_NEON)
1610 if (TestCpuFlag(kCpuHasNEON)) {
1611 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1612 }
1613#endif
1614#if defined(HAS_COPYROW_MIPS)
1615 if (TestCpuFlag(kCpuHasMIPS)) {
1616 mFnCopyRow = CopyRow_MIPS;
1617 }
1618#endif
1619}
1620
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001621size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1622 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1623 size_t maxAppsSegment = 1;
1624 if (entry.count > 0) {
1625 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1626 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1627 }
1628 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1629}
1630
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001631void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1632 if (quality != mQuality) {
1633 sp<AMessage> qualityParams = new AMessage;
1634 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1635 status_t res = mCodec->setParameters(qualityParams);
1636 if (res != OK) {
1637 ALOGE("%s: Failed to set codec quality: %s (%d)",
1638 __FUNCTION__, strerror(-res), res);
1639 } else {
1640 mQuality = quality;
1641 }
1642 }
1643}
1644
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001645bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001646 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001647 bool newInputAvailable = false;
1648
1649 {
1650 Mutex::Autolock l(mMutex);
1651 if (mErrorState) {
1652 // In case we landed in error state, return any pending buffers and
1653 // halt all further processing.
1654 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001655 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001656 return false;
1657 }
1658
1659
1660 while (!newInputAvailable) {
1661 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001662 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001663
1664 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001665 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001666 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001667 releaseInputFrameLocked(failingFrameNumber,
1668 &mPendingInputFrames[failingFrameNumber]);
1669
1670 // It's okay to remove the entry from mPendingInputFrames
1671 // because:
1672 // 1. Only one internal stream (main input) is critical in
1673 // backing the output stream.
1674 // 2. If captureResult/appSegment arrives after the entry is
1675 // removed, they are simply skipped.
1676 mPendingInputFrames.erase(failingFrameNumber);
1677 if (mPendingInputFrames.size() == 0) {
1678 markTrackerIdle();
1679 }
1680 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001681 }
1682
1683 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1684 if (ret == TIMED_OUT) {
1685 return true;
1686 } else if (ret != OK) {
1687 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1688 strerror(-ret), ret);
1689 return false;
1690 }
1691 }
1692 }
1693 }
1694
Shuzhen Wange8675782019-12-05 09:12:14 -08001695 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001696 Mutex::Autolock l(mMutex);
1697 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001698 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1699 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1700 frameNumber, strerror(-res), res);
1701 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001702 }
1703
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001704 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001705
1706 return true;
1707}
1708
Shuzhen Wange8675782019-12-05 09:12:14 -08001709void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1710 Mutex::Autolock l(mMutex);
1711 mExifErrorFrameNumbers.emplace(frameNumber);
1712 mInputReadyCondition.signal();
1713}
1714
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001715bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1716 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001717 int64_t frameNumber = resultExtras.frameNumber;
1718
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001719 // Buffer errors concerning internal composite streams should not be directly visible to
1720 // camera clients. They must only receive a single buffer error with the public composite
1721 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001722 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1723 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1724 flagAnExifErrorFrameNumber(frameNumber);
1725 res = true;
1726 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1727 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1728 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001729 res = true;
1730 }
1731
1732 return res;
1733}
1734
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001735void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1736 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1737 // simply skip using the capture result metadata to override EXIF.
1738 Mutex::Autolock l(mMutex);
1739
1740 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001741 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001742 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001743 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001744 break;
1745 }
1746 }
1747 if (timestamp == -1) {
1748 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001749 if (inputFrame.first == resultExtras.frameNumber) {
1750 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001751 break;
1752 }
1753 }
1754 }
1755
1756 if (timestamp == -1) {
1757 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1758 return;
1759 }
1760
1761 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001762 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1763 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001764 mInputReadyCondition.signal();
1765}
1766
Shuzhen Wange8675782019-12-05 09:12:14 -08001767void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1768 auto frameNumber = resultExtras.frameNumber;
1769 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1770 Mutex::Autolock l(mMutex);
1771 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1772 if (numRequests == 0) {
1773 // Pending request has been populated into mPendingInputFrames
1774 mErrorFrameNumbers.emplace(frameNumber);
1775 mInputReadyCondition.signal();
1776 } else {
1777 // REQUEST_ERROR was received without onShutter.
1778 }
1779}
1780
1781void HeicCompositeStream::markTrackerIdle() {
1782 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1783 if (statusTracker != nullptr) {
1784 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1785 ALOGV("%s: Mark component as idle", __FUNCTION__);
1786 }
1787}
1788
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001789void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1790 sp<HeicCompositeStream> parent = mParent.promote();
1791 if (parent == nullptr) return;
1792
1793 switch (msg->what()) {
1794 case kWhatCallbackNotify: {
1795 int32_t cbID;
1796 if (!msg->findInt32("callbackID", &cbID)) {
1797 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1798 break;
1799 }
1800
1801 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1802
1803 switch (cbID) {
1804 case MediaCodec::CB_INPUT_AVAILABLE: {
1805 int32_t index;
1806 if (!msg->findInt32("index", &index)) {
1807 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1808 break;
1809 }
1810 parent->onHeicInputFrameAvailable(index);
1811 break;
1812 }
1813
1814 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1815 int32_t index;
1816 size_t offset;
1817 size_t size;
1818 int64_t timeUs;
1819 int32_t flags;
1820
1821 if (!msg->findInt32("index", &index)) {
1822 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1823 break;
1824 }
1825 if (!msg->findSize("offset", &offset)) {
1826 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1827 break;
1828 }
1829 if (!msg->findSize("size", &size)) {
1830 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1831 break;
1832 }
1833 if (!msg->findInt64("timeUs", &timeUs)) {
1834 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1835 break;
1836 }
1837 if (!msg->findInt32("flags", &flags)) {
1838 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1839 break;
1840 }
1841
1842 CodecOutputBufferInfo bufferInfo = {
1843 index,
1844 (int32_t)offset,
1845 (int32_t)size,
1846 timeUs,
1847 (uint32_t)flags};
1848
1849 parent->onHeicOutputFrameAvailable(bufferInfo);
1850 break;
1851 }
1852
1853 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1854 sp<AMessage> format;
1855 if (!msg->findMessage("format", &format)) {
1856 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1857 break;
1858 }
Chong Zhang860eff12019-09-16 16:15:00 -07001859 // Here format is MediaCodec's internal copy of output format.
1860 // Make a copy since onHeicFormatChanged() might modify it.
1861 sp<AMessage> formatCopy;
1862 if (format != nullptr) {
1863 formatCopy = format->dup();
1864 }
1865 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001866 break;
1867 }
1868
1869 case MediaCodec::CB_ERROR: {
1870 status_t err;
1871 int32_t actionCode;
1872 AString detail;
1873 if (!msg->findInt32("err", &err)) {
1874 ALOGE("CB_ERROR: err is expected.");
1875 break;
1876 }
1877 if (!msg->findInt32("action", &actionCode)) {
1878 ALOGE("CB_ERROR: action is expected.");
1879 break;
1880 }
1881 msg->findString("detail", &detail);
1882 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1883 err, actionCode, detail.c_str());
1884
1885 parent->onHeicCodecError();
1886 break;
1887 }
1888
1889 default: {
1890 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1891 break;
1892 }
1893 }
1894 break;
1895 }
1896
1897 default:
1898 ALOGE("shouldn't be here");
1899 break;
1900 }
1901}
1902
1903}; // namespace camera3
1904}; // namespace android