]> git.sesse.net Git - ffmpeg/blob - libavcodec/mediacodecdec.c
0fe14846c3373564565e2fc515df9ddb8e1f0ca7
[ffmpeg] / libavcodec / mediacodecdec.c
1 /*
2  * Android MediaCodec MPEG-2 / H.264 / H.265 / MPEG-4 / VP8 / VP9 decoders
3  *
4  * Copyright (c) 2015-2016 Matthieu Bouron <matthieu.bouron stupeflix.com>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include <stdint.h>
24 #include <string.h>
25
26 #include "libavutil/avassert.h"
27 #include "libavutil/common.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/pixfmt.h"
31 #include "libavutil/internal.h"
32
33 #include "avcodec.h"
34 #include "decode.h"
35 #include "h264_parse.h"
36 #include "hevc_parse.h"
37 #include "hwaccel.h"
38 #include "internal.h"
39 #include "mediacodec_wrapper.h"
40 #include "mediacodecdec_common.h"
41
42 typedef struct MediaCodecH264DecContext {
43
44     MediaCodecDecContext *ctx;
45
46     AVPacket buffered_pkt;
47
48 } MediaCodecH264DecContext;
49
50 static av_cold int mediacodec_decode_close(AVCodecContext *avctx)
51 {
52     MediaCodecH264DecContext *s = avctx->priv_data;
53
54     ff_mediacodec_dec_close(avctx, s->ctx);
55     s->ctx = NULL;
56
57     av_packet_unref(&s->buffered_pkt);
58
59     return 0;
60 }
61
62 #if CONFIG_H264_MEDIACODEC_DECODER || CONFIG_HEVC_MEDIACODEC_DECODER
63 static int h2645_ps_to_nalu(const uint8_t *src, int src_size, uint8_t **out, int *out_size)
64 {
65     int i;
66     int ret = 0;
67     uint8_t *p = NULL;
68     static const uint8_t nalu_header[] = { 0x00, 0x00, 0x00, 0x01 };
69
70     if (!out || !out_size) {
71         return AVERROR(EINVAL);
72     }
73
74     p = av_malloc(sizeof(nalu_header) + src_size);
75     if (!p) {
76         return AVERROR(ENOMEM);
77     }
78
79     *out = p;
80     *out_size = sizeof(nalu_header) + src_size;
81
82     memcpy(p, nalu_header, sizeof(nalu_header));
83     memcpy(p + sizeof(nalu_header), src, src_size);
84
85     /* Escape 0x00, 0x00, 0x0{0-3} pattern */
86     for (i = 4; i < *out_size; i++) {
87         if (i < *out_size - 3 &&
88             p[i + 0] == 0 &&
89             p[i + 1] == 0 &&
90             p[i + 2] <= 3) {
91             uint8_t *new;
92
93             *out_size += 1;
94             new = av_realloc(*out, *out_size);
95             if (!new) {
96                 ret = AVERROR(ENOMEM);
97                 goto done;
98             }
99             *out = p = new;
100
101             i = i + 2;
102             memmove(p + i + 1, p + i, *out_size - (i + 1));
103             p[i] = 0x03;
104         }
105     }
106 done:
107     if (ret < 0) {
108         av_freep(out);
109         *out_size = 0;
110     }
111
112     return ret;
113 }
114 #endif
115
116 #if CONFIG_H264_MEDIACODEC_DECODER
117 static int h264_set_extradata(AVCodecContext *avctx, FFAMediaFormat *format)
118 {
119     int i;
120     int ret;
121
122     H264ParamSets ps;
123     const PPS *pps = NULL;
124     const SPS *sps = NULL;
125     int is_avc = 0;
126     int nal_length_size = 0;
127
128     memset(&ps, 0, sizeof(ps));
129
130     ret = ff_h264_decode_extradata(avctx->extradata, avctx->extradata_size,
131                                    &ps, &is_avc, &nal_length_size, 0, avctx);
132     if (ret < 0) {
133         goto done;
134     }
135
136     for (i = 0; i < MAX_PPS_COUNT; i++) {
137         if (ps.pps_list[i]) {
138             pps = (const PPS*)ps.pps_list[i]->data;
139             break;
140         }
141     }
142
143     if (pps) {
144         if (ps.sps_list[pps->sps_id]) {
145             sps = (const SPS*)ps.sps_list[pps->sps_id]->data;
146         }
147     }
148
149     if (pps && sps) {
150         uint8_t *data = NULL;
151         int data_size = 0;
152
153         if ((ret = h2645_ps_to_nalu(sps->data, sps->data_size, &data, &data_size)) < 0) {
154             goto done;
155         }
156         ff_AMediaFormat_setBuffer(format, "csd-0", (void*)data, data_size);
157         av_freep(&data);
158
159         if ((ret = h2645_ps_to_nalu(pps->data, pps->data_size, &data, &data_size)) < 0) {
160             goto done;
161         }
162         ff_AMediaFormat_setBuffer(format, "csd-1", (void*)data, data_size);
163         av_freep(&data);
164     } else {
165         av_log(avctx, AV_LOG_ERROR, "Could not extract PPS/SPS from extradata");
166         ret = AVERROR_INVALIDDATA;
167     }
168
169 done:
170     ff_h264_ps_uninit(&ps);
171
172     return ret;
173 }
174 #endif
175
176 #if CONFIG_HEVC_MEDIACODEC_DECODER
177 static int hevc_set_extradata(AVCodecContext *avctx, FFAMediaFormat *format)
178 {
179     int i;
180     int ret;
181
182     HEVCParamSets ps;
183     HEVCSEI sei;
184
185     const HEVCVPS *vps = NULL;
186     const HEVCPPS *pps = NULL;
187     const HEVCSPS *sps = NULL;
188     int is_nalff = 0;
189     int nal_length_size = 0;
190
191     uint8_t *vps_data = NULL;
192     uint8_t *sps_data = NULL;
193     uint8_t *pps_data = NULL;
194     int vps_data_size = 0;
195     int sps_data_size = 0;
196     int pps_data_size = 0;
197
198     memset(&ps, 0, sizeof(ps));
199     memset(&sei, 0, sizeof(sei));
200
201     ret = ff_hevc_decode_extradata(avctx->extradata, avctx->extradata_size,
202                                    &ps, &sei, &is_nalff, &nal_length_size, 0, 1, avctx);
203     if (ret < 0) {
204         goto done;
205     }
206
207     for (i = 0; i < HEVC_MAX_VPS_COUNT; i++) {
208         if (ps.vps_list[i]) {
209             vps = (const HEVCVPS*)ps.vps_list[i]->data;
210             break;
211         }
212     }
213
214     for (i = 0; i < HEVC_MAX_PPS_COUNT; i++) {
215         if (ps.pps_list[i]) {
216             pps = (const HEVCPPS*)ps.pps_list[i]->data;
217             break;
218         }
219     }
220
221     if (pps) {
222         if (ps.sps_list[pps->sps_id]) {
223             sps = (const HEVCSPS*)ps.sps_list[pps->sps_id]->data;
224         }
225     }
226
227     if (vps && pps && sps) {
228         uint8_t *data;
229         int data_size;
230
231         if ((ret = h2645_ps_to_nalu(vps->data, vps->data_size, &vps_data, &vps_data_size)) < 0 ||
232             (ret = h2645_ps_to_nalu(sps->data, sps->data_size, &sps_data, &sps_data_size)) < 0 ||
233             (ret = h2645_ps_to_nalu(pps->data, pps->data_size, &pps_data, &pps_data_size)) < 0) {
234             goto done;
235         }
236
237         data_size = vps_data_size + sps_data_size + pps_data_size;
238         data = av_mallocz(data_size);
239         if (!data) {
240             ret = AVERROR(ENOMEM);
241             goto done;
242         }
243
244         memcpy(data                                , vps_data, vps_data_size);
245         memcpy(data + vps_data_size                , sps_data, sps_data_size);
246         memcpy(data + vps_data_size + sps_data_size, pps_data, pps_data_size);
247
248         ff_AMediaFormat_setBuffer(format, "csd-0", data, data_size);
249
250         av_freep(&data);
251     } else {
252         av_log(avctx, AV_LOG_ERROR, "Could not extract VPS/PPS/SPS from extradata");
253         ret = AVERROR_INVALIDDATA;
254     }
255
256 done:
257     ff_hevc_ps_uninit(&ps);
258
259     av_freep(&vps_data);
260     av_freep(&sps_data);
261     av_freep(&pps_data);
262
263     return ret;
264 }
265 #endif
266
267 #if CONFIG_MPEG2_MEDIACODEC_DECODER || \
268     CONFIG_MPEG4_MEDIACODEC_DECODER || \
269     CONFIG_VP8_MEDIACODEC_DECODER   || \
270     CONFIG_VP9_MEDIACODEC_DECODER
271 static int common_set_extradata(AVCodecContext *avctx, FFAMediaFormat *format)
272 {
273     int ret = 0;
274
275     if (avctx->extradata) {
276         ff_AMediaFormat_setBuffer(format, "csd-0", avctx->extradata, avctx->extradata_size);
277     }
278
279     return ret;
280 }
281 #endif
282
283 static av_cold int mediacodec_decode_init(AVCodecContext *avctx)
284 {
285     int ret;
286
287     const char *codec_mime = NULL;
288
289     FFAMediaFormat *format = NULL;
290     MediaCodecH264DecContext *s = avctx->priv_data;
291
292     format = ff_AMediaFormat_new();
293     if (!format) {
294         av_log(avctx, AV_LOG_ERROR, "Failed to create media format\n");
295         ret = AVERROR_EXTERNAL;
296         goto done;
297     }
298
299     switch (avctx->codec_id) {
300 #if CONFIG_H264_MEDIACODEC_DECODER
301     case AV_CODEC_ID_H264:
302         codec_mime = "video/avc";
303
304         ret = h264_set_extradata(avctx, format);
305         if (ret < 0)
306             goto done;
307         break;
308 #endif
309 #if CONFIG_HEVC_MEDIACODEC_DECODER
310     case AV_CODEC_ID_HEVC:
311         codec_mime = "video/hevc";
312
313         ret = hevc_set_extradata(avctx, format);
314         if (ret < 0)
315             goto done;
316         break;
317 #endif
318 #if CONFIG_MPEG2_MEDIACODEC_DECODER
319     case AV_CODEC_ID_MPEG2VIDEO:
320         codec_mime = "video/mpeg2";
321
322         ret = common_set_extradata(avctx, format);
323         if (ret < 0)
324             goto done;
325         break;
326 #endif
327 #if CONFIG_MPEG4_MEDIACODEC_DECODER
328     case AV_CODEC_ID_MPEG4:
329         codec_mime = "video/mp4v-es",
330
331         ret = common_set_extradata(avctx, format);
332         if (ret < 0)
333             goto done;
334         break;
335 #endif
336 #if CONFIG_VP8_MEDIACODEC_DECODER
337     case AV_CODEC_ID_VP8:
338         codec_mime = "video/x-vnd.on2.vp8";
339
340         ret = common_set_extradata(avctx, format);
341         if (ret < 0)
342             goto done;
343         break;
344 #endif
345 #if CONFIG_VP9_MEDIACODEC_DECODER
346     case AV_CODEC_ID_VP9:
347         codec_mime = "video/x-vnd.on2.vp9";
348
349         ret = common_set_extradata(avctx, format);
350         if (ret < 0)
351             goto done;
352         break;
353 #endif
354     default:
355         av_assert0(0);
356     }
357
358     ff_AMediaFormat_setString(format, "mime", codec_mime);
359     ff_AMediaFormat_setInt32(format, "width", avctx->width);
360     ff_AMediaFormat_setInt32(format, "height", avctx->height);
361
362     s->ctx = av_mallocz(sizeof(*s->ctx));
363     if (!s->ctx) {
364         av_log(avctx, AV_LOG_ERROR, "Failed to allocate MediaCodecDecContext\n");
365         ret = AVERROR(ENOMEM);
366         goto done;
367     }
368
369     if ((ret = ff_mediacodec_dec_init(avctx, s->ctx, codec_mime, format)) < 0) {
370         s->ctx = NULL;
371         goto done;
372     }
373
374     av_log(avctx, AV_LOG_INFO, "MediaCodec started successfully, ret = %d\n", ret);
375
376 done:
377     if (format) {
378         ff_AMediaFormat_delete(format);
379     }
380
381     if (ret < 0) {
382         mediacodec_decode_close(avctx);
383     }
384
385     return ret;
386 }
387
388 static int mediacodec_send_receive(AVCodecContext *avctx,
389                                    MediaCodecH264DecContext *s,
390                                    AVFrame *frame, bool wait)
391 {
392     int ret;
393
394     /* send any pending data from buffered packet */
395     while (s->buffered_pkt.size) {
396         ret = ff_mediacodec_dec_send(avctx, s->ctx, &s->buffered_pkt);
397         if (ret == AVERROR(EAGAIN))
398             break;
399         else if (ret < 0)
400             return ret;
401         s->buffered_pkt.size -= ret;
402         s->buffered_pkt.data += ret;
403         if (s->buffered_pkt.size <= 0)
404             av_packet_unref(&s->buffered_pkt);
405     }
406
407     /* check for new frame */
408     return ff_mediacodec_dec_receive(avctx, s->ctx, frame, wait);
409 }
410
411 static int mediacodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
412 {
413     MediaCodecH264DecContext *s = avctx->priv_data;
414     int ret;
415
416     /*
417      * MediaCodec.flush() discards both input and output buffers, thus we
418      * need to delay the call to this function until the user has released or
419      * renderered the frames he retains.
420      *
421      * After we have buffered an input packet, check if the codec is in the
422      * flushing state. If it is, we need to call ff_mediacodec_dec_flush.
423      *
424      * ff_mediacodec_dec_flush returns 0 if the flush cannot be performed on
425      * the codec (because the user retains frames). The codec stays in the
426      * flushing state.
427      *
428      * ff_mediacodec_dec_flush returns 1 if the flush can actually be
429      * performed on the codec. The codec leaves the flushing state and can
430      * process again packets.
431      *
432      * ff_mediacodec_dec_flush returns a negative value if an error has
433      * occurred.
434      *
435      */
436     if (ff_mediacodec_dec_is_flushing(avctx, s->ctx)) {
437         if (!ff_mediacodec_dec_flush(avctx, s->ctx)) {
438             return AVERROR(EAGAIN);
439         }
440     }
441
442     /* flush buffered packet and check for new frame */
443     ret = mediacodec_send_receive(avctx, s, frame, false);
444     if (ret != AVERROR(EAGAIN))
445         return ret;
446
447     /* skip fetching new packet if we still have one buffered */
448     if (s->buffered_pkt.size > 0)
449         return AVERROR(EAGAIN);
450
451     /* fetch new packet or eof */
452     ret = ff_decode_get_packet(avctx, &s->buffered_pkt);
453     if (ret == AVERROR_EOF) {
454         AVPacket null_pkt = { 0 };
455         ret = ff_mediacodec_dec_send(avctx, s->ctx, &null_pkt);
456         if (ret < 0)
457             return ret;
458     }
459     else if (ret < 0)
460         return ret;
461
462     /* crank decoder with new packet */
463     return mediacodec_send_receive(avctx, s, frame, true);
464 }
465
466 static void mediacodec_decode_flush(AVCodecContext *avctx)
467 {
468     MediaCodecH264DecContext *s = avctx->priv_data;
469
470     av_packet_unref(&s->buffered_pkt);
471
472     ff_mediacodec_dec_flush(avctx, s->ctx);
473 }
474
475 static const AVCodecHWConfigInternal *mediacodec_hw_configs[] = {
476     &(const AVCodecHWConfigInternal) {
477         .public          = {
478             .pix_fmt     = AV_PIX_FMT_MEDIACODEC,
479             .methods     = AV_CODEC_HW_CONFIG_METHOD_AD_HOC |
480                            AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,
481             .device_type = AV_HWDEVICE_TYPE_MEDIACODEC,
482         },
483         .hwaccel         = NULL,
484     },
485     NULL
486 };
487
488 #define DECLARE_MEDIACODEC_VDEC(short_name, full_name, codec_id, bsf)                          \
489 AVCodec ff_##short_name##_mediacodec_decoder = {                                               \
490     .name           = #short_name "_mediacodec",                                               \
491     .long_name      = NULL_IF_CONFIG_SMALL(full_name " Android MediaCodec decoder"),           \
492     .type           = AVMEDIA_TYPE_VIDEO,                                                      \
493     .id             = codec_id,                                                                \
494     .priv_data_size = sizeof(MediaCodecH264DecContext),                                        \
495     .init           = mediacodec_decode_init,                                                  \
496     .receive_frame  = mediacodec_receive_frame,                                                \
497     .flush          = mediacodec_decode_flush,                                                 \
498     .close          = mediacodec_decode_close,                                                 \
499     .capabilities   = AV_CODEC_CAP_DELAY | AV_CODEC_CAP_AVOID_PROBING | AV_CODEC_CAP_HARDWARE, \
500     .caps_internal  = FF_CODEC_CAP_SETS_PKT_DTS,                                               \
501     .bsfs           = bsf,                                                                     \
502     .hw_configs     = mediacodec_hw_configs,                                                   \
503     .wrapper_name   = "mediacodec",                                                            \
504 };                                                                                             \
505
506 #if CONFIG_H264_MEDIACODEC_DECODER
507 DECLARE_MEDIACODEC_VDEC(h264, "H.264", AV_CODEC_ID_H264, "h264_mp4toannexb")
508 #endif
509
510 #if CONFIG_HEVC_MEDIACODEC_DECODER
511 DECLARE_MEDIACODEC_VDEC(hevc, "H.265", AV_CODEC_ID_HEVC, "hevc_mp4toannexb")
512 #endif
513
514 #if CONFIG_MPEG2_MEDIACODEC_DECODER
515 DECLARE_MEDIACODEC_VDEC(mpeg2, "MPEG-2", AV_CODEC_ID_MPEG2VIDEO, NULL)
516 #endif
517
518 #if CONFIG_MPEG4_MEDIACODEC_DECODER
519 DECLARE_MEDIACODEC_VDEC(mpeg4, "MPEG-4", AV_CODEC_ID_MPEG4, NULL)
520 #endif
521
522 #if CONFIG_VP8_MEDIACODEC_DECODER
523 DECLARE_MEDIACODEC_VDEC(vp8, "VP8", AV_CODEC_ID_VP8, NULL)
524 #endif
525
526 #if CONFIG_VP9_MEDIACODEC_DECODER
527 DECLARE_MEDIACODEC_VDEC(vp9, "VP9", AV_CODEC_ID_VP9, NULL)
528 #endif