blob: 8fc521e69d8b1ced885e9a115713e48ba7d1955d [file] [log] [blame]
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_SERVERS_CAMERA_CAMERA3_HEIC_COMPOSITE_STREAM_H
18#define ANDROID_SERVERS_CAMERA_CAMERA3_HEIC_COMPOSITE_STREAM_H
19
20#include <queue>
21
22#include <gui/IProducerListener.h>
23#include <gui/CpuConsumer.h>
24
25#include <media/hardware/VideoAPI.h>
26#include <media/MediaCodecBuffer.h>
27#include <media/stagefright/foundation/ALooper.h>
Shuzhen Wang3d00ee52019-09-25 14:19:28 -070028#include <media/stagefright/foundation/AMessage.h>
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080029#include <media/stagefright/MediaCodec.h>
30#include <media/stagefright/MediaMuxer.h>
31
32#include "CompositeStream.h"
33
34namespace android {
35namespace camera3 {
36
37class HeicCompositeStream : public CompositeStream, public Thread,
38 public CpuConsumer::FrameAvailableListener {
39public:
40 HeicCompositeStream(wp<CameraDeviceBase> device,
41 wp<hardware::camera2::ICameraDeviceCallbacks> cb);
42 ~HeicCompositeStream() override;
43
44 static bool isHeicCompositeStream(const sp<Surface> &surface);
45
46 status_t createInternalStreams(const std::vector<sp<Surface>>& consumers,
47 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
48 camera3_stream_rotation_t rotation, int *id, const String8& physicalCameraId,
49 std::vector<int> *surfaceIds, int streamSetId, bool isShared) override;
50
51 status_t deleteInternalStreams() override;
52
53 status_t configureStream() override;
54
55 status_t insertGbp(SurfaceMap* /*out*/outSurfaceMap, Vector<int32_t>* /*out*/outputStreamIds,
56 int32_t* /*out*/currentStreamId) override;
57
Emilian Peev4697b642019-11-19 17:11:14 -080058 status_t insertCompositeStreamIds(std::vector<int32_t>* compositeStreamIds /*out*/) override;
59
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080060 void onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) override;
61
62 int getStreamId() override { return mMainImageStreamId; }
63
64 // Use onShutter to keep track of frame number <-> timestamp mapping.
65 void onBufferReleased(const BufferInfo& bufferInfo) override;
66 void onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
67 const CameraMetadata& settings) override;
68
69 // CpuConsumer listener implementation
70 void onFrameAvailable(const BufferItem& item) override;
71
72 // Return stream information about the internal camera streams
73 static status_t getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
74 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/);
75
76 static bool isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -070077 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName = nullptr);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080078 static bool isInMemoryTempFileSupported();
79protected:
80
81 bool threadLoop() override;
82 bool onStreamBufferError(const CaptureResultExtras& resultExtras) override;
Shuzhen Wange7f4b462019-02-12 08:43:07 -080083 void onResultError(const CaptureResultExtras& resultExtras) override;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080084
85private:
86 //
87 // HEIC/HEVC Codec related structures, utility functions, and callbacks
88 //
89 struct CodecOutputBufferInfo {
90 int32_t index;
91 int32_t offset;
92 int32_t size;
93 int64_t timeUs;
94 uint32_t flags;
95 };
96
97 struct CodecInputBufferInfo {
98 int32_t index;
99 int64_t timeUs;
100 size_t tileIndex;
101 };
102
103 class CodecCallbackHandler : public AHandler {
104 public:
105 explicit CodecCallbackHandler(wp<HeicCompositeStream> parent) {
106 mParent = parent;
107 }
108 virtual void onMessageReceived(const sp<AMessage> &msg);
109 private:
110 wp<HeicCompositeStream> mParent;
111 };
112
113 enum {
114 kWhatCallbackNotify,
115 };
116
117 bool mUseHeic;
118 sp<MediaCodec> mCodec;
119 sp<ALooper> mCodecLooper, mCallbackLooper;
120 sp<CodecCallbackHandler> mCodecCallbackHandler;
121 sp<AMessage> mAsyncNotify;
122 sp<AMessage> mFormat;
123 size_t mNumOutputTiles;
124
125 int32_t mOutputWidth, mOutputHeight;
126 size_t mMaxHeicBufferSize;
127 int32_t mGridWidth, mGridHeight;
128 size_t mGridRows, mGridCols;
129 bool mUseGrid; // Whether to use framework YUV frame tiling.
130
131 static const int64_t kNoFrameDropMaxPtsGap = -1000000;
132 static const int32_t kNoGridOpRate = 30;
133 static const int32_t kGridOpRate = 120;
134
135 void onHeicOutputFrameAvailable(const CodecOutputBufferInfo& bufferInfo);
136 void onHeicInputFrameAvailable(int32_t index); // Only called for YUV input mode.
137 void onHeicFormatChanged(sp<AMessage>& newFormat);
138 void onHeicCodecError();
139
140 status_t initializeCodec(uint32_t width, uint32_t height,
141 const sp<CameraDeviceBase>& cameraDevice);
142 void deinitCodec();
143
144 //
145 // Composite stream related structures, utility functions and callbacks.
146 //
147 struct InputFrame {
148 int32_t orientation;
149 int32_t quality;
150
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800151 CpuConsumer::LockedBuffer appSegmentBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800152 std::vector<CodecOutputBufferInfo> codecOutputBuffers;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800153 std::unique_ptr<CameraMetadata> result;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800154
155 // Fields that are only applicable to HEVC tiling.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800156 CpuConsumer::LockedBuffer yuvBuffer;
157 std::vector<CodecInputBufferInfo> codecInputBuffers;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800158
159 bool error;
160 bool errorNotified;
161 int64_t frameNumber;
162
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700163 sp<AMessage> format;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800164 sp<MediaMuxer> muxer;
165 int fenceFd;
166 int fileFd;
167 ssize_t trackIndex;
168 ANativeWindowBuffer *anb;
169
170 bool appSegmentWritten;
171 size_t pendingOutputTiles;
172 size_t codecInputCounter;
173
174 InputFrame() : orientation(0), quality(kDefaultJpegQuality), error(false),
175 errorNotified(false), frameNumber(-1), fenceFd(-1), fileFd(-1),
176 trackIndex(-1), anb(nullptr), appSegmentWritten(false),
177 pendingOutputTiles(0), codecInputCounter(0) { }
178 };
179
180 void compilePendingInputLocked();
181 // Find first complete and valid frame with smallest timestamp
182 bool getNextReadyInputLocked(int64_t *currentTs /*out*/);
183 // Find next failing frame number with smallest timestamp and return respective frame number
184 int64_t getNextFailingInputLocked(int64_t *currentTs /*out*/);
185
186 status_t processInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
187 status_t processCodecInputFrame(InputFrame &inputFrame);
188 status_t startMuxerForInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
189 status_t processAppSegment(nsecs_t timestamp, InputFrame &inputFrame);
190 status_t processOneCodecOutputFrame(nsecs_t timestamp, InputFrame &inputFrame);
191 status_t processCompletedInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
192
193 void releaseInputFrameLocked(InputFrame *inputFrame /*out*/);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700194 void releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800195
196 size_t findAppSegmentsSize(const uint8_t* appSegmentBuffer, size_t maxSize,
197 size_t* app1SegmentSize);
198 int64_t findTimestampInNsLocked(int64_t timeInUs);
199 status_t copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
200 const CpuConsumer::LockedBuffer& yuvBuffer,
201 size_t top, size_t left, size_t width, size_t height);
Shuzhen Wang219c2992019-02-15 17:24:28 -0800202 void initCopyRowFunction(int32_t width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800203 static size_t calcAppSegmentMaxSize(const CameraMetadata& info);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700204 void updateCodecQualityLocked(int32_t quality);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800205
206 static const nsecs_t kWaitDuration = 10000000; // 10 ms
207 static const int32_t kDefaultJpegQuality = 99;
208 static const auto kJpegDataSpace = HAL_DATASPACE_V0_JFIF;
209 static const android_dataspace kAppSegmentDataSpace =
210 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS);
211 static const android_dataspace kHeifDataSpace =
212 static_cast<android_dataspace>(HAL_DATASPACE_HEIF);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700213 // Use the limit of pipeline depth in the API sepc as maximum number of acquired
214 // app segment buffers.
215 static const uint32_t kMaxAcquiredAppSegment = 8;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800216
217 int mAppSegmentStreamId, mAppSegmentSurfaceId;
218 sp<CpuConsumer> mAppSegmentConsumer;
219 sp<Surface> mAppSegmentSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800220 size_t mAppSegmentMaxSize;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800221 CameraMetadata mStaticInfo;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800222
223 int mMainImageStreamId, mMainImageSurfaceId;
224 sp<Surface> mMainImageSurface;
225 sp<CpuConsumer> mMainImageConsumer; // Only applicable for HEVC codec.
226 bool mYuvBufferAcquired; // Only applicable to HEVC codec
227
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700228 static const int32_t kMaxOutputSurfaceProducerCount = 1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800229 sp<Surface> mOutputSurface;
230 sp<ProducerListener> mProducerListener;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700231 int32_t mDequeuedOutputBufferCnt;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800232
233 // Map from frame number to JPEG setting of orientation+quality
234 std::map<int64_t, std::pair<int32_t, int32_t>> mSettingsByFrameNumber;
235 // Map from timestamp to JPEG setting of orientation+quality
236 std::map<int64_t, std::pair<int32_t, int32_t>> mSettingsByTimestamp;
237
238 // Keep all incoming APP segment Blob buffer pending further processing.
239 std::vector<int64_t> mInputAppSegmentBuffers;
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700240 int32_t mLockedAppSegmentBufferCnt;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800241
242 // Keep all incoming HEIC blob buffer pending further processing.
243 std::vector<CodecOutputBufferInfo> mCodecOutputBuffers;
244 std::queue<int64_t> mCodecOutputBufferTimestamps;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700245 size_t mCodecOutputCounter;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700246 int32_t mQuality;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800247
248 // Keep all incoming Yuv buffer pending tiling and encoding (for HEVC YUV tiling only)
249 std::vector<int64_t> mInputYuvBuffers;
250 // Keep all codec input buffers ready to be filled out (for HEVC YUV tiling only)
251 std::vector<int32_t> mCodecInputBuffers;
252
253 // Artificial strictly incremental YUV grid timestamp to make encoder happy.
254 int64_t mGridTimestampUs;
255
256 // In most common use case, entries are accessed in order.
257 std::map<int64_t, InputFrame> mPendingInputFrames;
Shuzhen Wang219c2992019-02-15 17:24:28 -0800258
259 // Function pointer of libyuv row copy.
260 void (*mFnCopyRow)(const uint8_t* src, uint8_t* dst, int width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800261};
262
263}; // namespace camera3
264}; // namespace android
265
266#endif //ANDROID_SERVERS_CAMERA_CAMERA3_HEIC_COMPOSITE_STREAM_H