blob: e88471d74d1f066fa6c0ec4d5bc84303f10e85b1 [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
58 void onShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp) override;
59
60 int getStreamId() override { return mMainImageStreamId; }
61
62 // Use onShutter to keep track of frame number <-> timestamp mapping.
63 void onBufferReleased(const BufferInfo& bufferInfo) override;
64 void onBufferRequestForFrameNumber(uint64_t frameNumber, int streamId,
65 const CameraMetadata& settings) override;
66
67 // CpuConsumer listener implementation
68 void onFrameAvailable(const BufferItem& item) override;
69
70 // Return stream information about the internal camera streams
71 static status_t getCompositeStreamInfo(const OutputStreamInfo &streamInfo,
72 const CameraMetadata& ch, std::vector<OutputStreamInfo>* compositeOutput /*out*/);
73
74 static bool isSizeSupportedByHeifEncoder(int32_t width, int32_t height,
Chong Zhang688abaa2019-05-17 16:32:23 -070075 bool* useHeic, bool* useGrid, int64_t* stall, AString* hevcName = nullptr);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080076 static bool isInMemoryTempFileSupported();
77protected:
78
79 bool threadLoop() override;
80 bool onStreamBufferError(const CaptureResultExtras& resultExtras) override;
Shuzhen Wange7f4b462019-02-12 08:43:07 -080081 void onResultError(const CaptureResultExtras& resultExtras) override;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -080082
83private:
84 //
85 // HEIC/HEVC Codec related structures, utility functions, and callbacks
86 //
87 struct CodecOutputBufferInfo {
88 int32_t index;
89 int32_t offset;
90 int32_t size;
91 int64_t timeUs;
92 uint32_t flags;
93 };
94
95 struct CodecInputBufferInfo {
96 int32_t index;
97 int64_t timeUs;
98 size_t tileIndex;
99 };
100
101 class CodecCallbackHandler : public AHandler {
102 public:
103 explicit CodecCallbackHandler(wp<HeicCompositeStream> parent) {
104 mParent = parent;
105 }
106 virtual void onMessageReceived(const sp<AMessage> &msg);
107 private:
108 wp<HeicCompositeStream> mParent;
109 };
110
111 enum {
112 kWhatCallbackNotify,
113 };
114
115 bool mUseHeic;
116 sp<MediaCodec> mCodec;
117 sp<ALooper> mCodecLooper, mCallbackLooper;
118 sp<CodecCallbackHandler> mCodecCallbackHandler;
119 sp<AMessage> mAsyncNotify;
120 sp<AMessage> mFormat;
121 size_t mNumOutputTiles;
122
123 int32_t mOutputWidth, mOutputHeight;
124 size_t mMaxHeicBufferSize;
125 int32_t mGridWidth, mGridHeight;
126 size_t mGridRows, mGridCols;
127 bool mUseGrid; // Whether to use framework YUV frame tiling.
128
129 static const int64_t kNoFrameDropMaxPtsGap = -1000000;
130 static const int32_t kNoGridOpRate = 30;
131 static const int32_t kGridOpRate = 120;
132
133 void onHeicOutputFrameAvailable(const CodecOutputBufferInfo& bufferInfo);
134 void onHeicInputFrameAvailable(int32_t index); // Only called for YUV input mode.
135 void onHeicFormatChanged(sp<AMessage>& newFormat);
136 void onHeicCodecError();
137
138 status_t initializeCodec(uint32_t width, uint32_t height,
139 const sp<CameraDeviceBase>& cameraDevice);
140 void deinitCodec();
141
142 //
143 // Composite stream related structures, utility functions and callbacks.
144 //
145 struct InputFrame {
146 int32_t orientation;
147 int32_t quality;
148
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800149 CpuConsumer::LockedBuffer appSegmentBuffer;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800150 std::vector<CodecOutputBufferInfo> codecOutputBuffers;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800151 std::unique_ptr<CameraMetadata> result;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800152
153 // Fields that are only applicable to HEVC tiling.
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800154 CpuConsumer::LockedBuffer yuvBuffer;
155 std::vector<CodecInputBufferInfo> codecInputBuffers;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800156
157 bool error;
158 bool errorNotified;
159 int64_t frameNumber;
160
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700161 sp<AMessage> format;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800162 sp<MediaMuxer> muxer;
163 int fenceFd;
164 int fileFd;
165 ssize_t trackIndex;
166 ANativeWindowBuffer *anb;
167
168 bool appSegmentWritten;
169 size_t pendingOutputTiles;
170 size_t codecInputCounter;
171
172 InputFrame() : orientation(0), quality(kDefaultJpegQuality), error(false),
173 errorNotified(false), frameNumber(-1), fenceFd(-1), fileFd(-1),
174 trackIndex(-1), anb(nullptr), appSegmentWritten(false),
175 pendingOutputTiles(0), codecInputCounter(0) { }
176 };
177
178 void compilePendingInputLocked();
179 // Find first complete and valid frame with smallest timestamp
180 bool getNextReadyInputLocked(int64_t *currentTs /*out*/);
181 // Find next failing frame number with smallest timestamp and return respective frame number
182 int64_t getNextFailingInputLocked(int64_t *currentTs /*out*/);
183
184 status_t processInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
185 status_t processCodecInputFrame(InputFrame &inputFrame);
186 status_t startMuxerForInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
187 status_t processAppSegment(nsecs_t timestamp, InputFrame &inputFrame);
188 status_t processOneCodecOutputFrame(nsecs_t timestamp, InputFrame &inputFrame);
189 status_t processCompletedInputFrame(nsecs_t timestamp, InputFrame &inputFrame);
190
191 void releaseInputFrameLocked(InputFrame *inputFrame /*out*/);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700192 void releaseInputFramesLocked();
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800193
194 size_t findAppSegmentsSize(const uint8_t* appSegmentBuffer, size_t maxSize,
195 size_t* app1SegmentSize);
196 int64_t findTimestampInNsLocked(int64_t timeInUs);
197 status_t copyOneYuvTile(sp<MediaCodecBuffer>& codecBuffer,
198 const CpuConsumer::LockedBuffer& yuvBuffer,
199 size_t top, size_t left, size_t width, size_t height);
Shuzhen Wang219c2992019-02-15 17:24:28 -0800200 void initCopyRowFunction(int32_t width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800201 static size_t calcAppSegmentMaxSize(const CameraMetadata& info);
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700202 void updateCodecQualityLocked(int32_t quality);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800203
204 static const nsecs_t kWaitDuration = 10000000; // 10 ms
205 static const int32_t kDefaultJpegQuality = 99;
206 static const auto kJpegDataSpace = HAL_DATASPACE_V0_JFIF;
207 static const android_dataspace kAppSegmentDataSpace =
208 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS);
209 static const android_dataspace kHeifDataSpace =
210 static_cast<android_dataspace>(HAL_DATASPACE_HEIF);
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700211 // Use the limit of pipeline depth in the API sepc as maximum number of acquired
212 // app segment buffers.
213 static const uint32_t kMaxAcquiredAppSegment = 8;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800214
215 int mAppSegmentStreamId, mAppSegmentSurfaceId;
216 sp<CpuConsumer> mAppSegmentConsumer;
217 sp<Surface> mAppSegmentSurface;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800218 size_t mAppSegmentMaxSize;
Shuzhen Wange7f4b462019-02-12 08:43:07 -0800219 CameraMetadata mStaticInfo;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800220
221 int mMainImageStreamId, mMainImageSurfaceId;
222 sp<Surface> mMainImageSurface;
223 sp<CpuConsumer> mMainImageConsumer; // Only applicable for HEVC codec.
224 bool mYuvBufferAcquired; // Only applicable to HEVC codec
225
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700226 static const int32_t kMaxOutputSurfaceProducerCount = 1;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800227 sp<Surface> mOutputSurface;
228 sp<ProducerListener> mProducerListener;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700229 int32_t mDequeuedOutputBufferCnt;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800230
231 // Map from frame number to JPEG setting of orientation+quality
232 std::map<int64_t, std::pair<int32_t, int32_t>> mSettingsByFrameNumber;
233 // Map from timestamp to JPEG setting of orientation+quality
234 std::map<int64_t, std::pair<int32_t, int32_t>> mSettingsByTimestamp;
235
236 // Keep all incoming APP segment Blob buffer pending further processing.
237 std::vector<int64_t> mInputAppSegmentBuffers;
Michael Gonzalezb5986a32019-10-09 15:38:17 -0700238 int32_t mLockedAppSegmentBufferCnt;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800239
240 // Keep all incoming HEIC blob buffer pending further processing.
241 std::vector<CodecOutputBufferInfo> mCodecOutputBuffers;
242 std::queue<int64_t> mCodecOutputBufferTimestamps;
Shuzhen Wang3d00ee52019-09-25 14:19:28 -0700243 size_t mCodecOutputCounter;
Shuzhen Wang62f49ed2019-09-04 14:07:53 -0700244 int32_t mQuality;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800245
246 // Keep all incoming Yuv buffer pending tiling and encoding (for HEVC YUV tiling only)
247 std::vector<int64_t> mInputYuvBuffers;
248 // Keep all codec input buffers ready to be filled out (for HEVC YUV tiling only)
249 std::vector<int32_t> mCodecInputBuffers;
250
251 // Artificial strictly incremental YUV grid timestamp to make encoder happy.
252 int64_t mGridTimestampUs;
253
254 // In most common use case, entries are accessed in order.
255 std::map<int64_t, InputFrame> mPendingInputFrames;
Shuzhen Wang219c2992019-02-15 17:24:28 -0800256
257 // Function pointer of libyuv row copy.
258 void (*mFnCopyRow)(const uint8_t* src, uint8_t* dst, int width);
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -0800259};
260
261}; // namespace camera3
262}; // namespace android
263
264#endif //ANDROID_SERVERS_CAMERA_CAMERA3_HEIC_COMPOSITE_STREAM_H