Debian Codegraph @

src/videofilters/h26x/media-codec-encoder.cpp

raw
1 /*
2 * Copyright (c) 2010-2022 Belledonne Communications SARL.
3 *
4 * This file is part of mediastreamer2
5 * (see https://gitlab.linphone.org/BC/public/mediastreamer2).
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
16 *
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "android_mediacodec.h"
22
23 #include "media-codec-encoder.h"
24
25 #include <algorithm>
26 #include <limits>
27
28 using namespace mediastreamer;
29 using namespace std;
30
31 namespace mediastreamer {
32
33 MediaCodecEncoder::MediaCodecEncoder(const std::string &mime)
34 : H26xEncoder(mime), _psInserter(H26xToolFactory::get(mime).createParameterSetsInserter()) {
35 try {
36 _vsize.width = 0;
37 _vsize.height = 0;
38 // We shall allocate the MediaCodec encoder the sooner as possible and before the decoder, because
39 // some phones hardware encoder and decoders can't be allocated at the same time.
40 createImpl();
41 } catch (const runtime_error &e) {
42 ms_error("MediaCodecEncoder: %s", e.what());
43 }
44 }
45
46 MediaCodecEncoder::~MediaCodecEncoder() {
47 if (_impl) AMediaCodec_delete(_impl);
48 }
49
50 void MediaCodecEncoder::enableOutbufferDequeueLimit(bool enable) {
51 if (enable) {
52 ms_warning("Enabling the DEVICE_MCH265_LIMIT_DEQUEUE_OF_OUTPUT_BUFFERS hack on this device.");
53 }
54 _hasOutbufferDequeueLimit = enable;
55 }
56
57 void MediaCodecEncoder::setFps(float fps) {
58 _fps = fps;
59 if (isRunning() && _impl) {
60 AMediaFormat *afmt = AMediaFormat_new();
61 AMediaFormat_setInt32(afmt, "frame-rate", int32_t(_fps));
62 AMediaCodec_setParams(_impl, afmt);
63 AMediaFormat_delete(afmt);
64 }
65 }
66
67 void MediaCodecEncoder::setBitrate(int bitrate) {
68 _bitrate = bitrate;
69 if (isRunning() && _impl) {
70 AMediaFormat *afmt = AMediaFormat_new();
71 // update the output bitrate
72 AMediaFormat_setInt32(afmt, "video-bitrate", (_bitrate * 9) / 10);
73 AMediaCodec_setParams(_impl, afmt);
74 AMediaFormat_delete(afmt);
75 }
76 }
77
78 void MediaCodecEncoder::start() {
79 try {
80 if (_impl == nullptr) {
81 ms_error("MediaCodecEncoder: starting failed. No MediaCodec instance.");
82 return;
83 }
84 if (_isRunning) {
85 ms_warning("MediaCodecEncoder: encoder already started");
86 return;
87 }
88 configureImpl();
89 if (AMediaCodec_start(_impl) != AMEDIA_OK) {
90 throw runtime_error("could not start encoder.");
91 }
92 _isRunning = true;
93 ms_message("MediaCodecEncoder: encoder successfully started");
94 } catch (const runtime_error &e) {
95 ms_error("MediaCodecEncoder: %s", e.what());
96 }
97 }
98
99 void MediaCodecEncoder::stop() {
100 if (_impl == nullptr) return;
101 if (!_isRunning) {
102 ms_warning("MediaCodecEncoder: encoder already stopped");
103 return;
104 }
105 if (_impl) {
106 AMediaCodec_flush(_impl);
107 AMediaCodec_stop(_impl);
108 // It is preferable to reset the encoder, otherwise it may not accept a new configuration while returning in
109 // preprocess(). This was observed at least on Moto G2, with qualcomm encoder.
110 AMediaCodec_reset(_impl);
111 }
112 _psInserter->flush();
113 _isRunning = false;
114 _pendingFrames = 0;
115 _firstImageQueued = false;
116 }
117
118 void MediaCodecEncoder::feed(mblk_t *rawData, uint64_t time, bool requestIFrame) {
119 // ensure that rawData is destroyed on function return
120 unique_ptr<mblk_t, void (*)(mblk_t *)> rawDataPtr(rawData, freemsg);
121
122 if (_recoveryMode && time % 5000 == 0) {
123 try {
124 if (_impl == nullptr) createImpl();
125 configureImpl();
126 _recoveryMode = false;
127 } catch (const runtime_error &e) {
128 ms_error("MediaCodecEncoder: %s", e.what());
129 ms_error(
130 "MediaCodecEncoder: AMediaCodec_reset() was not sufficient, will recreate the encoder in a moment...");
131 AMediaCodec_delete(_impl);
132 _impl = nullptr;
133 }
134 }
135
136 if (_impl == nullptr) return;
137
138 if (!_isRunning) {
139 ms_error("MediaCodecEncoder: encoder not running. Dropping buffer.");
140 return;
141 }
142
143 MSPicture pic;
144 ms_yuv_buf_init_from_mblk(&pic, rawData);
145
146 if (requestIFrame) {
147 AMediaFormat *afmt = AMediaFormat_new();
148 /*Force a key-frame*/
149 AMediaFormat_setInt32(afmt, "request-sync", 0);
150 AMediaCodec_setParams(_impl, afmt);
151 AMediaFormat_delete(afmt);
152 ms_error("MediaCodecEncoder: I-frame requested to MediaCodec");
153 }
154
155 ssize_t ibufidx = AMediaCodec_dequeueInputBuffer(_impl, _timeoutUs);
156 if (ibufidx < 0) {
157 if (ibufidx == AMEDIA_ERROR_UNKNOWN) {
158 ms_error("MediaCodecEncoder: AMediaCodec_dequeueInputBuffer() had an exception");
159 } else if (ibufidx == -1) {
160 ms_error("MediaCodecEncoder: no input buffer available.");
161 } else {
162 ms_error("MediaCodecEncoder: unknown error while requesting an input buffer (%zd)", ibufidx);
163 }
164 return;
165 }
166
167 size_t bufsize = 0;
168 size_t bufsize_max = numeric_limits<size_t>::max();
169
170 if (_pixelFormatConvertionEnabled) {
171 if (ms2_android_get_sdk_version() >= 31) {
172 // There is a size problem in Android 12
173 // We call getInputBuffer once before getting the image to know the max available size
174 // And use that size when queuing the buffer.
175 AMediaCodec_getInputBuffer(_impl, ibufidx, &bufsize_max);
176 }
177
178 AMediaImage image;
179 if (AMediaCodec_getInputImage(_impl, ibufidx, &image)) {
180 if (image.format == 35 /* YUV_420_888 */) {
181 MSRect src_roi = {0, 0, pic.w, pic.h};
182 int src_pix_strides[4] = {1, 1, 1, 1};
183 ms_yuv_buf_copy_with_pix_strides(pic.planes, pic.strides, src_pix_strides, src_roi, image.buffers,
184 image.row_strides, image.pixel_strides, image.crop_rect);
185 bufsize = image.row_strides[0] * image.height * 3 / 2;
186 } else {
187 ms_error("MediaCodecEncoder: encoder requires non YUV420 format");
188 }
189 AMediaImage_close(&image);
190 }
191 } else {
192 uint8_t *inputBuffer = AMediaCodec_getInputBuffer(_impl, ibufidx, &bufsize);
193 size_t dataSize = rawData->b_wptr - rawData->b_rptr;
194 if (dataSize <= bufsize) {
195 memcpy(inputBuffer, rawData->b_rptr, dataSize);
196 } else {
197 ms_error("MediaCodecEncoder: not enough space in the input buffer (required=%zu, availabel=%zu)", dataSize,
198 bufsize);
199 bufsize = 0;
200 }
201 }
202
203 if (AMediaCodec_queueInputBuffer(_impl, ibufidx, 0, min(bufsize, bufsize_max), time * 1000, 0) ==
204 AMEDIA_ERROR_BASE) {
205 ms_error("MediaCodecEncoder: error while queuing input buffer");
206 return;
207 }
208 if (!_firstImageQueued) _firstImageQueued = true;
209 _pendingFrames++;
210 }
211
212 bool MediaCodecEncoder::fetch(MSQueue *encodedData) {
213 MSQueue outq;
214 AMediaCodecBufferInfo info;
215 uint8_t *buf;
216 size_t bufsize;
217
218 if (_impl == nullptr || !_isRunning || _recoveryMode || !_firstImageQueued) return false;
219
220 if (_hasOutbufferDequeueLimit && _pendingFrames <= 0) return false;
221
222 ms_queue_init(&outq);
223
224 ssize_t obufidx = AMediaCodec_dequeueOutputBuffer(_impl, &info, _timeoutUs);
225 if (obufidx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
226 ms_message("MediaCodecEncoder: output format has changed.");
227 AMediaFormat *format = AMediaCodec_getOutputFormat(_impl);
228 ms_message("MediaCodecEncoder: new output format:\n%s", AMediaFormat_toString(format));
229 AMediaFormat_delete(format);
230 obufidx = AMediaCodec_dequeueOutputBuffer(_impl, &info, _timeoutUs);
231 }
232 if (obufidx < 0) {
233 if (obufidx == AMEDIA_ERROR_UNKNOWN) {
234 ms_error("MediaCodecEncoder: AMediaCodec_dequeueOutputBuffer() had an exception, MediaCodec is lost");
235 // MediaCodec need to be reset at this point because it may have become irrevocably crazy.
236 AMediaCodec_reset(_impl);
237 _recoveryMode = true;
238 } else if (obufidx != AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
239 ms_error("MediaCodecEncoder: unknown error while requesting an output buffer (%zd)", obufidx);
240 }
241 return false;
242 }
243
244 _pendingFrames--;
245
246 if ((buf = AMediaCodec_getOutputBuffer(_impl, obufidx, &bufsize)) == nullptr) {
247 ms_error("MediaCodecEncoder: AMediaCodec_getOutputBuffer() returned nullptr");
248 AMediaCodec_releaseOutputBuffer(_impl, obufidx, FALSE);
249 return false;
250 }
251 /*
252 * Split bitstream into NAL units. removePreventionBytes (start code emulation prevention byte) is willingly set to
253 * false, which is not obvious. Indeed, we should expect that the encoder has inserted prevention bytes (0x03) to
254 * escape 0x000001 start codes that could be present within slices. When splitting into NAL units, these 0x03 bytes
255 * should be removed, since it is allowed to have 0x000001 sequences within a NAL unit. However, the practice shows
256 * that if we do that, we get random decoding errors at the other end, whatever the other end is an Android or an
257 * iOS device. If we do not do that, the decoding goes perfectly well. How to explain this ?
258 * - this could mean that MediaCodec does not insert prevention bytes, but the encoder guarantees by some other
259 * means that no 0x000001 sequences can occur. however 0x00000301 may happen but this is not a prevention byte.
260 * - this could mean that we have another bug elsewhere in H26xUtils routines, but then why decoding goes perfectly
261 * well when not removing prevention bytes ?
262 */
263 H26xUtils::byteStreamToNalus(buf + info.offset, info.size, &outq, false);
264 _psInserter->process(&outq, encodedData);
265
266 AMediaCodec_releaseOutputBuffer(_impl, obufidx, FALSE);
267 return true;
268 }
269
270 void MediaCodecEncoder::createImpl() {
271 _impl = AMediaCodec_createEncoderByType(_mime.c_str());
272 if (_impl == nullptr) {
273 throw runtime_error("could not create MediaCodec");
274 }
275 }
276
277 void MediaCodecEncoder::configureImpl() {
278 AMediaFormat *format = createMediaFormat();
279
280 ms_message("MediaCodecEncoder: configuring MediaCodec with the following parameters:\n%s",
281 AMediaFormat_toString(format));
282
283 media_status_t status = AMediaCodec_configure(_impl, format, nullptr, nullptr, AMEDIACODEC_CONFIGURE_FLAG_ENCODE);
284 AMediaFormat_delete(format);
285
286 if (status != 0) {
287 throw runtime_error("could not configure encoder.");
288 }
289
290 format = AMediaCodec_getOutputFormat(_impl);
291 ms_message("MediaCodecEncoder: encoder successfully configured. In-force parameters:\n%s",
292 AMediaFormat_toString(format));
293 AMediaFormat_delete(format);
294 }
295
296 AMediaFormat *MediaCodecEncoder::createMediaFormat() const {
297 AMediaFormat *format = AMediaFormat_new();
298 AMediaFormat_setString(format, "mime", _mime.c_str());
299 AMediaFormat_setInt32(format, "color-format", _colorFormat);
300 AMediaFormat_setInt32(format, "width", _vsize.width);
301 AMediaFormat_setInt32(format, "height", _vsize.height);
302 AMediaFormat_setInt32(format, "frame-rate", _fps);
303 AMediaFormat_setInt32(format, "bitrate", (_bitrate * 9) / 10); // take a margin
304 AMediaFormat_setInt32(format, "bitrate-mode", _bitrateMode);
305 AMediaFormat_setInt32(format, "i-frame-interval", _iFrameInterval);
306 AMediaFormat_setInt32(format, "latency", _encodingLatency);
307 AMediaFormat_setInt32(format, "priority", _priority);
308 return format;
309 }
310
311 } // namespace mediastreamer