Debian Codegraph @

src/videofilters/h26x/media-codec-decoder.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-decoder.h"
24
25 using namespace mediastreamer;
26 using namespace std;
27
28 namespace mediastreamer {
29
30 MediaCodecDecoder::MediaCodecDecoder(const std::string &mime) : H26xDecoder(mime) {
31 try {
32 _impl = AMediaCodec_createDecoderByType(mime.c_str());
33 if (_impl == nullptr) {
34 ostringstream msg;
35 msg << "could not create MediaCodec for '" << mime << "'";
36 throw runtime_error(msg.str());
37 }
38 _format = createFormat(true);
39 _bufAllocator = ms_yuv_buf_allocator_new();
40 ms_yuv_buf_allocator_set_max_frames(_bufAllocator, 15); /* we need to accomodate decoding with 'B-frames' */
41 _naluHeader.reset(H26xToolFactory::get(mime).createNaluHeader());
42 _psStore.reset(H26xToolFactory::get(mime).createParameterSetsStore());
43 startImpl();
44 } catch (const runtime_error &e) {
45 ms_error("MediaCodecDecoder: %s. Dumping decoding context", e.what());
46 if (_impl) AMediaCodec_delete(_impl);
47 _impl = nullptr;
48 }
49 }
50
51 MediaCodecDecoder::~MediaCodecDecoder() {
52 if (_impl) AMediaCodec_delete(_impl);
53 if (_format) AMediaFormat_delete(_format);
54 if (_bufAllocator) ms_yuv_buf_allocator_free(_bufAllocator);
55 }
56
57 bool MediaCodecDecoder::setParameterSets(MSQueue *parameterSets, uint64_t timestamp) {
58 if (!feed(parameterSets, timestamp, true)) {
59 ms_error("MediaCodecDecoder: parameter sets has been refused by the decoder.");
60 return false;
61 }
62 _needParameters = false;
63 return true;
64 }
65
66 bool MediaCodecDecoder::feed(MSQueue *encodedFrame, uint64_t timestamp) {
67 bool status = false;
68
69 if (_impl == nullptr) {
70 ms_queue_flush(encodedFrame);
71 return true;
72 }
73
74 _psStore->extractAllPs(encodedFrame);
75 if (_psStore->hasNewParameters()) {
76 ms_message("MediaCodecDecoder: new paramter sets received");
77 _needParameters = true;
78 _psStore->acknowlege();
79 }
80
81 if (_needParameters && _psStore->psGatheringCompleted()) {
82 MSQueue parameters;
83 ms_queue_init(&parameters);
84 _psStore->fetchAllPs(&parameters);
85 if (!setParameterSets(&parameters, timestamp)) {
86 ms_error("MediaCodecDecoder: waiting for parameter sets.");
87 goto clean;
88 }
89 }
90
91 if (_needParameters) {
92 ms_error("MediaCodecDecoder: missing parameter sets");
93 goto clean;
94 }
95
96 if (_needKeyFrame) {
97 if (!isKeyFrame(encodedFrame)) {
98 ms_error("MediaCodecDecoder: waiting for key frame.");
99 goto clean;
100 }
101 ms_message("MediaCodecDecoder: key frame received");
102 _needKeyFrame = false;
103 }
104
105 if (!feed(encodedFrame, timestamp, false)) {
106 goto clean;
107 }
108
109 _pendingFrames++;
110 status = true;
111
112 clean:
113 ms_queue_flush(encodedFrame);
114 return status;
115 }
116
117 MediaCodecDecoder::Status MediaCodecDecoder::fetch(mblk_t *&frame) {
118 AMediaImage image = {0};
119 int dst_pix_strides[4] = {1, 1, 1, 1};
120 MSRect dst_roi = {0};
121 AMediaCodecBufferInfo info;
122 ssize_t oBufidx = -1;
123 Status status = NoError;
124
125 frame = nullptr;
126
127 if (_impl == nullptr || _pendingFrames <= 0) {
128 status = NoFrameAvailable;
129 goto end;
130 }
131 {
132 TimeReport dequeue("dequeueOutputBuffer");
133 oBufidx = AMediaCodec_dequeueOutputBuffer(_impl, &info, _timeoutUs);
134 while (oBufidx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED ||
135 oBufidx == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) {
136 ms_message("MediaCodecDecoder: %s", codecInfoToString(oBufidx).c_str());
137 if (oBufidx == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) {
138 AMediaFormat *format = AMediaCodec_getOutputFormat(_impl);
139 AMediaFormat_getInt32(format, "width", &_curWidth);
140 AMediaFormat_getInt32(format, "height", &_curHeight);
141 ms_message("MediaCodecDecoder: new format %ix%i :\n%s", _curWidth, _curHeight,
142 AMediaFormat_toString(format));
143 AMediaFormat_delete(format);
144 }
145 oBufidx = AMediaCodec_dequeueOutputBuffer(_impl, &info, _timeoutUs);
146 }
147 dequeue.finished();
148 }
149
150 if (oBufidx < 0) {
151 if (oBufidx == AMEDIACODEC_INFO_TRY_AGAIN_LATER) {
152 return NoFrameAvailable;
153 } else {
154 ms_error("MediaCodecDecoder: error while dequeueing an output buffer: %s",
155 codecInfoToString(oBufidx).c_str());
156 if (oBufidx == AMEDIA_ERROR_UNKNOWN) {
157 try {
158 resetImpl();
159 startImpl();
160 } catch (const runtime_error &e) {
161 ms_error("MediaCodecDecoder: decoding session couldn't been started. The session is definitively "
162 "lost !");
163 }
164 }
165 return DecodingFailure;
166 }
167 goto end;
168 }
169
170 _pendingFrames--;
171 {
172 TimeReport getOutputImage("AMediaCodec_getOutputImage");
173 if (AMediaCodec_getOutputImage(_impl, oBufidx, &image) <= 0) {
174 ms_error("MediaCodecDecoder: AMediaCodec_getOutputImage() failed");
175 status = DecodingFailure;
176 goto end;
177 }
178 getOutputImage.finished();
179 }
180
181 if (_curWidth && _curHeight && (_curWidth != image.crop_rect.w || _curHeight != image.crop_rect.h)) {
182 /*
183 * Sometimes (not all devices), we observe an insconsistency between the width/height announced by the
184 * MediaCodec.getOutputFormat() and the width/height announced by the getOutputImage(). In some cases this also
185 * results in an garbled decoded image, but sometimes not. We print out the information, but no further action
186 * can be done here.
187 */
188 ms_error("Mismatch between decoder new format and output image detected: %ix%i vs %ix%i", _curWidth, _curHeight,
189 image.crop_rect.w, image.crop_rect.h);
190 _curWidth = image.crop_rect.w;
191 _curHeight = image.crop_rect.h;
192 }
193 // ms_message("MediaCodecDecoder: got output image with presentation timestamp [%llu] ms.", (unsigned long long)
194 // image.timestamp/1000000ULL);
195
196 MSPicture pic;
197 frame = ms_yuv_buf_allocator_get(_bufAllocator, &pic, image.crop_rect.w, image.crop_rect.h);
198 // ms_message("image.crop_rect.w=%i, image.crop_rect.h=%i, image.row_strides=%i,%i,%i image.pixel_strides=%i,%i,%i",
199 // image.crop_rect.w, image.crop_rect.h, image.row_strides[0], image.row_strides[1], image.row_strides[2],
200 // image.pixel_strides[0], image.pixel_strides[1], image.pixel_strides[2]);
201 if (frame) {
202 ms_yuv_buf_copy_with_pix_strides(image.buffers, image.row_strides, image.pixel_strides, image.crop_rect,
203 pic.planes, pic.strides, dst_pix_strides, dst_roi);
204 mblk_set_timestamp_info(frame, (uint32_t)((image.timestamp / 1000000LL) * 90LL));
205 } else status = VideoDecoder::Status::NoFrameAvailable;
206
207 AMediaImage_close(&image);
208
209 end:
210 if (oBufidx >= 0) AMediaCodec_releaseOutputBuffer(_impl, oBufidx, FALSE);
211 return status;
212 }
213
214 AMediaFormat *MediaCodecDecoder::createFormat(bool withLowLatency) const {
215 AMediaFormat *format = AMediaFormat_new();
216 AMediaFormat_setString(format, "mime", getMime().c_str());
217 AMediaFormat_setInt32(format, "color-format", 0x7f420888);
218 AMediaFormat_setInt32(format, "max-width", 1920);
219 AMediaFormat_setInt32(format, "max-height", 1920);
220 AMediaFormat_setInt32(format, "priority", 0);
221 if (withLowLatency) AMediaFormat_setInt32(format, "low-latency", 1); // MediaFormat.KEY_LOW_LATENCY
222 return format;
223 }
224
225 void MediaCodecDecoder::startImpl() {
226 media_status_t status = AMEDIA_OK;
227 ostringstream errMsg;
228 ms_message("MediaCodecDecoder: starting decoder with following parameters:\n%s", AMediaFormat_toString(_format));
229 if ((status = AMediaCodec_configure(_impl, _format, nullptr, nullptr, 0)) != AMEDIA_OK) {
230 ms_warning("MediaCodecDecoder: configure failed, retrying without low-latency parameter.");
231 AMediaFormat_delete(_format);
232 _format = createFormat(false);
233 if ((status = AMediaCodec_configure(_impl, _format, nullptr, nullptr, 0)) != AMEDIA_OK) {
234 errMsg << "configuration failure: " << int(status);
235 throw runtime_error(errMsg.str());
236 }
237 }
238
239 if ((status = AMediaCodec_start(_impl)) != AMEDIA_OK) {
240 errMsg << "starting failure: " << int(status);
241 throw runtime_error(errMsg.str());
242 }
243
244 ms_message("MediaCodecDecoder: decoder successfully started. In-force parameters:\n%s",
245 AMediaFormat_toString(_format));
246 }
247
248 void MediaCodecDecoder::stopImpl() noexcept {
249 ms_message("MediaCodecDecoder: stopping decoder");
250 AMediaCodec_stop(_impl);
251 }
252
253 void MediaCodecDecoder::resetImpl() noexcept {
254 ms_message("MediaCodecDecoder: reseting decoder");
255 if (AMediaCodec_reset(_impl) != AMEDIA_OK) {
256 ms_error("MediaCodecDecoder: decoder couldn't been reset. Throwing decoding session out");
257 AMediaCodec_delete(_impl);
258 _impl = AMediaCodec_createDecoderByType(_mime.c_str());
259 if (_impl == nullptr)
260 ms_error(
261 "MediaCodecDecoder: couldn't recreate decoding session. The decoding session is definitively lost !");
262 }
263 }
264
265 bool MediaCodecDecoder::feed(MSQueue *encodedFrame, uint64_t timestamp, bool isPs) {
266 if (_impl == nullptr) return false;
267
268 ssize_t iBufidx = AMediaCodec_dequeueInputBuffer(_impl, _timeoutUs);
269 if (iBufidx < 0) {
270 ms_error("MediaCodecDecoder: %s.", iBufidx == -1
271 ? "no buffer available for queuing this frame ! Decoder is too slow"
272 : "AMediaCodec_dequeueInputBuffer() had an exception");
273 return false;
274 }
275
276 size_t bufsize;
277 size_t streamSize;
278 uint8_t *buf = AMediaCodec_getInputBuffer(_impl, iBufidx, &bufsize);
279 if (buf == nullptr) {
280 ms_error("MediaCodecDecoder: AMediaCodec_getInputBuffer() returned NULL");
281 return false;
282 }
283
284 try {
285 streamSize = H26xUtils::nalusToByteStream(encodedFrame, buf, bufsize);
286 } catch (const invalid_argument &e) {
287 ms_error(
288 "MediaCodecDecoder: cannot convert the all the nal units content into the input buffer size : bufsize=%zu",
289 bufsize);
290 }
291
292 uint32_t flags = isPs ? BufferFlag::CodecConfig : BufferFlag::None;
293 if (AMediaCodec_queueInputBuffer(_impl, iBufidx, 0, streamSize, timestamp * 1000ULL, flags) != 0) {
294 ms_error("MediaCodecDecoder: AMediaCodec_queueInputBuffer() had an exception");
295 return false;
296 }
297
298 return true;
299 }
300
301 bool MediaCodecDecoder::isKeyFrame(const MSQueue *frame) const {
302 for (const mblk_t *nalu = ms_queue_peek_first(frame); !ms_queue_end(frame, nalu);
303 nalu = ms_queue_next(frame, nalu)) {
304 _naluHeader->parse(nalu->b_rptr);
305 if (_naluHeader->getAbsType().isKeyFramePart()) return true;
306 }
307 return false;
308 }
309
310 std::string MediaCodecDecoder::codecInfoToString(ssize_t codecStatusCode) {
311 switch (codecStatusCode) {
312 case AMEDIA_ERROR_UNKNOWN:
313 return "MediaCodec had an exception";
314 case AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED:
315 return "output buffers has changed";
316 case AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED:
317 return "output format has changed";
318 case AMEDIACODEC_INFO_TRY_AGAIN_LATER:
319 return "no output buffer available";
320 default:
321 break;
322 }
323 ostringstream os;
324 if (codecStatusCode >= 0) {
325 os << "unqueued buffer (index=" << codecStatusCode << ")";
326 } else {
327 os << "unknown error (" << codecStatusCode << ")";
328 }
329 return os.str();
330 }
331
332 } // namespace mediastreamer