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