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