blob: 582001dfe8b81081649a17c1c68cb789556ff82d [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"
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -080039#include "utils/SessionConfigurationUtils.h"
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080040#include "HeicEncoderInfoManager.h"
41#include "HeicCompositeStream.h"
42
43using android::hardware::camera::device::V3_5::CameraBlob;
44using android::hardware::camera::device::V3_5::CameraBlobId;
45
46namespace android {
47namespace camera3 {
48
Shuzhen Wange8675782019-12-05 09:12:14 -080049HeicCompositeStream::HeicCompositeStream(sp<CameraDeviceBase> device,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080050 wp<hardware::camera2::ICameraDeviceCallbacks> cb) :
51 CompositeStream(device, cb),
52 mUseHeic(false),
53 mNumOutputTiles(1),
54 mOutputWidth(0),
55 mOutputHeight(0),
56 mMaxHeicBufferSize(0),
57 mGridWidth(HeicEncoderInfoManager::kGridWidth),
58 mGridHeight(HeicEncoderInfoManager::kGridHeight),
59 mGridRows(1),
60 mGridCols(1),
61 mUseGrid(false),
62 mAppSegmentStreamId(-1),
63 mAppSegmentSurfaceId(-1),
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080064 mMainImageStreamId(-1),
65 mMainImageSurfaceId(-1),
66 mYuvBufferAcquired(false),
67 mProducerListener(new ProducerListener()),
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070068 mDequeuedOutputBufferCnt(0),
69 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,
Emilian Peevf4816702020-04-03 15:44:51 -0700118 camera_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800119 const std::unordered_set<int32_t> &sensorPixelModesUsed,
120 std::vector<int> *surfaceIds,
121 int /*streamSetId*/, bool /*isShared*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800122
123 sp<CameraDeviceBase> device = mDevice.promote();
124 if (!device.get()) {
125 ALOGE("%s: Invalid camera device!", __FUNCTION__);
126 return NO_INIT;
127 }
128
129 status_t res = initializeCodec(width, height, device);
130 if (res != OK) {
131 ALOGE("%s: Failed to initialize HEIC/HEVC codec: %s (%d)",
132 __FUNCTION__, strerror(-res), res);
133 return NO_INIT;
134 }
135
136 sp<IGraphicBufferProducer> producer;
137 sp<IGraphicBufferConsumer> consumer;
138 BufferQueue::createBufferQueue(&producer, &consumer);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700139 mAppSegmentConsumer = new CpuConsumer(consumer, kMaxAcquiredAppSegment);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800140 mAppSegmentConsumer->setFrameAvailableListener(this);
141 mAppSegmentConsumer->setName(String8("Camera3-HeicComposite-AppSegmentStream"));
142 mAppSegmentSurface = new Surface(producer);
143
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800144 mStaticInfo = device->info();
145
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800146 res = device->createStream(mAppSegmentSurface, mAppSegmentMaxSize, 1, format,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800147 kAppSegmentDataSpace, rotation, &mAppSegmentStreamId, physicalCameraId,
148 sensorPixelModesUsed,surfaceIds);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800149 if (res == OK) {
150 mAppSegmentSurfaceId = (*surfaceIds)[0];
151 } else {
152 ALOGE("%s: Failed to create JPEG App segment stream: %s (%d)", __FUNCTION__,
153 strerror(-res), res);
154 return res;
155 }
156
157 if (!mUseGrid) {
158 res = mCodec->createInputSurface(&producer);
159 if (res != OK) {
160 ALOGE("%s: Failed to create input surface for Heic codec: %s (%d)",
161 __FUNCTION__, strerror(-res), res);
162 return res;
163 }
164 } else {
165 BufferQueue::createBufferQueue(&producer, &consumer);
166 mMainImageConsumer = new CpuConsumer(consumer, 1);
167 mMainImageConsumer->setFrameAvailableListener(this);
168 mMainImageConsumer->setName(String8("Camera3-HeicComposite-HevcInputYUVStream"));
169 }
170 mMainImageSurface = new Surface(producer);
171
172 res = mCodec->start();
173 if (res != OK) {
174 ALOGE("%s: Failed to start codec: %s (%d)", __FUNCTION__,
175 strerror(-res), res);
176 return res;
177 }
178
179 std::vector<int> sourceSurfaceId;
180 //Use YUV_888 format if framework tiling is needed.
181 int srcStreamFmt = mUseGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
182 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
183 res = device->createStream(mMainImageSurface, width, height, srcStreamFmt, kHeifDataSpace,
Jayant Chowdhary13f9b2f2020-12-02 22:46:15 -0800184 rotation, id, physicalCameraId, sensorPixelModesUsed, &sourceSurfaceId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800185 if (res == OK) {
186 mMainImageSurfaceId = sourceSurfaceId[0];
187 mMainImageStreamId = *id;
188 } else {
189 ALOGE("%s: Failed to create main image stream: %s (%d)", __FUNCTION__,
190 strerror(-res), res);
191 return res;
192 }
193
194 mOutputSurface = consumers[0];
Shuzhen Wange8675782019-12-05 09:12:14 -0800195 res = registerCompositeStreamListener(mMainImageStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800196 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800197 ALOGE("%s: Failed to register HAL main image stream: %s (%d)", __FUNCTION__,
198 strerror(-res), res);
199 return res;
200 }
201
202 res = registerCompositeStreamListener(mAppSegmentStreamId);
203 if (res != OK) {
204 ALOGE("%s: Failed to register HAL app segment stream: %s (%d)", __FUNCTION__,
205 strerror(-res), res);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800206 return res;
207 }
208
Shuzhen Wang219c2992019-02-15 17:24:28 -0800209 initCopyRowFunction(width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800210 return res;
211}
212
213status_t HeicCompositeStream::deleteInternalStreams() {
214 requestExit();
215 auto res = join();
216 if (res != OK) {
217 ALOGE("%s: Failed to join with the main processing thread: %s (%d)", __FUNCTION__,
218 strerror(-res), res);
219 }
220
221 deinitCodec();
222
223 if (mAppSegmentStreamId >= 0) {
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700224 // Camera devices may not be valid after switching to offline mode.
225 // In this case, all offline streams including internal composite streams
226 // are managed and released by the offline session.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800227 sp<CameraDeviceBase> device = mDevice.promote();
Emilian Peevc0fe54c2020-03-11 14:05:07 -0700228 if (device.get() != nullptr) {
229 res = device->deleteStream(mAppSegmentStreamId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800230 }
231
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800232 mAppSegmentStreamId = -1;
233 }
234
Shuzhen Wang2c545042019-02-07 10:27:35 -0800235 if (mOutputSurface != nullptr) {
236 mOutputSurface->disconnect(NATIVE_WINDOW_API_CAMERA);
237 mOutputSurface.clear();
238 }
Shuzhen Wange8675782019-12-05 09:12:14 -0800239
240 sp<StatusTracker> statusTracker = mStatusTracker.promote();
241 if (statusTracker != nullptr && mStatusId != StatusTracker::NO_STATUS_ID) {
242 statusTracker->removeComponent(mStatusId);
243 mStatusId = StatusTracker::NO_STATUS_ID;
244 }
245
246 if (mPendingInputFrames.size() > 0) {
247 ALOGW("%s: mPendingInputFrames has %zu stale entries",
248 __FUNCTION__, mPendingInputFrames.size());
249 mPendingInputFrames.clear();
250 }
251
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800252 return res;
253}
254
255void HeicCompositeStream::onBufferReleased(const BufferInfo& bufferInfo) {
256 Mutex::Autolock l(mMutex);
257
258 if (bufferInfo.mError) return;
259
Shuzhen Wange8675782019-12-05 09:12:14 -0800260 if (bufferInfo.mStreamId == mMainImageStreamId) {
261 mMainImageFrameNumbers.push(bufferInfo.mFrameNumber);
262 mCodecOutputBufferFrameNumbers.push(bufferInfo.mFrameNumber);
263 ALOGV("%s: [%" PRId64 "]: Adding main image frame number (%zu frame numbers in total)",
264 __FUNCTION__, bufferInfo.mFrameNumber, mMainImageFrameNumbers.size());
265 } else if (bufferInfo.mStreamId == mAppSegmentStreamId) {
266 mAppSegmentFrameNumbers.push(bufferInfo.mFrameNumber);
267 ALOGV("%s: [%" PRId64 "]: Adding app segment frame number (%zu frame numbers in total)",
268 __FUNCTION__, bufferInfo.mFrameNumber, mAppSegmentFrameNumbers.size());
269 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800270}
271
272// We need to get the settings early to handle the case where the codec output
273// arrives earlier than result metadata.
274void HeicCompositeStream::onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
275 const CameraMetadata& settings) {
276 ATRACE_ASYNC_BEGIN("HEIC capture", frameNumber);
277
278 Mutex::Autolock l(mMutex);
279 if (mErrorState || (streamId != getStreamId())) {
280 return;
281 }
282
283 mPendingCaptureResults.emplace(frameNumber, CameraMetadata());
284
285 camera_metadata_ro_entry entry;
286
287 int32_t orientation = 0;
288 entry = settings.find(ANDROID_JPEG_ORIENTATION);
289 if (entry.count == 1) {
290 orientation = entry.data.i32[0];
291 }
292
293 int32_t quality = kDefaultJpegQuality;
294 entry = settings.find(ANDROID_JPEG_QUALITY);
295 if (entry.count == 1) {
296 quality = entry.data.i32[0];
297 }
298
Shuzhen Wange8675782019-12-05 09:12:14 -0800299 mSettingsByFrameNumber[frameNumber] = {orientation, quality};
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800300}
301
302void HeicCompositeStream::onFrameAvailable(const BufferItem& item) {
303 if (item.mDataSpace == static_cast<android_dataspace>(kAppSegmentDataSpace)) {
304 ALOGV("%s: JPEG APP segments buffer with ts: %" PRIu64 " ms. arrived!",
305 __func__, ns2ms(item.mTimestamp));
306
307 Mutex::Autolock l(mMutex);
308 if (!mErrorState) {
309 mInputAppSegmentBuffers.push_back(item.mTimestamp);
310 mInputReadyCondition.signal();
311 }
312 } else if (item.mDataSpace == kHeifDataSpace) {
313 ALOGV("%s: YUV_888 buffer with ts: %" PRIu64 " ms. arrived!",
314 __func__, ns2ms(item.mTimestamp));
315
316 Mutex::Autolock l(mMutex);
317 if (!mUseGrid) {
318 ALOGE("%s: YUV_888 internal stream is only supported for HEVC tiling",
319 __FUNCTION__);
320 return;
321 }
322 if (!mErrorState) {
323 mInputYuvBuffers.push_back(item.mTimestamp);
324 mInputReadyCondition.signal();
325 }
326 } else {
327 ALOGE("%s: Unexpected data space: 0x%x", __FUNCTION__, item.mDataSpace);
328 }
329}
330
331status_t HeicCompositeStream::getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
332 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/) {
333 if (compositeOutput == nullptr) {
334 return BAD_VALUE;
335 }
336
337 compositeOutput->clear();
338
339 bool useGrid, useHeic;
340 bool isSizeSupported = isSizeSupportedByHeifEncoder(
341 streamInfo.width, streamInfo.height, &useHeic, &useGrid, nullptr);
342 if (!isSizeSupported) {
343 // Size is not supported by either encoder.
344 return OK;
345 }
346
347 compositeOutput->insert(compositeOutput->end(), 2, streamInfo);
348
349 // JPEG APPS segments Blob stream info
350 (*compositeOutput)[0].width = calcAppSegmentMaxSize(ch);
351 (*compositeOutput)[0].height = 1;
352 (*compositeOutput)[0].format = HAL_PIXEL_FORMAT_BLOB;
353 (*compositeOutput)[0].dataSpace = kAppSegmentDataSpace;
354 (*compositeOutput)[0].consumerUsage = GRALLOC_USAGE_SW_READ_OFTEN;
355
356 // YUV/IMPLEMENTATION_DEFINED stream info
357 (*compositeOutput)[1].width = streamInfo.width;
358 (*compositeOutput)[1].height = streamInfo.height;
359 (*compositeOutput)[1].format = useGrid ? HAL_PIXEL_FORMAT_YCbCr_420_888 :
360 HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
361 (*compositeOutput)[1].dataSpace = kHeifDataSpace;
362 (*compositeOutput)[1].consumerUsage = useHeic ? GRALLOC_USAGE_HW_IMAGE_ENCODER :
363 useGrid ? GRALLOC_USAGE_SW_READ_OFTEN : GRALLOC_USAGE_HW_VIDEO_ENCODER;
364
365 return NO_ERROR;
366}
367
368bool HeicCompositeStream::isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -0700369 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800370 static HeicEncoderInfoManager& heicManager = HeicEncoderInfoManager::getInstance();
Chong Zhang688abaa2019-05-17 16:32:23 -0700371 return heicManager.isSizeSupported(width, height, useHeic, useGrid, stall, hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800372}
373
374bool HeicCompositeStream::isInMemoryTempFileSupported() {
375 int memfd = syscall(__NR_memfd_create, "HEIF-try-memfd", MFD_CLOEXEC);
376 if (memfd == -1) {
377 if (errno != ENOSYS) {
378 ALOGE("%s: Failed to create tmpfs file. errno %d", __FUNCTION__, errno);
379 }
380 return false;
381 }
382 close(memfd);
383 return true;
384}
385
386void HeicCompositeStream::onHeicOutputFrameAvailable(
387 const CodecOutputBufferInfo& outputBufferInfo) {
388 Mutex::Autolock l(mMutex);
389
390 ALOGV("%s: index %d, offset %d, size %d, time %" PRId64 ", flags 0x%x",
391 __FUNCTION__, outputBufferInfo.index, outputBufferInfo.offset,
392 outputBufferInfo.size, outputBufferInfo.timeUs, outputBufferInfo.flags);
393
394 if (!mErrorState) {
395 if ((outputBufferInfo.size > 0) &&
396 ((outputBufferInfo.flags & MediaCodec::BUFFER_FLAG_CODECCONFIG) == 0)) {
397 mCodecOutputBuffers.push_back(outputBufferInfo);
398 mInputReadyCondition.signal();
399 } else {
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700400 ALOGV("%s: Releasing output buffer: size %d flags: 0x%x ", __FUNCTION__,
401 outputBufferInfo.size, outputBufferInfo.flags);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800402 mCodec->releaseOutputBuffer(outputBufferInfo.index);
403 }
404 } else {
405 mCodec->releaseOutputBuffer(outputBufferInfo.index);
406 }
407}
408
409void HeicCompositeStream::onHeicInputFrameAvailable(int32_t index) {
410 Mutex::Autolock l(mMutex);
411
412 if (!mUseGrid) {
413 ALOGE("%s: Codec YUV input mode must only be used for Hevc tiling mode", __FUNCTION__);
414 return;
415 }
416
417 mCodecInputBuffers.push_back(index);
418 mInputReadyCondition.signal();
419}
420
421void HeicCompositeStream::onHeicFormatChanged(sp<AMessage>& newFormat) {
422 if (newFormat == nullptr) {
423 ALOGE("%s: newFormat must not be null!", __FUNCTION__);
424 return;
425 }
426
427 Mutex::Autolock l(mMutex);
428
429 AString mime;
430 AString mimeHeic(MIMETYPE_IMAGE_ANDROID_HEIC);
431 newFormat->findString(KEY_MIME, &mime);
432 if (mime != mimeHeic) {
433 // For HEVC codec, below keys need to be filled out or overwritten so that the
434 // muxer can handle them as HEIC output image.
435 newFormat->setString(KEY_MIME, mimeHeic);
436 newFormat->setInt32(KEY_WIDTH, mOutputWidth);
437 newFormat->setInt32(KEY_HEIGHT, mOutputHeight);
438 if (mUseGrid) {
439 newFormat->setInt32(KEY_TILE_WIDTH, mGridWidth);
440 newFormat->setInt32(KEY_TILE_HEIGHT, mGridHeight);
441 newFormat->setInt32(KEY_GRID_ROWS, mGridRows);
442 newFormat->setInt32(KEY_GRID_COLUMNS, mGridCols);
443 }
444 }
445 newFormat->setInt32(KEY_IS_DEFAULT, 1 /*isPrimary*/);
446
447 int32_t gridRows, gridCols;
448 if (newFormat->findInt32(KEY_GRID_ROWS, &gridRows) &&
449 newFormat->findInt32(KEY_GRID_COLUMNS, &gridCols)) {
450 mNumOutputTiles = gridRows * gridCols;
451 } else {
452 mNumOutputTiles = 1;
453 }
454
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800455 mFormat = newFormat;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700456
457 ALOGV("%s: mNumOutputTiles is %zu", __FUNCTION__, mNumOutputTiles);
458 mInputReadyCondition.signal();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800459}
460
461void HeicCompositeStream::onHeicCodecError() {
462 Mutex::Autolock l(mMutex);
463 mErrorState = true;
464}
465
466status_t HeicCompositeStream::configureStream() {
467 if (isRunning()) {
468 // Processing thread is already running, nothing more to do.
469 return NO_ERROR;
470 }
471
472 if (mOutputSurface.get() == nullptr) {
473 ALOGE("%s: No valid output surface set!", __FUNCTION__);
474 return NO_INIT;
475 }
476
477 auto res = mOutputSurface->connect(NATIVE_WINDOW_API_CAMERA, mProducerListener);
478 if (res != OK) {
479 ALOGE("%s: Unable to connect to native window for stream %d",
480 __FUNCTION__, mMainImageStreamId);
481 return res;
482 }
483
484 if ((res = native_window_set_buffers_format(mOutputSurface.get(), HAL_PIXEL_FORMAT_BLOB))
485 != OK) {
486 ALOGE("%s: Unable to configure stream buffer format for stream %d", __FUNCTION__,
487 mMainImageStreamId);
488 return res;
489 }
490
491 ANativeWindow *anwConsumer = mOutputSurface.get();
492 int maxConsumerBuffers;
493 if ((res = anwConsumer->query(anwConsumer, NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS,
494 &maxConsumerBuffers)) != OK) {
495 ALOGE("%s: Unable to query consumer undequeued"
496 " buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
497 return res;
498 }
499
500 // Cannot use SourceSurface buffer count since it could be codec's 512*512 tile
501 // buffer count.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800502 if ((res = native_window_set_buffer_count(
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700503 anwConsumer, kMaxOutputSurfaceProducerCount + maxConsumerBuffers)) != OK) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800504 ALOGE("%s: Unable to set buffer count for stream %d", __FUNCTION__, mMainImageStreamId);
505 return res;
506 }
507
508 if ((res = native_window_set_buffers_dimensions(anwConsumer, mMaxHeicBufferSize, 1)) != OK) {
509 ALOGE("%s: Unable to set buffer dimension %zu x 1 for stream %d: %s (%d)",
510 __FUNCTION__, mMaxHeicBufferSize, mMainImageStreamId, strerror(-res), res);
511 return res;
512 }
513
Shuzhen Wange8675782019-12-05 09:12:14 -0800514 sp<camera3::StatusTracker> statusTracker = mStatusTracker.promote();
515 if (statusTracker != nullptr) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700516 std::string name = std::string("HeicStream ") + std::to_string(getStreamId());
517 mStatusId = statusTracker->addComponent(name);
Shuzhen Wange8675782019-12-05 09:12:14 -0800518 }
519
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800520 run("HeicCompositeStreamProc");
521
522 return NO_ERROR;
523}
524
525status_t HeicCompositeStream::insertGbp(SurfaceMap* /*out*/outSurfaceMap,
526 Vector<int32_t>* /*out*/outputStreamIds, int32_t* /*out*/currentStreamId) {
527 if (outSurfaceMap->find(mAppSegmentStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800528 outputStreamIds->push_back(mAppSegmentStreamId);
529 }
530 (*outSurfaceMap)[mAppSegmentStreamId].push_back(mAppSegmentSurfaceId);
531
532 if (outSurfaceMap->find(mMainImageStreamId) == outSurfaceMap->end()) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800533 outputStreamIds->push_back(mMainImageStreamId);
534 }
535 (*outSurfaceMap)[mMainImageStreamId].push_back(mMainImageSurfaceId);
536
537 if (currentStreamId != nullptr) {
538 *currentStreamId = mMainImageStreamId;
539 }
540
541 return NO_ERROR;
542}
543
Emilian Peev4697b642019-11-19 17:11:14 -0800544status_t HeicCompositeStream::insertCompositeStreamIds(
545 std::vector<int32_t>* compositeStreamIds /*out*/) {
546 if (compositeStreamIds == nullptr) {
547 return BAD_VALUE;
548 }
549
550 compositeStreamIds->push_back(mAppSegmentStreamId);
551 compositeStreamIds->push_back(mMainImageStreamId);
552
553 return OK;
554}
555
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800556void HeicCompositeStream::onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) {
557 Mutex::Autolock l(mMutex);
558 if (mErrorState) {
559 return;
560 }
561
562 if (mSettingsByFrameNumber.find(resultExtras.frameNumber) != mSettingsByFrameNumber.end()) {
Shuzhen Wange8675782019-12-05 09:12:14 -0800563 ALOGV("%s: [%" PRId64 "]: timestamp %" PRId64 ", requestId %d", __FUNCTION__,
564 resultExtras.frameNumber, timestamp, resultExtras.requestId);
565 mSettingsByFrameNumber[resultExtras.frameNumber].shutterNotified = true;
566 mSettingsByFrameNumber[resultExtras.frameNumber].timestamp = timestamp;
567 mSettingsByFrameNumber[resultExtras.frameNumber].requestId = resultExtras.requestId;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800568 mInputReadyCondition.signal();
569 }
570}
571
572void HeicCompositeStream::compilePendingInputLocked() {
Shuzhen Wange8675782019-12-05 09:12:14 -0800573 auto i = mSettingsByFrameNumber.begin();
574 while (i != mSettingsByFrameNumber.end()) {
575 if (i->second.shutterNotified) {
576 mPendingInputFrames[i->first].orientation = i->second.orientation;
577 mPendingInputFrames[i->first].quality = i->second.quality;
578 mPendingInputFrames[i->first].timestamp = i->second.timestamp;
579 mPendingInputFrames[i->first].requestId = i->second.requestId;
580 ALOGV("%s: [%" PRId64 "]: timestamp is %" PRId64, __FUNCTION__,
581 i->first, i->second.timestamp);
582 i = mSettingsByFrameNumber.erase(i);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700583
Shuzhen Wange8675782019-12-05 09:12:14 -0800584 // Set encoder quality if no inflight encoding
585 if (mPendingInputFrames.size() == 1) {
586 sp<StatusTracker> statusTracker = mStatusTracker.promote();
587 if (statusTracker != nullptr) {
588 statusTracker->markComponentActive(mStatusId);
589 ALOGV("%s: Mark component as active", __FUNCTION__);
590 }
591
592 int32_t newQuality = mPendingInputFrames.begin()->second.quality;
593 updateCodecQualityLocked(newQuality);
594 }
595 } else {
596 i++;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700597 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800598 }
599
Shuzhen Wange8675782019-12-05 09:12:14 -0800600 while (!mInputAppSegmentBuffers.empty() && mAppSegmentFrameNumbers.size() > 0) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800601 CpuConsumer::LockedBuffer imgBuffer;
602 auto it = mInputAppSegmentBuffers.begin();
603 auto res = mAppSegmentConsumer->lockNextBuffer(&imgBuffer);
604 if (res == NOT_ENOUGH_DATA) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700605 // Can not lock any more buffers.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800606 break;
607 } else if ((res != OK) || (*it != imgBuffer.timestamp)) {
608 if (res != OK) {
609 ALOGE("%s: Error locking JPEG_APP_SEGMENTS image buffer: %s (%d)", __FUNCTION__,
610 strerror(-res), res);
611 } else {
612 ALOGE("%s: Expecting JPEG_APP_SEGMENTS buffer with time stamp: %" PRId64
613 " received buffer with time stamp: %" PRId64, __FUNCTION__,
614 *it, imgBuffer.timestamp);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700615 mAppSegmentConsumer->unlockBuffer(imgBuffer);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800616 }
617 mPendingInputFrames[*it].error = true;
618 mInputAppSegmentBuffers.erase(it);
619 continue;
620 }
621
Shuzhen Wange8675782019-12-05 09:12:14 -0800622 if (mPendingInputFrames.find(mAppSegmentFrameNumbers.front()) == mPendingInputFrames.end()) {
623 ALOGE("%s: mPendingInputFrames doesn't contain frameNumber %" PRId64, __FUNCTION__,
624 mAppSegmentFrameNumbers.front());
Shuzhen Wang991b7b62020-06-17 11:39:11 -0700625 mInputAppSegmentBuffers.erase(it);
626 mAppSegmentFrameNumbers.pop();
Shuzhen Wange8675782019-12-05 09:12:14 -0800627 continue;
628 }
629
630 int64_t frameNumber = mAppSegmentFrameNumbers.front();
631 // If mPendingInputFrames doesn't contain the expected frame number, the captured
632 // input app segment frame must have been dropped via a buffer error. Simply
633 // return the buffer to the buffer queue.
634 if ((mPendingInputFrames.find(frameNumber) == mPendingInputFrames.end()) ||
635 (mPendingInputFrames[frameNumber].error)) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800636 mAppSegmentConsumer->unlockBuffer(imgBuffer);
637 } else {
Shuzhen Wange8675782019-12-05 09:12:14 -0800638 mPendingInputFrames[frameNumber].appSegmentBuffer = imgBuffer;
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 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800901 }
902 }
903
904 return res;
905}
906
Shuzhen Wange8675782019-12-05 09:12:14 -0800907status_t HeicCompositeStream::startMuxerForInputFrame(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800908 sp<ANativeWindow> outputANW = mOutputSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800909
910 auto res = outputANW->dequeueBuffer(mOutputSurface.get(), &inputFrame.anb, &inputFrame.fenceFd);
911 if (res != OK) {
912 ALOGE("%s: Error retrieving output buffer: %s (%d)", __FUNCTION__, strerror(-res),
913 res);
914 return res;
915 }
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700916 mDequeuedOutputBufferCnt++;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800917
918 // Combine current thread id, stream id and timestamp to uniquely identify image.
919 std::ostringstream tempOutputFile;
920 tempOutputFile << "HEIF-" << pthread_self() << "-"
Shuzhen Wange8675782019-12-05 09:12:14 -0800921 << getStreamId() << "-" << frameNumber;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800922 inputFrame.fileFd = syscall(__NR_memfd_create, tempOutputFile.str().c_str(), MFD_CLOEXEC);
923 if (inputFrame.fileFd < 0) {
924 ALOGE("%s: Failed to create file %s. Error no is %d", __FUNCTION__,
925 tempOutputFile.str().c_str(), errno);
926 return NO_INIT;
927 }
928 inputFrame.muxer = new MediaMuxer(inputFrame.fileFd, MediaMuxer::OUTPUT_FORMAT_HEIF);
929 if (inputFrame.muxer == nullptr) {
930 ALOGE("%s: Failed to create MediaMuxer for file fd %d",
931 __FUNCTION__, inputFrame.fileFd);
932 return NO_INIT;
933 }
934
935 res = inputFrame.muxer->setOrientationHint(inputFrame.orientation);
936 if (res != OK) {
937 ALOGE("%s: Failed to setOrientationHint: %s (%d)", __FUNCTION__,
938 strerror(-res), res);
939 return res;
940 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800941
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700942 ssize_t trackId = inputFrame.muxer->addTrack(inputFrame.format);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800943 if (trackId < 0) {
944 ALOGE("%s: Failed to addTrack to the muxer: %zd", __FUNCTION__, trackId);
945 return NO_INIT;
946 }
947
948 inputFrame.trackIndex = trackId;
949 inputFrame.pendingOutputTiles = mNumOutputTiles;
950
951 res = inputFrame.muxer->start();
952 if (res != OK) {
953 ALOGE("%s: Failed to start MediaMuxer: %s (%d)",
954 __FUNCTION__, strerror(-res), res);
955 return res;
956 }
957
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700958 ALOGV("%s: [%" PRId64 "]: Muxer started for inputFrame", __FUNCTION__,
Shuzhen Wange8675782019-12-05 09:12:14 -0800959 frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800960 return OK;
961}
962
Shuzhen Wange8675782019-12-05 09:12:14 -0800963status_t HeicCompositeStream::processAppSegment(int64_t frameNumber, InputFrame &inputFrame) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800964 size_t app1Size = 0;
Shuzhen Wange8675782019-12-05 09:12:14 -0800965 size_t appSegmentSize = 0;
966 if (!inputFrame.exifError) {
967 appSegmentSize = findAppSegmentsSize(inputFrame.appSegmentBuffer.data,
968 inputFrame.appSegmentBuffer.width * inputFrame.appSegmentBuffer.height,
969 &app1Size);
970 if (appSegmentSize == 0) {
971 ALOGE("%s: Failed to find JPEG APP segment size", __FUNCTION__);
972 return NO_INIT;
973 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800974 }
975
976 std::unique_ptr<ExifUtils> exifUtils(ExifUtils::create());
Shuzhen Wange8675782019-12-05 09:12:14 -0800977 auto exifRes = inputFrame.exifError ?
978 exifUtils->initializeEmpty() :
979 exifUtils->initialize(inputFrame.appSegmentBuffer.data, app1Size);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800980 if (!exifRes) {
981 ALOGE("%s: Failed to initialize ExifUtils object!", __FUNCTION__);
982 return BAD_VALUE;
983 }
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800984 exifRes = exifUtils->setFromMetadata(*inputFrame.result, mStaticInfo,
985 mOutputWidth, mOutputHeight);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800986 if (!exifRes) {
987 ALOGE("%s: Failed to set Exif tags using metadata and main image sizes", __FUNCTION__);
988 return BAD_VALUE;
989 }
990 exifRes = exifUtils->setOrientation(inputFrame.orientation);
991 if (!exifRes) {
992 ALOGE("%s: ExifUtils failed to set orientation", __FUNCTION__);
993 return BAD_VALUE;
994 }
995 exifRes = exifUtils->generateApp1();
996 if (!exifRes) {
997 ALOGE("%s: ExifUtils failed to generate APP1 segment", __FUNCTION__);
998 return BAD_VALUE;
999 }
1000
1001 unsigned int newApp1Length = exifUtils->getApp1Length();
1002 const uint8_t *newApp1Segment = exifUtils->getApp1Buffer();
1003
1004 //Assemble the APP1 marker buffer required by MediaCodec
1005 uint8_t kExifApp1Marker[] = {'E', 'x', 'i', 'f', 0xFF, 0xE1, 0x00, 0x00};
1006 kExifApp1Marker[6] = static_cast<uint8_t>(newApp1Length >> 8);
1007 kExifApp1Marker[7] = static_cast<uint8_t>(newApp1Length & 0xFF);
1008 size_t appSegmentBufferSize = sizeof(kExifApp1Marker) +
1009 appSegmentSize - app1Size + newApp1Length;
1010 uint8_t* appSegmentBuffer = new uint8_t[appSegmentBufferSize];
1011 memcpy(appSegmentBuffer, kExifApp1Marker, sizeof(kExifApp1Marker));
1012 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker), newApp1Segment, newApp1Length);
1013 if (appSegmentSize - app1Size > 0) {
1014 memcpy(appSegmentBuffer + sizeof(kExifApp1Marker) + newApp1Length,
1015 inputFrame.appSegmentBuffer.data + app1Size, appSegmentSize - app1Size);
1016 }
1017
1018 sp<ABuffer> aBuffer = new ABuffer(appSegmentBuffer, appSegmentBufferSize);
1019 auto res = inputFrame.muxer->writeSampleData(aBuffer, inputFrame.trackIndex,
Shuzhen Wange8675782019-12-05 09:12:14 -08001020 inputFrame.timestamp, MediaCodec::BUFFER_FLAG_MUXER_DATA);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001021 delete[] appSegmentBuffer;
1022
1023 if (res != OK) {
1024 ALOGE("%s: Failed to write JPEG APP segments to muxer: %s (%d)",
1025 __FUNCTION__, strerror(-res), res);
1026 return res;
1027 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001028
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001029 ALOGV("%s: [%" PRId64 "]: appSegmentSize is %zu, width %d, height %d, app1Size %zu",
Shuzhen Wange8675782019-12-05 09:12:14 -08001030 __FUNCTION__, frameNumber, appSegmentSize, inputFrame.appSegmentBuffer.width,
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001031 inputFrame.appSegmentBuffer.height, app1Size);
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001032
1033 inputFrame.appSegmentWritten = true;
1034 // Release the buffer now so any pending input app segments can be processed
1035 mAppSegmentConsumer->unlockBuffer(inputFrame.appSegmentBuffer);
1036 inputFrame.appSegmentBuffer.data = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001037 inputFrame.exifError = false;
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001038
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001039 return OK;
1040}
1041
1042status_t HeicCompositeStream::processCodecInputFrame(InputFrame &inputFrame) {
1043 for (auto& inputBuffer : inputFrame.codecInputBuffers) {
1044 sp<MediaCodecBuffer> buffer;
1045 auto res = mCodec->getInputBuffer(inputBuffer.index, &buffer);
1046 if (res != OK) {
1047 ALOGE("%s: Error getting codec input buffer: %s (%d)", __FUNCTION__,
1048 strerror(-res), res);
1049 return res;
1050 }
1051
1052 // Copy one tile from source to destination.
1053 size_t tileX = inputBuffer.tileIndex % mGridCols;
1054 size_t tileY = inputBuffer.tileIndex / mGridCols;
1055 size_t top = mGridHeight * tileY;
1056 size_t left = mGridWidth * tileX;
1057 size_t width = (tileX == static_cast<size_t>(mGridCols) - 1) ?
1058 mOutputWidth - tileX * mGridWidth : mGridWidth;
1059 size_t height = (tileY == static_cast<size_t>(mGridRows) - 1) ?
1060 mOutputHeight - tileY * mGridHeight : mGridHeight;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001061 ALOGV("%s: inputBuffer tileIndex [%zu, %zu], top %zu, left %zu, width %zu, height %zu,"
1062 " timeUs %" PRId64, __FUNCTION__, tileX, tileY, top, left, width, height,
1063 inputBuffer.timeUs);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001064
1065 res = copyOneYuvTile(buffer, inputFrame.yuvBuffer, top, left, width, height);
1066 if (res != OK) {
1067 ALOGE("%s: Failed to copy YUV tile %s (%d)", __FUNCTION__,
1068 strerror(-res), res);
1069 return res;
1070 }
1071
1072 res = mCodec->queueInputBuffer(inputBuffer.index, 0, buffer->capacity(),
1073 inputBuffer.timeUs, 0, nullptr /*errorDetailMsg*/);
1074 if (res != OK) {
1075 ALOGE("%s: Failed to queueInputBuffer to Codec: %s (%d)",
1076 __FUNCTION__, strerror(-res), res);
1077 return res;
1078 }
1079 }
1080
1081 inputFrame.codecInputBuffers.clear();
1082 return OK;
1083}
1084
Shuzhen Wange8675782019-12-05 09:12:14 -08001085status_t HeicCompositeStream::processOneCodecOutputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001086 InputFrame &inputFrame) {
1087 auto it = inputFrame.codecOutputBuffers.begin();
1088 sp<MediaCodecBuffer> buffer;
1089 status_t res = mCodec->getOutputBuffer(it->index, &buffer);
1090 if (res != OK) {
1091 ALOGE("%s: Error getting Heic codec output buffer at index %d: %s (%d)",
1092 __FUNCTION__, it->index, strerror(-res), res);
1093 return res;
1094 }
1095 if (buffer == nullptr) {
1096 ALOGE("%s: Invalid Heic codec output buffer at index %d",
1097 __FUNCTION__, it->index);
1098 return BAD_VALUE;
1099 }
1100
1101 sp<ABuffer> aBuffer = new ABuffer(buffer->data(), buffer->size());
1102 res = inputFrame.muxer->writeSampleData(
Shuzhen Wange8675782019-12-05 09:12:14 -08001103 aBuffer, inputFrame.trackIndex, inputFrame.timestamp, 0 /*flags*/);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001104 if (res != OK) {
1105 ALOGE("%s: Failed to write buffer index %d to muxer: %s (%d)",
1106 __FUNCTION__, it->index, strerror(-res), res);
1107 return res;
1108 }
1109
1110 mCodec->releaseOutputBuffer(it->index);
1111 if (inputFrame.pendingOutputTiles == 0) {
1112 ALOGW("%s: Codec generated more tiles than expected!", __FUNCTION__);
1113 } else {
1114 inputFrame.pendingOutputTiles--;
1115 }
1116
1117 inputFrame.codecOutputBuffers.erase(inputFrame.codecOutputBuffers.begin());
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001118
1119 ALOGV("%s: [%" PRId64 "]: Output buffer index %d",
Shuzhen Wange8675782019-12-05 09:12:14 -08001120 __FUNCTION__, frameNumber, it->index);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001121 return OK;
1122}
1123
Shuzhen Wange8675782019-12-05 09:12:14 -08001124status_t HeicCompositeStream::processCompletedInputFrame(int64_t frameNumber,
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001125 InputFrame &inputFrame) {
1126 sp<ANativeWindow> outputANW = mOutputSurface;
1127 inputFrame.muxer->stop();
1128
1129 // Copy the content of the file to memory.
1130 sp<GraphicBuffer> gb = GraphicBuffer::from(inputFrame.anb);
1131 void* dstBuffer;
1132 auto res = gb->lockAsync(GRALLOC_USAGE_SW_WRITE_OFTEN, &dstBuffer, inputFrame.fenceFd);
1133 if (res != OK) {
1134 ALOGE("%s: Error trying to lock output buffer fence: %s (%d)", __FUNCTION__,
1135 strerror(-res), res);
1136 return res;
1137 }
1138
1139 off_t fSize = lseek(inputFrame.fileFd, 0, SEEK_END);
1140 if (static_cast<size_t>(fSize) > mMaxHeicBufferSize - sizeof(CameraBlob)) {
1141 ALOGE("%s: Error: MediaMuxer output size %ld is larger than buffer sizer %zu",
1142 __FUNCTION__, fSize, mMaxHeicBufferSize - sizeof(CameraBlob));
1143 return BAD_VALUE;
1144 }
1145
1146 lseek(inputFrame.fileFd, 0, SEEK_SET);
1147 ssize_t bytesRead = read(inputFrame.fileFd, dstBuffer, fSize);
1148 if (bytesRead < fSize) {
1149 ALOGE("%s: Only %zd of %ld bytes read", __FUNCTION__, bytesRead, fSize);
1150 return BAD_VALUE;
1151 }
1152
1153 close(inputFrame.fileFd);
1154 inputFrame.fileFd = -1;
1155
1156 // Fill in HEIC header
1157 uint8_t *header = static_cast<uint8_t*>(dstBuffer) + mMaxHeicBufferSize - sizeof(CameraBlob);
1158 struct CameraBlob *blobHeader = (struct CameraBlob *)header;
1159 // Must be in sync with CAMERA3_HEIC_BLOB_ID in android_media_Utils.cpp
1160 blobHeader->blobId = static_cast<CameraBlobId>(0x00FE);
1161 blobHeader->blobSize = fSize;
1162
Shuzhen Wange8675782019-12-05 09:12:14 -08001163 res = native_window_set_buffers_timestamp(mOutputSurface.get(), inputFrame.timestamp);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001164 if (res != OK) {
1165 ALOGE("%s: Stream %d: Error setting timestamp: %s (%d)",
1166 __FUNCTION__, getStreamId(), strerror(-res), res);
1167 return res;
1168 }
1169
1170 res = outputANW->queueBuffer(mOutputSurface.get(), inputFrame.anb, /*fence*/ -1);
1171 if (res != OK) {
1172 ALOGE("%s: Failed to queueBuffer to Heic stream: %s (%d)", __FUNCTION__,
1173 strerror(-res), res);
1174 return res;
1175 }
1176 inputFrame.anb = nullptr;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -07001177 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001178
Shuzhen Wange8675782019-12-05 09:12:14 -08001179 ALOGV("%s: [%" PRId64 "]", __FUNCTION__, frameNumber);
1180 ATRACE_ASYNC_END("HEIC capture", frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001181 return OK;
1182}
1183
1184
Shuzhen Wange8675782019-12-05 09:12:14 -08001185void HeicCompositeStream::releaseInputFrameLocked(int64_t frameNumber,
1186 InputFrame *inputFrame /*out*/) {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001187 if (inputFrame == nullptr) {
1188 return;
1189 }
1190
1191 if (inputFrame->appSegmentBuffer.data != nullptr) {
1192 mAppSegmentConsumer->unlockBuffer(inputFrame->appSegmentBuffer);
1193 inputFrame->appSegmentBuffer.data = nullptr;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001194 }
1195
1196 while (!inputFrame->codecOutputBuffers.empty()) {
1197 auto it = inputFrame->codecOutputBuffers.begin();
1198 ALOGV("%s: releaseOutputBuffer index %d", __FUNCTION__, it->index);
1199 mCodec->releaseOutputBuffer(it->index);
1200 inputFrame->codecOutputBuffers.erase(it);
1201 }
1202
1203 if (inputFrame->yuvBuffer.data != nullptr) {
1204 mMainImageConsumer->unlockBuffer(inputFrame->yuvBuffer);
1205 inputFrame->yuvBuffer.data = nullptr;
1206 mYuvBufferAcquired = false;
1207 }
1208
1209 while (!inputFrame->codecInputBuffers.empty()) {
1210 auto it = inputFrame->codecInputBuffers.begin();
1211 inputFrame->codecInputBuffers.erase(it);
1212 }
1213
Shuzhen Wange8675782019-12-05 09:12:14 -08001214 if (inputFrame->error || mErrorState) {
1215 ALOGV("%s: notifyError called for frameNumber %" PRId64, __FUNCTION__, frameNumber);
1216 notifyError(frameNumber, inputFrame->requestId);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001217 }
1218
1219 if (inputFrame->fileFd >= 0) {
1220 close(inputFrame->fileFd);
1221 inputFrame->fileFd = -1;
1222 }
1223
1224 if (inputFrame->anb != nullptr) {
1225 sp<ANativeWindow> outputANW = mOutputSurface;
1226 outputANW->cancelBuffer(mOutputSurface.get(), inputFrame->anb, /*fence*/ -1);
1227 inputFrame->anb = nullptr;
Shuzhen Wange8675782019-12-05 09:12:14 -08001228
1229 mDequeuedOutputBufferCnt--;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001230 }
1231}
1232
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001233void HeicCompositeStream::releaseInputFramesLocked() {
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001234 auto it = mPendingInputFrames.begin();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001235 bool inputFrameDone = false;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001236 while (it != mPendingInputFrames.end()) {
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001237 auto& inputFrame = it->second;
1238 if (inputFrame.error ||
Shuzhen Wange8675782019-12-05 09:12:14 -08001239 (inputFrame.appSegmentWritten && inputFrame.pendingOutputTiles == 0)) {
1240 releaseInputFrameLocked(it->first, &inputFrame);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001241 it = mPendingInputFrames.erase(it);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001242 inputFrameDone = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001243 } else {
1244 it++;
1245 }
1246 }
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001247
1248 // Update codec quality based on first upcoming input frame.
1249 // Note that when encoding is in surface mode, currently there is no
1250 // way for camera service to synchronize quality setting on a per-frame
1251 // basis: we don't get notification when codec is ready to consume a new
1252 // input frame. So we update codec quality on a best-effort basis.
1253 if (inputFrameDone) {
1254 auto firstPendingFrame = mPendingInputFrames.begin();
1255 if (firstPendingFrame != mPendingInputFrames.end()) {
1256 updateCodecQualityLocked(firstPendingFrame->second.quality);
Shuzhen Wange8675782019-12-05 09:12:14 -08001257 } else {
1258 markTrackerIdle();
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001259 }
1260 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001261}
1262
1263status_t HeicCompositeStream::initializeCodec(uint32_t width, uint32_t height,
1264 const sp<CameraDeviceBase>& cameraDevice) {
1265 ALOGV("%s", __FUNCTION__);
1266
1267 bool useGrid = false;
Chong Zhang688abaa2019-05-17 16:32:23 -07001268 AString hevcName;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001269 bool isSizeSupported = isSizeSupportedByHeifEncoder(width, height,
Chong Zhang688abaa2019-05-17 16:32:23 -07001270 &mUseHeic, &useGrid, nullptr, &hevcName);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001271 if (!isSizeSupported) {
1272 ALOGE("%s: Encoder doesnt' support size %u x %u!",
1273 __FUNCTION__, width, height);
1274 return BAD_VALUE;
1275 }
1276
1277 // Create Looper for MediaCodec.
1278 auto desiredMime = mUseHeic ? MIMETYPE_IMAGE_ANDROID_HEIC : MIMETYPE_VIDEO_HEVC;
1279 mCodecLooper = new ALooper;
1280 mCodecLooper->setName("Camera3-HeicComposite-MediaCodecLooper");
1281 status_t res = mCodecLooper->start(
1282 false, // runOnCallingThread
1283 false, // canCallJava
1284 PRIORITY_AUDIO);
1285 if (res != OK) {
1286 ALOGE("%s: Failed to start codec looper: %s (%d)",
1287 __FUNCTION__, strerror(-res), res);
1288 return NO_INIT;
1289 }
1290
1291 // Create HEIC/HEVC codec.
Chong Zhang688abaa2019-05-17 16:32:23 -07001292 if (mUseHeic) {
1293 mCodec = MediaCodec::CreateByType(mCodecLooper, desiredMime, true /*encoder*/);
1294 } else {
1295 mCodec = MediaCodec::CreateByComponentName(mCodecLooper, hevcName);
1296 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001297 if (mCodec == nullptr) {
1298 ALOGE("%s: Failed to create codec for %s", __FUNCTION__, desiredMime);
1299 return NO_INIT;
1300 }
1301
1302 // Create Looper and handler for Codec callback.
1303 mCodecCallbackHandler = new CodecCallbackHandler(this);
1304 if (mCodecCallbackHandler == nullptr) {
1305 ALOGE("%s: Failed to create codec callback handler", __FUNCTION__);
1306 return NO_MEMORY;
1307 }
1308 mCallbackLooper = new ALooper;
1309 mCallbackLooper->setName("Camera3-HeicComposite-MediaCodecCallbackLooper");
1310 res = mCallbackLooper->start(
1311 false, // runOnCallingThread
1312 false, // canCallJava
1313 PRIORITY_AUDIO);
1314 if (res != OK) {
1315 ALOGE("%s: Failed to start media callback looper: %s (%d)",
1316 __FUNCTION__, strerror(-res), res);
1317 return NO_INIT;
1318 }
1319 mCallbackLooper->registerHandler(mCodecCallbackHandler);
1320
1321 mAsyncNotify = new AMessage(kWhatCallbackNotify, mCodecCallbackHandler);
1322 res = mCodec->setCallback(mAsyncNotify);
1323 if (res != OK) {
1324 ALOGE("%s: Failed to set MediaCodec callback: %s (%d)", __FUNCTION__,
1325 strerror(-res), res);
1326 return res;
1327 }
1328
1329 // Create output format and configure the Codec.
1330 sp<AMessage> outputFormat = new AMessage();
1331 outputFormat->setString(KEY_MIME, desiredMime);
1332 outputFormat->setInt32(KEY_BITRATE_MODE, BITRATE_MODE_CQ);
1333 outputFormat->setInt32(KEY_QUALITY, kDefaultJpegQuality);
1334 // Ask codec to skip timestamp check and encode all frames.
Chong Zhang70bfcec2019-03-18 12:52:28 -07001335 outputFormat->setInt64(KEY_MAX_PTS_GAP_TO_ENCODER, kNoFrameDropMaxPtsGap);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001336
1337 int32_t gridWidth, gridHeight, gridRows, gridCols;
1338 if (useGrid || mUseHeic) {
1339 gridWidth = HeicEncoderInfoManager::kGridWidth;
1340 gridHeight = HeicEncoderInfoManager::kGridHeight;
1341 gridRows = (height + gridHeight - 1)/gridHeight;
1342 gridCols = (width + gridWidth - 1)/gridWidth;
1343
1344 if (mUseHeic) {
1345 outputFormat->setInt32(KEY_TILE_WIDTH, gridWidth);
1346 outputFormat->setInt32(KEY_TILE_HEIGHT, gridHeight);
1347 outputFormat->setInt32(KEY_GRID_COLUMNS, gridCols);
1348 outputFormat->setInt32(KEY_GRID_ROWS, gridRows);
1349 }
1350
1351 } else {
1352 gridWidth = width;
1353 gridHeight = height;
1354 gridRows = 1;
1355 gridCols = 1;
1356 }
1357
1358 outputFormat->setInt32(KEY_WIDTH, !useGrid ? width : gridWidth);
1359 outputFormat->setInt32(KEY_HEIGHT, !useGrid ? height : gridHeight);
1360 outputFormat->setInt32(KEY_I_FRAME_INTERVAL, 0);
1361 outputFormat->setInt32(KEY_COLOR_FORMAT,
1362 useGrid ? COLOR_FormatYUV420Flexible : COLOR_FormatSurface);
Shuzhen Wang0ca81522019-08-30 14:15:16 -07001363 outputFormat->setInt32(KEY_FRAME_RATE, useGrid ? gridRows * gridCols : kNoGridOpRate);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001364 // This only serves as a hint to encoder when encoding is not real-time.
1365 outputFormat->setInt32(KEY_OPERATING_RATE, useGrid ? kGridOpRate : kNoGridOpRate);
1366
1367 res = mCodec->configure(outputFormat, nullptr /*nativeWindow*/,
1368 nullptr /*crypto*/, CONFIGURE_FLAG_ENCODE);
1369 if (res != OK) {
1370 ALOGE("%s: Failed to configure codec: %s (%d)", __FUNCTION__,
1371 strerror(-res), res);
1372 return res;
1373 }
1374
1375 mGridWidth = gridWidth;
1376 mGridHeight = gridHeight;
1377 mGridRows = gridRows;
1378 mGridCols = gridCols;
1379 mUseGrid = useGrid;
1380 mOutputWidth = width;
1381 mOutputHeight = height;
1382 mAppSegmentMaxSize = calcAppSegmentMaxSize(cameraDevice->info());
1383 mMaxHeicBufferSize = mOutputWidth * mOutputHeight * 3 / 2 + mAppSegmentMaxSize;
1384
1385 return OK;
1386}
1387
1388void HeicCompositeStream::deinitCodec() {
1389 ALOGV("%s", __FUNCTION__);
1390 if (mCodec != nullptr) {
1391 mCodec->stop();
1392 mCodec->release();
1393 mCodec.clear();
1394 }
1395
1396 if (mCodecLooper != nullptr) {
1397 mCodecLooper->stop();
1398 mCodecLooper.clear();
1399 }
1400
1401 if (mCallbackLooper != nullptr) {
1402 mCallbackLooper->stop();
1403 mCallbackLooper.clear();
1404 }
1405
1406 mAsyncNotify.clear();
1407 mFormat.clear();
1408}
1409
1410// Return the size of the complete list of app segment, 0 indicates failure
1411size_t HeicCompositeStream::findAppSegmentsSize(const uint8_t* appSegmentBuffer,
1412 size_t maxSize, size_t *app1SegmentSize) {
1413 if (appSegmentBuffer == nullptr || app1SegmentSize == nullptr) {
1414 ALOGE("%s: Invalid input appSegmentBuffer %p, app1SegmentSize %p",
1415 __FUNCTION__, appSegmentBuffer, app1SegmentSize);
1416 return 0;
1417 }
1418
1419 size_t expectedSize = 0;
1420 // First check for EXIF transport header at the end of the buffer
1421 const uint8_t *header = appSegmentBuffer + (maxSize - sizeof(struct CameraBlob));
1422 const struct CameraBlob *blob = (const struct CameraBlob*)(header);
1423 if (blob->blobId != CameraBlobId::JPEG_APP_SEGMENTS) {
1424 ALOGE("%s: Invalid EXIF blobId %hu", __FUNCTION__, blob->blobId);
1425 return 0;
1426 }
1427
1428 expectedSize = blob->blobSize;
1429 if (expectedSize == 0 || expectedSize > maxSize - sizeof(struct CameraBlob)) {
1430 ALOGE("%s: Invalid blobSize %zu.", __FUNCTION__, expectedSize);
1431 return 0;
1432 }
1433
1434 uint32_t totalSize = 0;
1435
1436 // Verify APP1 marker (mandatory)
1437 uint8_t app1Marker[] = {0xFF, 0xE1};
1438 if (memcmp(appSegmentBuffer, app1Marker, sizeof(app1Marker))) {
1439 ALOGE("%s: Invalid APP1 marker: %x, %x", __FUNCTION__,
1440 appSegmentBuffer[0], appSegmentBuffer[1]);
1441 return 0;
1442 }
1443 totalSize += sizeof(app1Marker);
1444
1445 uint16_t app1Size = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1446 appSegmentBuffer[totalSize+1];
1447 totalSize += app1Size;
1448
1449 ALOGV("%s: Expected APP segments size %zu, APP1 segment size %u",
1450 __FUNCTION__, expectedSize, app1Size);
1451 while (totalSize < expectedSize) {
1452 if (appSegmentBuffer[totalSize] != 0xFF ||
1453 appSegmentBuffer[totalSize+1] <= 0xE1 ||
1454 appSegmentBuffer[totalSize+1] > 0xEF) {
1455 // Invalid APPn marker
1456 ALOGE("%s: Invalid APPn marker: %x, %x", __FUNCTION__,
1457 appSegmentBuffer[totalSize], appSegmentBuffer[totalSize+1]);
1458 return 0;
1459 }
1460 totalSize += 2;
1461
1462 uint16_t appnSize = (static_cast<uint16_t>(appSegmentBuffer[totalSize]) << 8) +
1463 appSegmentBuffer[totalSize+1];
1464 totalSize += appnSize;
1465 }
1466
1467 if (totalSize != expectedSize) {
1468 ALOGE("%s: Invalid JPEG APP segments: totalSize %u vs expected size %zu",
1469 __FUNCTION__, totalSize, expectedSize);
1470 return 0;
1471 }
1472
1473 *app1SegmentSize = app1Size + sizeof(app1Marker);
1474 return expectedSize;
1475}
1476
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001477status_t HeicCompositeStream::copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
1478 const CpuConsumer::LockedBuffer& yuvBuffer,
1479 size_t top, size_t left, size_t width, size_t height) {
1480 ATRACE_CALL();
1481
1482 // Get stride information for codecBuffer
1483 sp<ABuffer> imageData;
1484 if (!codecBuffer->meta()->findBuffer("image-data", &imageData)) {
1485 ALOGE("%s: Codec input buffer is not for image data!", __FUNCTION__);
1486 return BAD_VALUE;
1487 }
1488 if (imageData->size() != sizeof(MediaImage2)) {
1489 ALOGE("%s: Invalid codec input image size %zu, expected %zu",
1490 __FUNCTION__, imageData->size(), sizeof(MediaImage2));
1491 return BAD_VALUE;
1492 }
1493 MediaImage2* imageInfo = reinterpret_cast<MediaImage2*>(imageData->data());
1494 if (imageInfo->mType != MediaImage2::MEDIA_IMAGE_TYPE_YUV ||
1495 imageInfo->mBitDepth != 8 ||
1496 imageInfo->mBitDepthAllocated != 8 ||
1497 imageInfo->mNumPlanes != 3) {
1498 ALOGE("%s: Invalid codec input image info: mType %d, mBitDepth %d, "
1499 "mBitDepthAllocated %d, mNumPlanes %d!", __FUNCTION__,
1500 imageInfo->mType, imageInfo->mBitDepth,
1501 imageInfo->mBitDepthAllocated, imageInfo->mNumPlanes);
1502 return BAD_VALUE;
1503 }
1504
1505 ALOGV("%s: yuvBuffer chromaStep %d, chromaStride %d",
1506 __FUNCTION__, yuvBuffer.chromaStep, yuvBuffer.chromaStride);
1507 ALOGV("%s: U offset %u, V offset %u, U rowInc %d, V rowInc %d, U colInc %d, V colInc %d",
1508 __FUNCTION__, imageInfo->mPlane[MediaImage2::U].mOffset,
1509 imageInfo->mPlane[MediaImage2::V].mOffset,
1510 imageInfo->mPlane[MediaImage2::U].mRowInc,
1511 imageInfo->mPlane[MediaImage2::V].mRowInc,
1512 imageInfo->mPlane[MediaImage2::U].mColInc,
1513 imageInfo->mPlane[MediaImage2::V].mColInc);
1514
1515 // Y
1516 for (auto row = top; row < top+height; row++) {
1517 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::Y].mOffset +
1518 imageInfo->mPlane[MediaImage2::Y].mRowInc * (row - top);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001519 mFnCopyRow(yuvBuffer.data+row*yuvBuffer.stride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001520 }
1521
1522 // U is Cb, V is Cr
1523 bool codecUPlaneFirst = imageInfo->mPlane[MediaImage2::V].mOffset >
1524 imageInfo->mPlane[MediaImage2::U].mOffset;
1525 uint32_t codecUvOffsetDiff = codecUPlaneFirst ?
1526 imageInfo->mPlane[MediaImage2::V].mOffset - imageInfo->mPlane[MediaImage2::U].mOffset :
1527 imageInfo->mPlane[MediaImage2::U].mOffset - imageInfo->mPlane[MediaImage2::V].mOffset;
1528 bool isCodecUvSemiplannar = (codecUvOffsetDiff == 1) &&
1529 (imageInfo->mPlane[MediaImage2::U].mRowInc ==
1530 imageInfo->mPlane[MediaImage2::V].mRowInc) &&
1531 (imageInfo->mPlane[MediaImage2::U].mColInc == 2) &&
1532 (imageInfo->mPlane[MediaImage2::V].mColInc == 2);
1533 bool isCodecUvPlannar =
1534 ((codecUPlaneFirst && codecUvOffsetDiff >=
1535 imageInfo->mPlane[MediaImage2::U].mRowInc * imageInfo->mHeight/2) ||
1536 ((!codecUPlaneFirst && codecUvOffsetDiff >=
1537 imageInfo->mPlane[MediaImage2::V].mRowInc * imageInfo->mHeight/2))) &&
1538 imageInfo->mPlane[MediaImage2::U].mColInc == 1 &&
1539 imageInfo->mPlane[MediaImage2::V].mColInc == 1;
1540 bool cameraUPlaneFirst = yuvBuffer.dataCr > yuvBuffer.dataCb;
1541
1542 if (isCodecUvSemiplannar && yuvBuffer.chromaStep == 2 &&
1543 (codecUPlaneFirst == cameraUPlaneFirst)) {
1544 // UV semiplannar
1545 // The chrome plane could be either Cb first, or Cr first. Take the
1546 // smaller address.
1547 uint8_t *src = std::min(yuvBuffer.dataCb, yuvBuffer.dataCr);
1548 MediaImage2::PlaneIndex dstPlane = codecUvOffsetDiff > 0 ? MediaImage2::U : MediaImage2::V;
1549 for (auto row = top/2; row < (top+height)/2; row++) {
1550 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[dstPlane].mOffset +
1551 imageInfo->mPlane[dstPlane].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001552 mFnCopyRow(src+row*yuvBuffer.chromaStride+left, dst, width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001553 }
1554 } else if (isCodecUvPlannar && yuvBuffer.chromaStep == 1) {
1555 // U plane
1556 for (auto row = top/2; row < (top+height)/2; row++) {
1557 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::U].mOffset +
1558 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001559 mFnCopyRow(yuvBuffer.dataCb+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001560 }
1561
1562 // V plane
1563 for (auto row = top/2; row < (top+height)/2; row++) {
1564 uint8_t *dst = codecBuffer->data() + imageInfo->mPlane[MediaImage2::V].mOffset +
1565 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2);
Shuzhen Wang219c2992019-02-15 17:24:28 -08001566 mFnCopyRow(yuvBuffer.dataCr+row*yuvBuffer.chromaStride+left/2, dst, width/2);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001567 }
1568 } else {
Shuzhen Wang219c2992019-02-15 17:24:28 -08001569 // Convert between semiplannar and plannar, or when UV orders are
1570 // different.
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001571 uint8_t *dst = codecBuffer->data();
1572 for (auto row = top/2; row < (top+height)/2; row++) {
1573 for (auto col = left/2; col < (left+width)/2; col++) {
1574 // U/Cb
1575 int32_t dstIndex = imageInfo->mPlane[MediaImage2::U].mOffset +
1576 imageInfo->mPlane[MediaImage2::U].mRowInc * (row - top/2) +
1577 imageInfo->mPlane[MediaImage2::U].mColInc * (col - left/2);
1578 int32_t srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1579 dst[dstIndex] = yuvBuffer.dataCb[srcIndex];
1580
1581 // V/Cr
1582 dstIndex = imageInfo->mPlane[MediaImage2::V].mOffset +
1583 imageInfo->mPlane[MediaImage2::V].mRowInc * (row - top/2) +
1584 imageInfo->mPlane[MediaImage2::V].mColInc * (col - left/2);
1585 srcIndex = row * yuvBuffer.chromaStride + yuvBuffer.chromaStep * col;
1586 dst[dstIndex] = yuvBuffer.dataCr[srcIndex];
1587 }
1588 }
1589 }
1590 return OK;
1591}
1592
Shuzhen Wang219c2992019-02-15 17:24:28 -08001593void HeicCompositeStream::initCopyRowFunction(int32_t width)
1594{
1595 using namespace libyuv;
1596
1597 mFnCopyRow = CopyRow_C;
1598#if defined(HAS_COPYROW_SSE2)
1599 if (TestCpuFlag(kCpuHasSSE2)) {
1600 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
1601 }
1602#endif
1603#if defined(HAS_COPYROW_AVX)
1604 if (TestCpuFlag(kCpuHasAVX)) {
1605 mFnCopyRow = IS_ALIGNED(width, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
1606 }
1607#endif
1608#if defined(HAS_COPYROW_ERMS)
1609 if (TestCpuFlag(kCpuHasERMS)) {
1610 mFnCopyRow = CopyRow_ERMS;
1611 }
1612#endif
1613#if defined(HAS_COPYROW_NEON)
1614 if (TestCpuFlag(kCpuHasNEON)) {
1615 mFnCopyRow = IS_ALIGNED(width, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
1616 }
1617#endif
1618#if defined(HAS_COPYROW_MIPS)
1619 if (TestCpuFlag(kCpuHasMIPS)) {
1620 mFnCopyRow = CopyRow_MIPS;
1621 }
1622#endif
1623}
1624
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001625size_t HeicCompositeStream::calcAppSegmentMaxSize(const CameraMetadata& info) {
1626 camera_metadata_ro_entry_t entry = info.find(ANDROID_HEIC_INFO_MAX_JPEG_APP_SEGMENTS_COUNT);
1627 size_t maxAppsSegment = 1;
1628 if (entry.count > 0) {
1629 maxAppsSegment = entry.data.u8[0] < 1 ? 1 :
1630 entry.data.u8[0] > 16 ? 16 : entry.data.u8[0];
1631 }
1632 return maxAppsSegment * (2 + 0xFFFF) + sizeof(struct CameraBlob);
1633}
1634
Shuzhen Wang62f49ed2019-09-04 14:07:53 -07001635void HeicCompositeStream::updateCodecQualityLocked(int32_t quality) {
1636 if (quality != mQuality) {
1637 sp<AMessage> qualityParams = new AMessage;
1638 qualityParams->setInt32(PARAMETER_KEY_VIDEO_BITRATE, quality);
1639 status_t res = mCodec->setParameters(qualityParams);
1640 if (res != OK) {
1641 ALOGE("%s: Failed to set codec quality: %s (%d)",
1642 __FUNCTION__, strerror(-res), res);
1643 } else {
1644 mQuality = quality;
1645 }
1646 }
1647}
1648
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001649bool HeicCompositeStream::threadLoop() {
Shuzhen Wange8675782019-12-05 09:12:14 -08001650 int64_t frameNumber = -1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001651 bool newInputAvailable = false;
1652
1653 {
1654 Mutex::Autolock l(mMutex);
1655 if (mErrorState) {
1656 // In case we landed in error state, return any pending buffers and
1657 // halt all further processing.
1658 compilePendingInputLocked();
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001659 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001660 return false;
1661 }
1662
1663
1664 while (!newInputAvailable) {
1665 compilePendingInputLocked();
Shuzhen Wange8675782019-12-05 09:12:14 -08001666 newInputAvailable = getNextReadyInputLocked(&frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001667
1668 if (!newInputAvailable) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001669 auto failingFrameNumber = getNextFailingInputLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001670 if (failingFrameNumber >= 0) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001671 releaseInputFrameLocked(failingFrameNumber,
1672 &mPendingInputFrames[failingFrameNumber]);
1673
1674 // It's okay to remove the entry from mPendingInputFrames
1675 // because:
1676 // 1. Only one internal stream (main input) is critical in
1677 // backing the output stream.
1678 // 2. If captureResult/appSegment arrives after the entry is
1679 // removed, they are simply skipped.
1680 mPendingInputFrames.erase(failingFrameNumber);
1681 if (mPendingInputFrames.size() == 0) {
1682 markTrackerIdle();
1683 }
1684 return true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001685 }
1686
1687 auto ret = mInputReadyCondition.waitRelative(mMutex, kWaitDuration);
1688 if (ret == TIMED_OUT) {
1689 return true;
1690 } else if (ret != OK) {
1691 ALOGE("%s: Timed wait on condition failed: %s (%d)", __FUNCTION__,
1692 strerror(-ret), ret);
1693 return false;
1694 }
1695 }
1696 }
1697 }
1698
Shuzhen Wange8675782019-12-05 09:12:14 -08001699 auto res = processInputFrame(frameNumber, mPendingInputFrames[frameNumber]);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001700 Mutex::Autolock l(mMutex);
1701 if (res != OK) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001702 ALOGE("%s: Failed processing frame with timestamp: %" PRIu64 ", frameNumber: %"
1703 PRId64 ": %s (%d)", __FUNCTION__, mPendingInputFrames[frameNumber].timestamp,
1704 frameNumber, strerror(-res), res);
1705 mPendingInputFrames[frameNumber].error = true;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001706 }
1707
Michael Gonzalezb5986a32019-10-09 15:38:17 -07001708 releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001709
1710 return true;
1711}
1712
Shuzhen Wange8675782019-12-05 09:12:14 -08001713void HeicCompositeStream::flagAnExifErrorFrameNumber(int64_t frameNumber) {
1714 Mutex::Autolock l(mMutex);
1715 mExifErrorFrameNumbers.emplace(frameNumber);
1716 mInputReadyCondition.signal();
1717}
1718
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001719bool HeicCompositeStream::onStreamBufferError(const CaptureResultExtras& resultExtras) {
1720 bool res = false;
Shuzhen Wange8675782019-12-05 09:12:14 -08001721 int64_t frameNumber = resultExtras.frameNumber;
1722
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001723 // Buffer errors concerning internal composite streams should not be directly visible to
1724 // camera clients. They must only receive a single buffer error with the public composite
1725 // stream id.
Shuzhen Wange8675782019-12-05 09:12:14 -08001726 if (resultExtras.errorStreamId == mAppSegmentStreamId) {
1727 ALOGV("%s: APP_SEGMENT frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1728 flagAnExifErrorFrameNumber(frameNumber);
1729 res = true;
1730 } else if (resultExtras.errorStreamId == mMainImageStreamId) {
1731 ALOGV("%s: YUV frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1732 flagAnErrorFrameNumber(frameNumber);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001733 res = true;
1734 }
1735
1736 return res;
1737}
1738
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001739void HeicCompositeStream::onResultError(const CaptureResultExtras& resultExtras) {
1740 // For result error, since the APPS_SEGMENT buffer already contains EXIF,
1741 // simply skip using the capture result metadata to override EXIF.
1742 Mutex::Autolock l(mMutex);
1743
1744 int64_t timestamp = -1;
Shuzhen Wange8675782019-12-05 09:12:14 -08001745 for (const auto& fn : mSettingsByFrameNumber) {
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001746 if (fn.first == resultExtras.frameNumber) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001747 timestamp = fn.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001748 break;
1749 }
1750 }
1751 if (timestamp == -1) {
1752 for (const auto& inputFrame : mPendingInputFrames) {
Shuzhen Wange8675782019-12-05 09:12:14 -08001753 if (inputFrame.first == resultExtras.frameNumber) {
1754 timestamp = inputFrame.second.timestamp;
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001755 break;
1756 }
1757 }
1758 }
1759
1760 if (timestamp == -1) {
1761 ALOGE("%s: Failed to find shutter timestamp for result error!", __FUNCTION__);
1762 return;
1763 }
1764
1765 mCaptureResults.emplace(timestamp, std::make_tuple(resultExtras.frameNumber, CameraMetadata()));
Shuzhen Wange8675782019-12-05 09:12:14 -08001766 ALOGV("%s: timestamp %" PRId64 ", frameNumber %" PRId64, __FUNCTION__,
1767 timestamp, resultExtras.frameNumber);
Shuzhen Wange7f4b462019-02-12 08:43:07 -08001768 mInputReadyCondition.signal();
1769}
1770
Shuzhen Wange8675782019-12-05 09:12:14 -08001771void HeicCompositeStream::onRequestError(const CaptureResultExtras& resultExtras) {
1772 auto frameNumber = resultExtras.frameNumber;
1773 ALOGV("%s: frameNumber: %" PRId64, __FUNCTION__, frameNumber);
1774 Mutex::Autolock l(mMutex);
1775 auto numRequests = mSettingsByFrameNumber.erase(frameNumber);
1776 if (numRequests == 0) {
1777 // Pending request has been populated into mPendingInputFrames
1778 mErrorFrameNumbers.emplace(frameNumber);
1779 mInputReadyCondition.signal();
1780 } else {
1781 // REQUEST_ERROR was received without onShutter.
1782 }
1783}
1784
1785void HeicCompositeStream::markTrackerIdle() {
1786 sp<StatusTracker> statusTracker = mStatusTracker.promote();
1787 if (statusTracker != nullptr) {
1788 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
1789 ALOGV("%s: Mark component as idle", __FUNCTION__);
1790 }
1791}
1792
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001793void HeicCompositeStream::CodecCallbackHandler::onMessageReceived(const sp<AMessage> &msg) {
1794 sp<HeicCompositeStream> parent = mParent.promote();
1795 if (parent == nullptr) return;
1796
1797 switch (msg->what()) {
1798 case kWhatCallbackNotify: {
1799 int32_t cbID;
1800 if (!msg->findInt32("callbackID", &cbID)) {
1801 ALOGE("kWhatCallbackNotify: callbackID is expected.");
1802 break;
1803 }
1804
1805 ALOGV("kWhatCallbackNotify: cbID = %d", cbID);
1806
1807 switch (cbID) {
1808 case MediaCodec::CB_INPUT_AVAILABLE: {
1809 int32_t index;
1810 if (!msg->findInt32("index", &index)) {
1811 ALOGE("CB_INPUT_AVAILABLE: index is expected.");
1812 break;
1813 }
1814 parent->onHeicInputFrameAvailable(index);
1815 break;
1816 }
1817
1818 case MediaCodec::CB_OUTPUT_AVAILABLE: {
1819 int32_t index;
1820 size_t offset;
1821 size_t size;
1822 int64_t timeUs;
1823 int32_t flags;
1824
1825 if (!msg->findInt32("index", &index)) {
1826 ALOGE("CB_OUTPUT_AVAILABLE: index is expected.");
1827 break;
1828 }
1829 if (!msg->findSize("offset", &offset)) {
1830 ALOGE("CB_OUTPUT_AVAILABLE: offset is expected.");
1831 break;
1832 }
1833 if (!msg->findSize("size", &size)) {
1834 ALOGE("CB_OUTPUT_AVAILABLE: size is expected.");
1835 break;
1836 }
1837 if (!msg->findInt64("timeUs", &timeUs)) {
1838 ALOGE("CB_OUTPUT_AVAILABLE: timeUs is expected.");
1839 break;
1840 }
1841 if (!msg->findInt32("flags", &flags)) {
1842 ALOGE("CB_OUTPUT_AVAILABLE: flags is expected.");
1843 break;
1844 }
1845
1846 CodecOutputBufferInfo bufferInfo = {
1847 index,
1848 (int32_t)offset,
1849 (int32_t)size,
1850 timeUs,
1851 (uint32_t)flags};
1852
1853 parent->onHeicOutputFrameAvailable(bufferInfo);
1854 break;
1855 }
1856
1857 case MediaCodec::CB_OUTPUT_FORMAT_CHANGED: {
1858 sp<AMessage> format;
1859 if (!msg->findMessage("format", &format)) {
1860 ALOGE("CB_OUTPUT_FORMAT_CHANGED: format is expected.");
1861 break;
1862 }
Chong Zhang860eff12019-09-16 16:15:00 -07001863 // Here format is MediaCodec's internal copy of output format.
1864 // Make a copy since onHeicFormatChanged() might modify it.
1865 sp<AMessage> formatCopy;
1866 if (format != nullptr) {
1867 formatCopy = format->dup();
1868 }
1869 parent->onHeicFormatChanged(formatCopy);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001870 break;
1871 }
1872
1873 case MediaCodec::CB_ERROR: {
1874 status_t err;
1875 int32_t actionCode;
1876 AString detail;
1877 if (!msg->findInt32("err", &err)) {
1878 ALOGE("CB_ERROR: err is expected.");
1879 break;
1880 }
1881 if (!msg->findInt32("action", &actionCode)) {
1882 ALOGE("CB_ERROR: action is expected.");
1883 break;
1884 }
1885 msg->findString("detail", &detail);
1886 ALOGE("Codec reported error(0x%x), actionCode(%d), detail(%s)",
1887 err, actionCode, detail.c_str());
1888
1889 parent->onHeicCodecError();
1890 break;
1891 }
1892
1893 default: {
1894 ALOGE("kWhatCallbackNotify: callbackID(%d) is unexpected.", cbID);
1895 break;
1896 }
1897 }
1898 break;
1899 }
1900
1901 default:
1902 ALOGE("shouldn't be here");
1903 break;
1904 }
1905}
1906
1907}; // namespace camera3
1908}; // namespace android