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