]> git.sesse.net Git - ffmpeg/blob - libavcodec/mediacodecdec.c
Merge commit 'e62ff72fc1052273deb708ba715f73e5187281d4'
[ffmpeg] / libavcodec / mediacodecdec.c
1 /*
2  * Android MediaCodec decoder
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 <string.h>
24 #include <sys/types.h>
25
26 #include "libavutil/common.h"
27 #include "libavutil/mem.h"
28 #include "libavutil/log.h"
29 #include "libavutil/pixfmt.h"
30 #include "libavutil/time.h"
31 #include "libavutil/timestamp.h"
32
33 #include "avcodec.h"
34 #include "internal.h"
35
36 #include "mediacodec_sw_buffer.h"
37 #include "mediacodec_wrapper.h"
38 #include "mediacodecdec.h"
39
40 /**
41  * OMX.k3.video.decoder.avc, OMX.NVIDIA.* OMX.SEC.avc.dec and OMX.google
42  * codec workarounds used in various place are taken from the Gstreamer
43  * project.
44  *
45  * Gstreamer references:
46  * https://cgit.freedesktop.org/gstreamer/gst-plugins-bad/tree/sys/androidmedia/
47  *
48  * Gstreamer copyright notice:
49  *
50  * Copyright (C) 2012, Collabora Ltd.
51  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>
52  *
53  * Copyright (C) 2012, Rafaël Carré <funman@videolanorg>
54  *
55  * Copyright (C) 2015, Sebastian Dröge <sebastian@centricular.com>
56  *
57  * Copyright (C) 2014-2015, Collabora Ltd.
58  *   Author: Matthieu Bouron <matthieu.bouron@gcollabora.com>
59  *
60  * Copyright (C) 2015, Edward Hervey
61  *   Author: Edward Hervey <bilboed@gmail.com>
62  *
63  * Copyright (C) 2015, Matthew Waters <matthew@centricular.com>
64  *
65  * This library is free software; you can redistribute it and/or
66  * modify it under the terms of the GNU Lesser General Public
67  * License as published by the Free Software Foundation
68  * version 2.1 of the License.
69  *
70  * This library is distributed in the hope that it will be useful,
71  * but WITHOUT ANY WARRANTY; without even the implied warranty of
72  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
73  * Lesser General Public License for more details.
74  *
75  * You should have received a copy of the GNU Lesser General Public
76  * License along with this library; if not, write to the Free Software
77  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA
78  *
79  */
80
81 #define INPUT_DEQUEUE_TIMEOUT_US 8000
82 #define OUTPUT_DEQUEUE_TIMEOUT_US 8000
83 #define OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US 1000000
84
85 enum {
86     COLOR_FormatYUV420Planar                              = 0x13,
87     COLOR_FormatYUV420SemiPlanar                          = 0x15,
88     COLOR_FormatYCbYCr                                    = 0x19,
89     COLOR_FormatAndroidOpaque                             = 0x7F000789,
90     COLOR_QCOM_FormatYUV420SemiPlanar                     = 0x7fa30c00,
91     COLOR_QCOM_FormatYUV420SemiPlanar32m                  = 0x7fa30c04,
92     COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka = 0x7fa30c03,
93     COLOR_TI_FormatYUV420PackedSemiPlanar                 = 0x7f000100,
94     COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced       = 0x7f000001,
95 };
96
97 static const struct {
98
99     int color_format;
100     enum AVPixelFormat pix_fmt;
101
102 } color_formats[] = {
103
104     { COLOR_FormatYUV420Planar,                              AV_PIX_FMT_YUV420P },
105     { COLOR_FormatYUV420SemiPlanar,                          AV_PIX_FMT_NV12    },
106     { COLOR_QCOM_FormatYUV420SemiPlanar,                     AV_PIX_FMT_NV12    },
107     { COLOR_QCOM_FormatYUV420SemiPlanar32m,                  AV_PIX_FMT_NV12    },
108     { COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka, AV_PIX_FMT_NV12    },
109     { COLOR_TI_FormatYUV420PackedSemiPlanar,                 AV_PIX_FMT_NV12    },
110     { COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced,       AV_PIX_FMT_NV12    },
111     { 0 }
112 };
113
114 static enum AVPixelFormat mcdec_map_color_format(AVCodecContext *avctx,
115                                                  MediaCodecDecContext *s,
116                                                  int color_format)
117 {
118     int i;
119     enum AVPixelFormat ret = AV_PIX_FMT_NONE;
120
121     if (!strcmp(s->codec_name, "OMX.k3.video.decoder.avc") && color_format == COLOR_FormatYCbYCr) {
122         s->color_format = color_format = COLOR_TI_FormatYUV420PackedSemiPlanar;
123     }
124
125     for (i = 0; i < FF_ARRAY_ELEMS(color_formats); i++) {
126         if (color_formats[i].color_format == color_format) {
127             return color_formats[i].pix_fmt;
128         }
129     }
130
131     av_log(avctx, AV_LOG_ERROR, "Output color format 0x%x (value=%d) is not supported\n",
132         color_format, color_format);
133
134     return ret;
135 }
136
137 static int mediacodec_wrap_buffer(AVCodecContext *avctx,
138                                   MediaCodecDecContext *s,
139                                   uint8_t *data,
140                                   size_t size,
141                                   ssize_t index,
142                                   FFAMediaCodecBufferInfo *info,
143                                   AVFrame *frame)
144 {
145     int ret = 0;
146     int status = 0;
147
148     frame->width = avctx->width;
149     frame->height = avctx->height;
150     frame->format = avctx->pix_fmt;
151
152     /* MediaCodec buffers needs to be copied to our own refcounted buffers
153      * because the flush command invalidates all input and output buffers.
154      */
155     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {
156         av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer\n");
157         goto done;
158     }
159
160     /* Override frame->pkt_pts as ff_get_buffer will override its value based
161      * on the last avpacket received which is not in sync with the frame:
162      *   * N avpackets can be pushed before 1 frame is actually returned
163      *   * 0-sized avpackets are pushed to flush remaining frames at EOS */
164     frame->pkt_pts = info->presentationTimeUs;
165     frame->pkt_dts = AV_NOPTS_VALUE;
166
167     av_log(avctx, AV_LOG_DEBUG,
168             "Frame: width=%d stride=%d height=%d slice-height=%d "
169             "crop-top=%d crop-bottom=%d crop-left=%d crop-right=%d encoder=%s\n"
170             "destination linesizes=%d,%d,%d\n" ,
171             avctx->width, s->stride, avctx->height, s->slice_height,
172             s->crop_top, s->crop_bottom, s->crop_left, s->crop_right, s->codec_name,
173             frame->linesize[0], frame->linesize[1], frame->linesize[2]);
174
175     switch (s->color_format) {
176     case COLOR_FormatYUV420Planar:
177         ff_mediacodec_sw_buffer_copy_yuv420_planar(avctx, s, data, size, info, frame);
178         break;
179     case COLOR_FormatYUV420SemiPlanar:
180     case COLOR_QCOM_FormatYUV420SemiPlanar:
181     case COLOR_QCOM_FormatYUV420SemiPlanar32m:
182         ff_mediacodec_sw_buffer_copy_yuv420_semi_planar(avctx, s, data, size, info, frame);
183         break;
184     case COLOR_TI_FormatYUV420PackedSemiPlanar:
185     case COLOR_TI_FormatYUV420PackedSemiPlanarInterlaced:
186         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar(avctx, s, data, size, info, frame);
187         break;
188     case COLOR_QCOM_FormatYUV420PackedSemiPlanar64x32Tile2m8ka:
189         ff_mediacodec_sw_buffer_copy_yuv420_packed_semi_planar_64x32Tile2m8ka(avctx, s, data, size, info, frame);
190         break;
191     default:
192         av_log(avctx, AV_LOG_ERROR, "Unsupported color format 0x%x (value=%d)\n",
193             s->color_format, s->color_format);
194         ret = AVERROR(EINVAL);
195         goto done;
196     }
197
198     ret = 0;
199 done:
200     status = ff_AMediaCodec_releaseOutputBuffer(s->codec, index, 0);
201     if (status < 0) {
202         av_log(avctx, AV_LOG_ERROR, "Failed to release output buffer\n");
203         ret = AVERROR_EXTERNAL;
204     }
205
206     return ret;
207 }
208
209 static int mediacodec_dec_parse_format(AVCodecContext *avctx, MediaCodecDecContext *s)
210 {
211     int width = 0;
212     int height = 0;
213     int32_t value = 0;
214     char *format = NULL;
215
216     if (!s->format) {
217         av_log(avctx, AV_LOG_ERROR, "Output MediaFormat is not set\n");
218         return AVERROR(EINVAL);
219     }
220
221     format = ff_AMediaFormat_toString(s->format);
222     if (!format) {
223         return AVERROR_EXTERNAL;
224     }
225     av_log(avctx, AV_LOG_DEBUG, "Parsing MediaFormat %s\n", format);
226     av_freep(&format);
227
228     /* Mandatory fields */
229     if (!ff_AMediaFormat_getInt32(s->format, "width", &value)) {
230         format = ff_AMediaFormat_toString(s->format);
231         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", "width", format);
232         av_freep(&format);
233         return AVERROR_EXTERNAL;
234     }
235     s->width = value;
236
237     if (!ff_AMediaFormat_getInt32(s->format, "height", &value)) {
238         format = ff_AMediaFormat_toString(s->format);
239         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", "height", format);
240         av_freep(&format);
241         return AVERROR_EXTERNAL;
242     }
243     s->height = value;
244
245     if (!ff_AMediaFormat_getInt32(s->format, "stride", &value)) {
246         format = ff_AMediaFormat_toString(s->format);
247         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", "stride", format);
248         av_freep(&format);
249         return AVERROR_EXTERNAL;
250     }
251     s->stride = value > 0 ? value : s->width;
252
253     if (!ff_AMediaFormat_getInt32(s->format, "slice-height", &value)) {
254         format = ff_AMediaFormat_toString(s->format);
255         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", "slice-height", format);
256         av_freep(&format);
257         return AVERROR_EXTERNAL;
258     }
259     s->slice_height = value > 0 ? value : s->height;
260
261     if (strstr(s->codec_name, "OMX.Nvidia.")) {
262         s->slice_height = FFALIGN(s->height, 16);
263     } else if (strstr(s->codec_name, "OMX.SEC.avc.dec")) {
264         s->slice_height = avctx->height;
265         s->stride = avctx->width;
266     }
267
268     if (!ff_AMediaFormat_getInt32(s->format, "color-format", &value)) {
269         format = ff_AMediaFormat_toString(s->format);
270         av_log(avctx, AV_LOG_ERROR, "Could not get %s from format %s\n", "color-format", format);
271         av_freep(&format);
272         return AVERROR_EXTERNAL;
273     }
274     s->color_format = value;
275
276     s->pix_fmt = avctx->pix_fmt = mcdec_map_color_format(avctx, s, value);
277     if (avctx->pix_fmt == AV_PIX_FMT_NONE) {
278         av_log(avctx, AV_LOG_ERROR, "Output color format is not supported\n");
279         return AVERROR(EINVAL);
280     }
281
282     /* Optional fields */
283     if (ff_AMediaFormat_getInt32(s->format, "crop-top", &value))
284         s->crop_top = value;
285
286     if (ff_AMediaFormat_getInt32(s->format, "crop-bottom", &value))
287         s->crop_bottom = value;
288
289     if (ff_AMediaFormat_getInt32(s->format, "crop-left", &value))
290         s->crop_left = value;
291
292     if (ff_AMediaFormat_getInt32(s->format, "crop-right", &value))
293         s->crop_right = value;
294
295     width = s->crop_right + 1 - s->crop_left;
296     height = s->crop_bottom + 1 - s->crop_top;
297
298     av_log(avctx, AV_LOG_INFO,
299         "Output crop parameters top=%d bottom=%d left=%d right=%d, "
300         "resulting dimensions width=%d height=%d\n",
301         s->crop_top, s->crop_bottom, s->crop_left, s->crop_right,
302         width, height);
303
304     return ff_set_dimensions(avctx, width, height);
305 }
306
307 int ff_mediacodec_dec_init(AVCodecContext *avctx, MediaCodecDecContext *s,
308                            const char *mime, FFAMediaFormat *format)
309 {
310     int ret = 0;
311     int status;
312     int profile;
313
314     s->first_buffer_at = av_gettime();
315
316     profile = ff_AMediaCodecProfile_getProfileFromAVCodecContext(avctx);
317     if (profile < 0) {
318         av_log(avctx, AV_LOG_WARNING, "Unsupported or unknown profile");
319     }
320
321     s->codec_name = ff_AMediaCodecList_getCodecNameByType(mime, profile, 0, avctx);
322     if (!s->codec_name) {
323         ret = AVERROR_EXTERNAL;
324         goto fail;
325     }
326
327     av_log(avctx, AV_LOG_DEBUG, "Found decoder %s\n", s->codec_name);
328     s->codec = ff_AMediaCodec_createCodecByName(s->codec_name);
329     if (!s->codec) {
330         av_log(avctx, AV_LOG_ERROR, "Failed to create media decoder for type %s and name %s\n", mime, s->codec_name);
331         ret = AVERROR_EXTERNAL;
332         goto fail;
333     }
334
335     status = ff_AMediaCodec_configure(s->codec, format, NULL, NULL, 0);
336     if (status < 0) {
337         char *desc = ff_AMediaFormat_toString(format);
338         av_log(avctx, AV_LOG_ERROR,
339             "Failed to configure codec (status = %d) with format %s\n",
340             status, desc);
341         av_freep(&desc);
342
343         ret = AVERROR_EXTERNAL;
344         goto fail;
345     }
346
347     status = ff_AMediaCodec_start(s->codec);
348     if (status < 0) {
349         char *desc = ff_AMediaFormat_toString(format);
350         av_log(avctx, AV_LOG_ERROR,
351             "Failed to start codec (status = %d) with format %s\n",
352             status, desc);
353         av_freep(&desc);
354         ret = AVERROR_EXTERNAL;
355         goto fail;
356     }
357
358     s->format = ff_AMediaCodec_getOutputFormat(s->codec);
359     if (s->format) {
360         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
361             av_log(avctx, AV_LOG_ERROR,
362                 "Failed to configure context\n");
363             goto fail;
364         }
365     }
366
367     av_log(avctx, AV_LOG_DEBUG, "MediaCodec %p started successfully\n", s->codec);
368
369     return 0;
370
371 fail:
372     av_log(avctx, AV_LOG_ERROR, "MediaCodec %p failed to start\n", s->codec);
373     ff_mediacodec_dec_close(avctx, s);
374     return ret;
375 }
376
377 int ff_mediacodec_dec_decode(AVCodecContext *avctx, MediaCodecDecContext *s,
378                              AVFrame *frame, int *got_frame,
379                              AVPacket *pkt)
380 {
381     int ret;
382     int offset = 0;
383     int need_flushing = 0;
384     uint8_t *data;
385     ssize_t index;
386     size_t size;
387     FFAMediaCodec *codec = s->codec;
388     FFAMediaCodecBufferInfo info = { 0 };
389
390     int status;
391
392     int64_t input_dequeue_timeout_us = INPUT_DEQUEUE_TIMEOUT_US;
393     int64_t output_dequeue_timeout_us = OUTPUT_DEQUEUE_TIMEOUT_US;
394
395     if (pkt->size == 0) {
396         need_flushing = 1;
397     }
398
399     if (s->flushing && need_flushing && s->queued_buffer_nb <= 0) {
400         return 0;
401     }
402
403     while (offset < pkt->size || (need_flushing && !s->flushing)) {
404         int size;
405
406         index = ff_AMediaCodec_dequeueInputBuffer(codec, input_dequeue_timeout_us);
407         if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
408             break;
409         }
410
411         if (index < 0) {
412             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue input buffer (status=%zd)\n", index);
413             return AVERROR_EXTERNAL;
414         }
415
416         data = ff_AMediaCodec_getInputBuffer(codec, index, &size);
417         if (!data) {
418             av_log(avctx, AV_LOG_ERROR, "Failed to get input buffer\n");
419             return AVERROR_EXTERNAL;
420         }
421
422         if (need_flushing) {
423             uint32_t flags = ff_AMediaCodec_getBufferFlagEndOfStream(codec);
424
425             av_log(avctx, AV_LOG_DEBUG, "Sending End Of Stream signal\n");
426
427             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, 0, pkt->pts, flags);
428             if (status < 0) {
429                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input empty buffer (status = %d)\n", status);
430                 return AVERROR_EXTERNAL;
431             }
432
433             s->flushing = 1;
434             break;
435         } else {
436             size = FFMIN(pkt->size - offset, size);
437
438             memcpy(data, pkt->data + offset, size);
439             offset += size;
440
441             status = ff_AMediaCodec_queueInputBuffer(codec, index, 0, size, pkt->pts, 0);
442             if (status < 0) {
443                 av_log(avctx, AV_LOG_ERROR, "Failed to queue input buffer (status = %d)\n", status);
444                 return AVERROR_EXTERNAL;
445             }
446
447             s->queued_buffer_nb++;
448             if (s->queued_buffer_nb > s->queued_buffer_max)
449                 s->queued_buffer_max = s->queued_buffer_nb;
450         }
451     }
452
453     if (s->flushing) {
454         /* If the codec is flushing, block for a fair amount of time to
455         * ensure we got a frame */
456         output_dequeue_timeout_us = OUTPUT_DEQUEUE_BLOCK_TIMEOUT_US;
457     } else if (s->dequeued_buffer_nb == 0) {
458         /* If the codec hasn't produced any frames, do not block so we
459          * can push data to it as fast as possible, and get the first
460          * frame */
461         output_dequeue_timeout_us = 0;
462     }
463
464     index = ff_AMediaCodec_dequeueOutputBuffer(codec, &info, output_dequeue_timeout_us);
465     if (index >= 0) {
466         int ret;
467
468         if (!s->first_buffer++) {
469             av_log(avctx, AV_LOG_DEBUG, "Got first buffer after %fms\n", (av_gettime() - s->first_buffer_at) / 1000);
470         }
471
472         av_log(avctx, AV_LOG_DEBUG, "Got output buffer %zd"
473                 " offset=%" PRIi32 " size=%" PRIi32 " ts=%" PRIi64
474                 " flags=%" PRIu32 "\n", index, info.offset, info.size,
475                 info.presentationTimeUs, info.flags);
476
477         data = ff_AMediaCodec_getOutputBuffer(codec, index, &size);
478         if (!data) {
479             av_log(avctx, AV_LOG_ERROR, "Failed to get output buffer\n");
480             return AVERROR_EXTERNAL;
481         }
482
483         if ((ret = mediacodec_wrap_buffer(avctx, s, data, size, index, &info, frame)) < 0) {
484             av_log(avctx, AV_LOG_ERROR, "Failed to wrap MediaCodec buffer\n");
485             return ret;
486         }
487
488         *got_frame = 1;
489         s->queued_buffer_nb--;
490         s->dequeued_buffer_nb++;
491
492     } else if (ff_AMediaCodec_infoOutputFormatChanged(codec, index)) {
493         char *format = NULL;
494
495         if (s->format) {
496             status = ff_AMediaFormat_delete(s->format);
497             if (status < 0) {
498                 av_log(avctx, AV_LOG_ERROR, "Failed to delete MediaFormat %p\n", s->format);
499             }
500         }
501
502         s->format = ff_AMediaCodec_getOutputFormat(codec);
503         if (!s->format) {
504             av_log(avctx, AV_LOG_ERROR, "Failed to get output format\n");
505             return AVERROR_EXTERNAL;
506         }
507
508         format = ff_AMediaFormat_toString(s->format);
509         if (!format) {
510             return AVERROR_EXTERNAL;
511         }
512         av_log(avctx, AV_LOG_INFO, "Output MediaFormat changed to %s\n", format);
513         av_freep(&format);
514
515         if ((ret = mediacodec_dec_parse_format(avctx, s)) < 0) {
516             return ret;
517         }
518
519     } else if (ff_AMediaCodec_infoOutputBuffersChanged(codec, index)) {
520         ff_AMediaCodec_cleanOutputBuffers(codec);
521     } else if (ff_AMediaCodec_infoTryAgainLater(codec, index)) {
522         if (s->flushing) {
523             av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer within %" PRIi64 "ms "
524                                         "while flushing remaining frames, output will probably lack last %d frames\n",
525                                         output_dequeue_timeout_us / 1000, s->queued_buffer_nb);
526         } else {
527             av_log(avctx, AV_LOG_DEBUG, "No output buffer available, try again later\n");
528         }
529     } else {
530         av_log(avctx, AV_LOG_ERROR, "Failed to dequeue output buffer (status=%zd)\n", index);
531         return AVERROR_EXTERNAL;
532     }
533
534     return offset;
535 }
536
537 int ff_mediacodec_dec_flush(AVCodecContext *avctx, MediaCodecDecContext *s)
538 {
539     FFAMediaCodec *codec = s->codec;
540     int status;
541
542     s->queued_buffer_nb = 0;
543     s->dequeued_buffer_nb = 0;
544
545     s->flushing = 0;
546
547     status = ff_AMediaCodec_flush(codec);
548     if (status < 0) {
549         av_log(avctx, AV_LOG_ERROR, "Failed to flush codec\n");
550         return AVERROR_EXTERNAL;
551     }
552
553     s->first_buffer = 0;
554     s->first_buffer_at = av_gettime();
555
556     return 0;
557 }
558
559 int ff_mediacodec_dec_close(AVCodecContext *avctx, MediaCodecDecContext *s)
560 {
561     if (s->codec) {
562         ff_AMediaCodec_delete(s->codec);
563         s->codec = NULL;
564     }
565
566     if (s->format) {
567         ff_AMediaFormat_delete(s->format);
568         s->format = NULL;
569     }
570
571     av_freep(&s->codec_name);
572
573     return 0;
574 }