avviddec: Fix pool reallocation logic
[platform/upstream/gst-libav.git] / ext / libav / gstavviddec.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
17  * Boston, MA 02110-1301, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include <assert.h>
25 #include <string.h>
26
27 #include <libavcodec/avcodec.h>
28
29 #include <gst/gst.h>
30 #include <gst/video/video.h>
31 #include <gst/video/gstvideodecoder.h>
32 #include <gst/video/gstvideometa.h>
33 #include <gst/video/gstvideopool.h>
34
35 #include "gstav.h"
36 #include "gstavcodecmap.h"
37 #include "gstavutils.h"
38 #include "gstavviddec.h"
39
40 GST_DEBUG_CATEGORY_EXTERN (GST_CAT_PERFORMANCE);
41
42 #define MAX_TS_MASK 0xff
43
44 #define DEFAULT_LOWRES                  0
45 #define DEFAULT_SKIPFRAME               0
46 #define DEFAULT_DIRECT_RENDERING        TRUE
47 #define DEFAULT_DEBUG_MV                FALSE
48 #define DEFAULT_MAX_THREADS             0
49 #define DEFAULT_OUTPUT_CORRUPT          TRUE
50 #define REQUIRED_POOL_MAX_BUFFERS       32
51 #define DEFAULT_STRIDE_ALIGN            15
52 #define DEFAULT_ALLOC_PARAM             { 0, DEFAULT_STRIDE_ALIGN, 0, 0, }
53
54 enum
55 {
56   PROP_0,
57   PROP_LOWRES,
58   PROP_SKIPFRAME,
59   PROP_DIRECT_RENDERING,
60   PROP_DEBUG_MV,
61   PROP_MAX_THREADS,
62   PROP_OUTPUT_CORRUPT,
63   PROP_LAST
64 };
65
66 /* A number of function prototypes are given so we can refer to them later. */
67 static void gst_ffmpegviddec_base_init (GstFFMpegVidDecClass * klass);
68 static void gst_ffmpegviddec_class_init (GstFFMpegVidDecClass * klass);
69 static void gst_ffmpegviddec_init (GstFFMpegVidDec * ffmpegdec);
70 static void gst_ffmpegviddec_finalize (GObject * object);
71
72 static gboolean gst_ffmpegviddec_set_format (GstVideoDecoder * decoder,
73     GstVideoCodecState * state);
74 static GstFlowReturn gst_ffmpegviddec_handle_frame (GstVideoDecoder * decoder,
75     GstVideoCodecFrame * frame);
76 static gboolean gst_ffmpegviddec_start (GstVideoDecoder * decoder);
77 static gboolean gst_ffmpegviddec_stop (GstVideoDecoder * decoder);
78 static gboolean gst_ffmpegviddec_flush (GstVideoDecoder * decoder);
79 static gboolean gst_ffmpegviddec_decide_allocation (GstVideoDecoder * decoder,
80     GstQuery * query);
81 static gboolean gst_ffmpegviddec_propose_allocation (GstVideoDecoder * decoder,
82     GstQuery * query);
83
84 static void gst_ffmpegviddec_set_property (GObject * object,
85     guint prop_id, const GValue * value, GParamSpec * pspec);
86 static void gst_ffmpegviddec_get_property (GObject * object,
87     guint prop_id, GValue * value, GParamSpec * pspec);
88
89 static gboolean gst_ffmpegviddec_negotiate (GstFFMpegVidDec * ffmpegdec,
90     AVCodecContext * context, AVFrame * picture);
91
92 /* some sort of bufferpool handling, but different */
93 static int gst_ffmpegviddec_get_buffer2 (AVCodecContext * context,
94     AVFrame * picture, int flags);
95
96 static GstFlowReturn gst_ffmpegviddec_finish (GstVideoDecoder * decoder);
97 static void gst_ffmpegviddec_drain (GstFFMpegVidDec * ffmpegdec);
98
99 static gboolean picture_changed (GstFFMpegVidDec * ffmpegdec,
100     AVFrame * picture);
101 static gboolean context_changed (GstFFMpegVidDec * ffmpegdec,
102     AVCodecContext * context);
103
104 #define GST_FFDEC_PARAMS_QDATA g_quark_from_static_string("avdec-params")
105
106 static GstElementClass *parent_class = NULL;
107
108 #define GST_FFMPEGVIDDEC_TYPE_LOWRES (gst_ffmpegviddec_lowres_get_type())
109 static GType
110 gst_ffmpegviddec_lowres_get_type (void)
111 {
112   static GType ffmpegdec_lowres_type = 0;
113
114   if (!ffmpegdec_lowres_type) {
115     static const GEnumValue ffmpegdec_lowres[] = {
116       {0, "0", "full"},
117       {1, "1", "1/2-size"},
118       {2, "2", "1/4-size"},
119       {0, NULL, NULL},
120     };
121
122     ffmpegdec_lowres_type =
123         g_enum_register_static ("GstLibAVVidDecLowres", ffmpegdec_lowres);
124   }
125
126   return ffmpegdec_lowres_type;
127 }
128
129 #define GST_FFMPEGVIDDEC_TYPE_SKIPFRAME (gst_ffmpegviddec_skipframe_get_type())
130 static GType
131 gst_ffmpegviddec_skipframe_get_type (void)
132 {
133   static GType ffmpegdec_skipframe_type = 0;
134
135   if (!ffmpegdec_skipframe_type) {
136     static const GEnumValue ffmpegdec_skipframe[] = {
137       {0, "0", "Skip nothing"},
138       {1, "1", "Skip B-frames"},
139       {2, "2", "Skip IDCT/Dequantization"},
140       {5, "5", "Skip everything"},
141       {0, NULL, NULL},
142     };
143
144     ffmpegdec_skipframe_type =
145         g_enum_register_static ("GstLibAVVidDecSkipFrame", ffmpegdec_skipframe);
146   }
147
148   return ffmpegdec_skipframe_type;
149 }
150
151 static void
152 gst_ffmpegviddec_base_init (GstFFMpegVidDecClass * klass)
153 {
154   GstElementClass *element_class = GST_ELEMENT_CLASS (klass);
155   GstPadTemplate *sinktempl, *srctempl;
156   GstCaps *sinkcaps, *srccaps;
157   AVCodec *in_plugin;
158   gchar *longname, *description;
159
160   in_plugin =
161       (AVCodec *) g_type_get_qdata (G_OBJECT_CLASS_TYPE (klass),
162       GST_FFDEC_PARAMS_QDATA);
163   g_assert (in_plugin != NULL);
164
165   /* construct the element details struct */
166   longname = g_strdup_printf ("libav %s decoder", in_plugin->long_name);
167   description = g_strdup_printf ("libav %s decoder", in_plugin->name);
168   gst_element_class_set_metadata (element_class, longname,
169       "Codec/Decoder/Video", description,
170       "Wim Taymans <wim.taymans@gmail.com>, "
171       "Ronald Bultje <rbultje@ronald.bitfreak.net>, "
172       "Edward Hervey <bilboed@bilboed.com>");
173   g_free (longname);
174   g_free (description);
175
176   /* get the caps */
177   sinkcaps = gst_ffmpeg_codecid_to_caps (in_plugin->id, NULL, FALSE);
178   if (!sinkcaps) {
179     GST_DEBUG ("Couldn't get sink caps for decoder '%s'", in_plugin->name);
180     sinkcaps = gst_caps_new_empty_simple ("unknown/unknown");
181   }
182   srccaps = gst_ffmpeg_codectype_to_video_caps (NULL,
183       in_plugin->id, FALSE, in_plugin);
184   if (!srccaps) {
185     GST_DEBUG ("Couldn't get source caps for decoder '%s'", in_plugin->name);
186     srccaps = gst_caps_from_string ("video/x-raw");
187   }
188
189   /* pad templates */
190   sinktempl = gst_pad_template_new ("sink", GST_PAD_SINK,
191       GST_PAD_ALWAYS, sinkcaps);
192   srctempl = gst_pad_template_new ("src", GST_PAD_SRC, GST_PAD_ALWAYS, srccaps);
193
194   gst_element_class_add_pad_template (element_class, srctempl);
195   gst_element_class_add_pad_template (element_class, sinktempl);
196
197   klass->in_plugin = in_plugin;
198 }
199
200 static void
201 gst_ffmpegviddec_class_init (GstFFMpegVidDecClass * klass)
202 {
203   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
204   GstVideoDecoderClass *viddec_class = GST_VIDEO_DECODER_CLASS (klass);
205   int caps;
206
207   parent_class = g_type_class_peek_parent (klass);
208
209   gobject_class->finalize = gst_ffmpegviddec_finalize;
210
211   gobject_class->set_property = gst_ffmpegviddec_set_property;
212   gobject_class->get_property = gst_ffmpegviddec_get_property;
213
214   g_object_class_install_property (gobject_class, PROP_SKIPFRAME,
215       g_param_spec_enum ("skip-frame", "Skip frames",
216           "Which types of frames to skip during decoding",
217           GST_FFMPEGVIDDEC_TYPE_SKIPFRAME, 0,
218           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
219   g_object_class_install_property (gobject_class, PROP_LOWRES,
220       g_param_spec_enum ("lowres", "Low resolution",
221           "At which resolution to decode images",
222           GST_FFMPEGVIDDEC_TYPE_LOWRES, 0,
223           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
224   g_object_class_install_property (gobject_class, PROP_DIRECT_RENDERING,
225       g_param_spec_boolean ("direct-rendering", "Direct Rendering",
226           "Enable direct rendering", DEFAULT_DIRECT_RENDERING,
227           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
228   g_object_class_install_property (gobject_class, PROP_DEBUG_MV,
229       g_param_spec_boolean ("debug-mv", "Debug motion vectors",
230           "Whether libav should print motion vectors on top of the image",
231           DEFAULT_DEBUG_MV, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
232   g_object_class_install_property (gobject_class, PROP_OUTPUT_CORRUPT,
233       g_param_spec_boolean ("output-corrupt", "Output corrupt buffers",
234           "Whether libav should output frames even if corrupted",
235           DEFAULT_OUTPUT_CORRUPT, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
236
237   caps = klass->in_plugin->capabilities;
238   if (caps & (CODEC_CAP_FRAME_THREADS | CODEC_CAP_SLICE_THREADS)) {
239     g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MAX_THREADS,
240         g_param_spec_int ("max-threads", "Maximum decode threads",
241             "Maximum number of worker threads to spawn. (0 = auto)",
242             0, G_MAXINT, DEFAULT_MAX_THREADS,
243             G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
244   }
245
246   viddec_class->set_format = gst_ffmpegviddec_set_format;
247   viddec_class->handle_frame = gst_ffmpegviddec_handle_frame;
248   viddec_class->start = gst_ffmpegviddec_start;
249   viddec_class->stop = gst_ffmpegviddec_stop;
250   viddec_class->flush = gst_ffmpegviddec_flush;
251   viddec_class->finish = gst_ffmpegviddec_finish;
252   viddec_class->drain = gst_ffmpegviddec_finish;        /* drain and finish are the same to us */
253   viddec_class->decide_allocation = gst_ffmpegviddec_decide_allocation;
254   viddec_class->propose_allocation = gst_ffmpegviddec_propose_allocation;
255 }
256
257 static void
258 gst_ffmpegviddec_init (GstFFMpegVidDec * ffmpegdec)
259 {
260   GstFFMpegVidDecClass *klass =
261       (GstFFMpegVidDecClass *) G_OBJECT_GET_CLASS (ffmpegdec);
262
263   /* some ffmpeg data */
264   ffmpegdec->context = avcodec_alloc_context3 (klass->in_plugin);
265   ffmpegdec->context->opaque = ffmpegdec;
266   ffmpegdec->picture = av_frame_alloc ();
267   ffmpegdec->opened = FALSE;
268   ffmpegdec->skip_frame = ffmpegdec->lowres = 0;
269   ffmpegdec->direct_rendering = DEFAULT_DIRECT_RENDERING;
270   ffmpegdec->debug_mv = DEFAULT_DEBUG_MV;
271   ffmpegdec->max_threads = DEFAULT_MAX_THREADS;
272   ffmpegdec->output_corrupt = DEFAULT_OUTPUT_CORRUPT;
273
274   GST_PAD_SET_ACCEPT_TEMPLATE (GST_VIDEO_DECODER_SINK_PAD (ffmpegdec));
275   gst_video_decoder_set_use_default_pad_acceptcaps (GST_VIDEO_DECODER_CAST
276       (ffmpegdec), TRUE);
277
278   gst_video_decoder_set_needs_format (GST_VIDEO_DECODER (ffmpegdec), TRUE);
279 }
280
281 static void
282 gst_ffmpegviddec_finalize (GObject * object)
283 {
284   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) object;
285
286   av_frame_free (&ffmpegdec->picture);
287
288   if (ffmpegdec->context != NULL) {
289     gst_ffmpeg_avcodec_close (ffmpegdec->context);
290     av_free (ffmpegdec->context);
291     ffmpegdec->context = NULL;
292   }
293
294   G_OBJECT_CLASS (parent_class)->finalize (object);
295 }
296
297 static void
298 gst_ffmpegviddec_context_set_flags (AVCodecContext * context, guint flags,
299     gboolean enable)
300 {
301   g_return_if_fail (context != NULL);
302
303   if (enable)
304     context->flags |= flags;
305   else
306     context->flags &= ~flags;
307 }
308
309 /* with LOCK */
310 static gboolean
311 gst_ffmpegviddec_close (GstFFMpegVidDec * ffmpegdec, gboolean reset)
312 {
313   GstFFMpegVidDecClass *oclass;
314   gint i;
315
316   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
317
318   GST_LOG_OBJECT (ffmpegdec, "closing ffmpeg codec");
319
320   gst_caps_replace (&ffmpegdec->last_caps, NULL);
321
322   gst_ffmpeg_avcodec_close (ffmpegdec->context);
323   ffmpegdec->opened = FALSE;
324
325   for (i = 0; i < G_N_ELEMENTS (ffmpegdec->stride); i++)
326     ffmpegdec->stride[i] = -1;
327
328   gst_buffer_replace (&ffmpegdec->palette, NULL);
329
330   if (ffmpegdec->context->extradata) {
331     av_free (ffmpegdec->context->extradata);
332     ffmpegdec->context->extradata = NULL;
333   }
334   if (ffmpegdec->context->slice_offset) {
335     g_free (ffmpegdec->context->slice_offset);
336     ffmpegdec->context->slice_offset = NULL;
337   }
338   if (reset) {
339     if (avcodec_get_context_defaults3 (ffmpegdec->context,
340             oclass->in_plugin) < 0) {
341       GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
342       return FALSE;
343     }
344     ffmpegdec->context->opaque = ffmpegdec;
345   }
346   return TRUE;
347 }
348
349 /* with LOCK */
350 static gboolean
351 gst_ffmpegviddec_open (GstFFMpegVidDec * ffmpegdec)
352 {
353   GstFFMpegVidDecClass *oclass;
354   gint i;
355
356   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
357
358   if (gst_ffmpeg_avcodec_open (ffmpegdec->context, oclass->in_plugin) < 0)
359     goto could_not_open;
360
361   for (i = 0; i < G_N_ELEMENTS (ffmpegdec->stride); i++)
362     ffmpegdec->stride[i] = -1;
363
364   ffmpegdec->opened = TRUE;
365   ffmpegdec->is_realvideo = FALSE;
366
367   GST_LOG_OBJECT (ffmpegdec, "Opened libav codec %s, id %d",
368       oclass->in_plugin->name, oclass->in_plugin->id);
369
370   switch (oclass->in_plugin->id) {
371     case AV_CODEC_ID_RV10:
372     case AV_CODEC_ID_RV30:
373     case AV_CODEC_ID_RV20:
374     case AV_CODEC_ID_RV40:
375       ffmpegdec->is_realvideo = TRUE;
376       break;
377     default:
378       GST_LOG_OBJECT (ffmpegdec, "Parser deactivated for format");
379       break;
380   }
381
382   gst_ffmpegviddec_context_set_flags (ffmpegdec->context,
383       CODEC_FLAG_OUTPUT_CORRUPT, ffmpegdec->output_corrupt);
384
385   return TRUE;
386
387   /* ERRORS */
388 could_not_open:
389   {
390     gst_ffmpegviddec_close (ffmpegdec, TRUE);
391     GST_DEBUG_OBJECT (ffmpegdec, "avdec_%s: Failed to open libav codec",
392         oclass->in_plugin->name);
393     return FALSE;
394   }
395 }
396
397 static void
398 gst_ffmpegviddec_get_palette (GstFFMpegVidDec * ffmpegdec,
399     GstVideoCodecState * state)
400 {
401   GstStructure *str = gst_caps_get_structure (state->caps, 0);
402   const GValue *palette_v;
403   GstBuffer *palette;
404
405   /* do we have a palette? */
406   if ((palette_v = gst_structure_get_value (str, "palette_data"))) {
407     palette = gst_value_get_buffer (palette_v);
408     GST_DEBUG ("got palette data %p", palette);
409     if (gst_buffer_get_size (palette) >= AVPALETTE_SIZE) {
410       gst_buffer_replace (&ffmpegdec->palette, palette);
411     }
412   }
413 }
414
415
416 static gboolean
417 gst_ffmpegviddec_set_format (GstVideoDecoder * decoder,
418     GstVideoCodecState * state)
419 {
420   GstFFMpegVidDec *ffmpegdec;
421   GstFFMpegVidDecClass *oclass;
422   GstClockTime latency = GST_CLOCK_TIME_NONE;
423   gboolean ret = FALSE;
424
425   ffmpegdec = (GstFFMpegVidDec *) decoder;
426   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
427
428   if (ffmpegdec->last_caps != NULL &&
429       gst_caps_is_equal (ffmpegdec->last_caps, state->caps)) {
430     return TRUE;
431   }
432
433   GST_DEBUG_OBJECT (ffmpegdec, "setcaps called");
434
435   GST_OBJECT_LOCK (ffmpegdec);
436   /* stupid check for VC1 */
437   if ((oclass->in_plugin->id == AV_CODEC_ID_WMV3) ||
438       (oclass->in_plugin->id == AV_CODEC_ID_VC1))
439     oclass->in_plugin->id = gst_ffmpeg_caps_to_codecid (state->caps, NULL);
440
441   /* close old session */
442   if (ffmpegdec->opened) {
443     GST_OBJECT_UNLOCK (ffmpegdec);
444     gst_ffmpegviddec_drain (ffmpegdec);
445     GST_OBJECT_LOCK (ffmpegdec);
446     if (!gst_ffmpegviddec_close (ffmpegdec, TRUE)) {
447       GST_OBJECT_UNLOCK (ffmpegdec);
448       return FALSE;
449     }
450     ffmpegdec->pic_pix_fmt = 0;
451     ffmpegdec->pic_width = 0;
452     ffmpegdec->pic_height = 0;
453     ffmpegdec->pic_par_n = 0;
454     ffmpegdec->pic_par_d = 0;
455     ffmpegdec->ctx_ticks = 0;
456     ffmpegdec->ctx_time_n = 0;
457     ffmpegdec->ctx_time_d = 0;
458   }
459
460   gst_caps_replace (&ffmpegdec->last_caps, state->caps);
461
462   /* set buffer functions */
463   ffmpegdec->context->get_buffer2 = gst_ffmpegviddec_get_buffer2;
464   ffmpegdec->context->get_buffer = NULL;
465   ffmpegdec->context->reget_buffer = NULL;
466   ffmpegdec->context->release_buffer = NULL;
467   ffmpegdec->context->draw_horiz_band = NULL;
468
469   /* reset coded_width/_height to prevent it being reused from last time when
470    * the codec is opened again, causing a mismatch and possible
471    * segfault/corruption. (Common scenario when renegotiating caps) */
472   ffmpegdec->context->coded_width = 0;
473   ffmpegdec->context->coded_height = 0;
474
475   GST_LOG_OBJECT (ffmpegdec, "size %dx%d", ffmpegdec->context->width,
476       ffmpegdec->context->height);
477
478   /* FIXME : Create a method that takes GstVideoCodecState instead */
479   /* get size and so */
480   gst_ffmpeg_caps_with_codecid (oclass->in_plugin->id,
481       oclass->in_plugin->type, state->caps, ffmpegdec->context);
482
483   GST_LOG_OBJECT (ffmpegdec, "size after %dx%d", ffmpegdec->context->width,
484       ffmpegdec->context->height);
485
486   gst_ffmpegviddec_get_palette (ffmpegdec, state);
487
488   if (!ffmpegdec->context->time_base.den || !ffmpegdec->context->time_base.num) {
489     GST_DEBUG_OBJECT (ffmpegdec, "forcing 25/1 framerate");
490     ffmpegdec->context->time_base.num = 1;
491     ffmpegdec->context->time_base.den = 25;
492   }
493
494   /* workaround encoder bugs */
495   ffmpegdec->context->workaround_bugs |= FF_BUG_AUTODETECT;
496   ffmpegdec->context->err_recognition = 1;
497
498   /* for slow cpus */
499   ffmpegdec->context->lowres = ffmpegdec->lowres;
500   ffmpegdec->context->skip_frame = ffmpegdec->skip_frame;
501
502   /* ffmpeg can draw motion vectors on top of the image (not every decoder
503    * supports it) */
504   ffmpegdec->context->debug_mv = ffmpegdec->debug_mv;
505
506   {
507     GstQuery *query;
508     gboolean is_live;
509
510     if (ffmpegdec->max_threads == 0) {
511       if (!(oclass->in_plugin->capabilities & CODEC_CAP_AUTO_THREADS))
512         ffmpegdec->context->thread_count = gst_ffmpeg_auto_max_threads ();
513       else
514         ffmpegdec->context->thread_count = 0;
515     } else
516       ffmpegdec->context->thread_count = ffmpegdec->max_threads;
517
518     query = gst_query_new_latency ();
519     is_live = FALSE;
520     /* Check if upstream is live. If it isn't we can enable frame based
521      * threading, which is adding latency */
522     if (gst_pad_peer_query (GST_VIDEO_DECODER_SINK_PAD (ffmpegdec), query)) {
523       gst_query_parse_latency (query, &is_live, NULL, NULL);
524     }
525     gst_query_unref (query);
526
527     if (is_live)
528       ffmpegdec->context->thread_type = FF_THREAD_SLICE;
529     else
530       ffmpegdec->context->thread_type = FF_THREAD_SLICE | FF_THREAD_FRAME;
531   }
532
533   /* open codec - we don't select an output pix_fmt yet,
534    * simply because we don't know! We only get it
535    * during playback... */
536   if (!gst_ffmpegviddec_open (ffmpegdec))
537     goto open_failed;
538
539   if (ffmpegdec->input_state)
540     gst_video_codec_state_unref (ffmpegdec->input_state);
541   ffmpegdec->input_state = gst_video_codec_state_ref (state);
542
543   if (ffmpegdec->input_state->info.fps_n) {
544     GstVideoInfo *info = &ffmpegdec->input_state->info;
545     latency = gst_util_uint64_scale_ceil (
546         (ffmpegdec->context->has_b_frames) * GST_SECOND, info->fps_d,
547         info->fps_n);
548   }
549
550   ret = TRUE;
551
552 done:
553   GST_OBJECT_UNLOCK (ffmpegdec);
554
555   if (GST_CLOCK_TIME_IS_VALID (latency))
556     gst_video_decoder_set_latency (decoder, latency, latency);
557
558   return ret;
559
560   /* ERRORS */
561 open_failed:
562   {
563     GST_DEBUG_OBJECT (ffmpegdec, "Failed to open");
564     goto done;
565   }
566 }
567
568 typedef struct
569 {
570   GstFFMpegVidDec *ffmpegdec;
571   GstVideoCodecFrame *frame;
572   gboolean mapped;
573   GstVideoFrame vframe;
574   GstBuffer *buffer;
575   AVBufferRef *avbuffer;
576 } GstFFMpegVidDecVideoFrame;
577
578 static GstFFMpegVidDecVideoFrame *
579 gst_ffmpegviddec_video_frame_new (GstFFMpegVidDec * ffmpegdec,
580     GstVideoCodecFrame * frame)
581 {
582   GstFFMpegVidDecVideoFrame *dframe;
583
584   dframe = g_slice_new0 (GstFFMpegVidDecVideoFrame);
585   dframe->ffmpegdec = ffmpegdec;
586   dframe->frame = frame;
587
588   GST_DEBUG_OBJECT (ffmpegdec, "new video frame %p", dframe);
589
590   return dframe;
591 }
592
593 static void
594 gst_ffmpegviddec_video_frame_free (GstFFMpegVidDec * ffmpegdec,
595     GstFFMpegVidDecVideoFrame * frame)
596 {
597   GST_DEBUG_OBJECT (ffmpegdec, "free video frame %p", frame);
598
599   if (frame->mapped)
600     gst_video_frame_unmap (&frame->vframe);
601   gst_video_decoder_release_frame (GST_VIDEO_DECODER (ffmpegdec), frame->frame);
602   gst_buffer_replace (&frame->buffer, NULL);
603   if (frame->avbuffer) {
604     av_buffer_unref (&frame->avbuffer);
605   }
606   g_slice_free (GstFFMpegVidDecVideoFrame, frame);
607 }
608
609 static void
610 dummy_free_buffer (void *opaque, uint8_t * data)
611 {
612   GstFFMpegVidDecVideoFrame *frame = opaque;
613
614   gst_ffmpegviddec_video_frame_free (frame->ffmpegdec, frame);
615 }
616
617 /* This function prepares the pool configuration for direct rendering. To use
618  * this method, the codec should support direct rendering and the pool should
619  * support video meta and video alignement */
620 static void
621 gst_ffmpegvideodec_prepare_dr_pool (GstFFMpegVidDec * ffmpegdec,
622     GstBufferPool * pool, GstVideoInfo * info, GstStructure * config)
623 {
624   GstVideoAlignment align;
625   gint width, height;
626   gint linesize_align[4];
627   gint i;
628   guint edge;
629
630   width = GST_VIDEO_INFO_WIDTH (info);
631   height = GST_VIDEO_INFO_HEIGHT (info);
632
633   /* let ffmpeg find the alignment and padding */
634   avcodec_align_dimensions2 (ffmpegdec->context, &width, &height,
635       linesize_align);
636
637   if (ffmpegdec->context->flags & CODEC_FLAG_EMU_EDGE)
638     edge = 0;
639   else
640     edge = avcodec_get_edge_width ();
641
642   /* increase the size for the padding */
643   width += edge << 1;
644   height += edge << 1;
645
646   align.padding_top = edge;
647   align.padding_left = edge;
648   align.padding_right = width - GST_VIDEO_INFO_WIDTH (info) - edge;
649   align.padding_bottom = height - GST_VIDEO_INFO_HEIGHT (info) - edge;
650
651   /* add extra padding to match libav buffer allocation sizes */
652   align.padding_bottom++;
653
654   for (i = 0; i < GST_VIDEO_MAX_PLANES; i++)
655     align.stride_align[i] = (linesize_align[i] > 0 ? linesize_align[i] - 1 : 0);
656
657   GST_DEBUG_OBJECT (ffmpegdec, "aligned dimension %dx%d -> %dx%d "
658       "padding t:%u l:%u r:%u b:%u, stride_align %d:%d:%d:%d",
659       GST_VIDEO_INFO_WIDTH (info),
660       GST_VIDEO_INFO_HEIGHT (info), width, height, align.padding_top,
661       align.padding_left, align.padding_right, align.padding_bottom,
662       align.stride_align[0], align.stride_align[1], align.stride_align[2],
663       align.stride_align[3]);
664
665   gst_buffer_pool_config_add_option (config,
666       GST_BUFFER_POOL_OPTION_VIDEO_ALIGNMENT);
667   gst_buffer_pool_config_set_video_alignment (config, &align);
668 }
669
670 static void
671 gst_ffmpegviddec_ensure_internal_pool (GstFFMpegVidDec * ffmpegdec,
672     AVFrame * picture)
673 {
674   GstAllocationParams params = DEFAULT_ALLOC_PARAM;
675   GstVideoInfo info;
676   GstVideoFormat format;
677   GstCaps *caps;
678   GstStructure *config;
679   gint i;
680
681   if (ffmpegdec->internal_pool != NULL &&
682       ffmpegdec->pool_width == picture->width &&
683       ffmpegdec->pool_height == picture->height &&
684       ffmpegdec->pool_format == picture->format)
685     return;
686
687   GST_DEBUG_OBJECT (ffmpegdec, "Updating internal pool (%i, %i)",
688       picture->width, picture->height);
689
690   format = gst_ffmpeg_pixfmt_to_videoformat (picture->format);
691   gst_video_info_set_format (&info, format, picture->width, picture->height);
692
693   for (i = 0; i < G_N_ELEMENTS (ffmpegdec->stride); i++)
694     ffmpegdec->stride[i] = -1;
695
696   if (ffmpegdec->internal_pool)
697     gst_object_unref (ffmpegdec->internal_pool);
698
699   ffmpegdec->internal_pool = gst_video_buffer_pool_new ();
700   config = gst_buffer_pool_get_config (ffmpegdec->internal_pool);
701
702   caps = gst_video_info_to_caps (&info);
703   gst_buffer_pool_config_set_params (config, caps, info.size, 2, 0);
704   gst_buffer_pool_config_set_allocator (config, NULL, &params);
705   gst_buffer_pool_config_add_option (config, GST_BUFFER_POOL_OPTION_VIDEO_META);
706
707   gst_ffmpegvideodec_prepare_dr_pool (ffmpegdec,
708       ffmpegdec->internal_pool, &info, config);
709   /* generic video pool never fails */
710   gst_buffer_pool_set_config (ffmpegdec->internal_pool, config);
711   gst_caps_unref (caps);
712
713   gst_buffer_pool_set_active (ffmpegdec->internal_pool, TRUE);
714
715   /* Remember pool size so we can detect changes */
716   ffmpegdec->pool_width = picture->width;
717   ffmpegdec->pool_height = picture->height;
718   ffmpegdec->pool_format = picture->format;
719   ffmpegdec->pool_info = info;
720 }
721
722 static gboolean
723 gst_ffmpegviddec_can_direct_render (GstFFMpegVidDec * ffmpegdec)
724 {
725   GstFFMpegVidDecClass *oclass;
726
727   if (!ffmpegdec->direct_rendering)
728     return FALSE;
729
730   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
731   return ((oclass->in_plugin->capabilities & CODEC_CAP_DR1) == CODEC_CAP_DR1);
732 }
733
734 /* called when ffmpeg wants us to allocate a buffer to write the decoded frame
735  * into. We try to give it memory from our pool */
736 static int
737 gst_ffmpegviddec_get_buffer2 (AVCodecContext * context, AVFrame * picture,
738     int flags)
739 {
740   GstVideoCodecFrame *frame;
741   GstFFMpegVidDecVideoFrame *dframe;
742   GstFFMpegVidDec *ffmpegdec;
743   gint c;
744   GstFlowReturn ret;
745
746   ffmpegdec = (GstFFMpegVidDec *) context->opaque;
747
748   GST_DEBUG_OBJECT (ffmpegdec, "getting buffer picture %p", picture);
749
750   /* apply the last info we have seen to this picture, when we get the
751    * picture back from ffmpeg we can use this to correctly timestamp the output
752    * buffer */
753   GST_DEBUG_OBJECT (ffmpegdec, "opaque value SN %d",
754       (gint32) picture->reordered_opaque);
755
756   frame =
757       gst_video_decoder_get_frame (GST_VIDEO_DECODER (ffmpegdec),
758       picture->reordered_opaque);
759   if (G_UNLIKELY (frame == NULL))
760     goto no_frame;
761
762   /* now it has a buffer allocated, so it is real and will also
763    * be _released */
764   GST_VIDEO_CODEC_FRAME_FLAG_UNSET (frame,
765       GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY);
766
767   if (G_UNLIKELY (frame->output_buffer != NULL))
768     goto duplicate_frame;
769
770   /* GstFFMpegVidDecVideoFrame receives the frame ref */
771   if (picture->opaque) {
772     dframe = picture->opaque;
773     dframe->frame = frame;
774   } else {
775     picture->opaque = dframe =
776         gst_ffmpegviddec_video_frame_new (ffmpegdec, frame);
777   }
778
779   GST_DEBUG_OBJECT (ffmpegdec, "storing opaque %p", dframe);
780
781   if (!gst_ffmpegviddec_can_direct_render (ffmpegdec))
782     goto no_dr;
783
784   gst_ffmpegviddec_ensure_internal_pool (ffmpegdec, picture);
785
786   ret = gst_buffer_pool_acquire_buffer (ffmpegdec->internal_pool,
787       &frame->output_buffer, NULL);
788   if (ret != GST_FLOW_OK)
789     goto alloc_failed;
790
791   /* piggy-backed alloc'ed on the frame,
792    * and there was much rejoicing and we are grateful.
793    * Now take away buffer from frame, we will give it back later when decoded.
794    * This allows multiple request for a buffer per frame; unusual but possible. */
795   gst_buffer_replace (&dframe->buffer, frame->output_buffer);
796   gst_buffer_replace (&frame->output_buffer, NULL);
797
798   /* Fill avpicture */
799   if (!gst_video_frame_map (&dframe->vframe, &ffmpegdec->pool_info,
800           dframe->buffer, GST_MAP_READWRITE))
801     goto invalid_frame;
802   dframe->mapped = TRUE;
803
804   for (c = 0; c < AV_NUM_DATA_POINTERS; c++) {
805     if (c < GST_VIDEO_INFO_N_PLANES (&ffmpegdec->pool_info)) {
806       picture->data[c] = GST_VIDEO_FRAME_PLANE_DATA (&dframe->vframe, c);
807       picture->linesize[c] = GST_VIDEO_FRAME_PLANE_STRIDE (&dframe->vframe, c);
808
809       if (ffmpegdec->stride[c] == -1)
810         ffmpegdec->stride[c] = picture->linesize[c];
811
812       /* libav does not allow stride changes, decide allocation should check
813        * before replacing the internal pool with a downstream pool.
814        * https://bugzilla.gnome.org/show_bug.cgi?id=704769
815        * https://bugzilla.libav.org/show_bug.cgi?id=556
816        */
817       g_assert (picture->linesize[c] == ffmpegdec->stride[c]);
818     } else {
819       picture->data[c] = NULL;
820       picture->linesize[c] = 0;
821     }
822     GST_LOG_OBJECT (ffmpegdec, "linesize %d, data %p", picture->linesize[c],
823         picture->data[c]);
824   }
825
826   picture->buf[0] = av_buffer_create (NULL, 0, dummy_free_buffer, dframe, 0);
827
828   /* tell ffmpeg we own this buffer, transfer the ref we have on the buffer to
829    * the opaque data. */
830   picture->type = FF_BUFFER_TYPE_USER;
831
832   GST_LOG_OBJECT (ffmpegdec, "returned frame %p", dframe->buffer);
833
834   return 0;
835
836   /* fallbacks */
837 no_dr:
838   {
839     GST_LOG_OBJECT (ffmpegdec, "direct rendering disabled, fallback alloc");
840     goto fallback;
841   }
842 alloc_failed:
843   {
844     /* alloc default buffer when we can't get one from downstream */
845     GST_LOG_OBJECT (ffmpegdec, "alloc failed, fallback alloc");
846     goto fallback;
847   }
848 invalid_frame:
849   {
850     /* alloc default buffer when we can't get one from downstream */
851     GST_LOG_OBJECT (ffmpegdec, "failed to map frame, fallback alloc");
852     gst_buffer_replace (&dframe->buffer, NULL);
853     goto fallback;
854   }
855 fallback:
856   {
857     int c;
858     int ret = avcodec_default_get_buffer2 (context, picture, flags);
859
860     for (c = 0; c < AV_NUM_DATA_POINTERS; c++) {
861       ffmpegdec->stride[c] = picture->linesize[c];
862     }
863     /* Wrap our buffer around the default one to be able to have a callback
864      * when our data can be freed. Just putting our data into the first free
865      * buffer might not work if there are too many allocated already
866      */
867     if (picture->buf[0]) {
868       dframe->avbuffer = picture->buf[0];
869       picture->buf[0] =
870           av_buffer_create (picture->buf[0]->data, picture->buf[0]->size,
871           dummy_free_buffer, dframe, 0);
872     } else {
873       picture->buf[0] =
874           av_buffer_create (NULL, 0, dummy_free_buffer, dframe, 0);
875     }
876
877     return ret;
878   }
879 duplicate_frame:
880   {
881     GST_WARNING_OBJECT (ffmpegdec, "already alloc'ed output buffer for frame");
882     gst_video_codec_frame_unref (frame);
883     return -1;
884   }
885 no_frame:
886   {
887     GST_WARNING_OBJECT (ffmpegdec, "Couldn't get codec frame !");
888     return -1;
889   }
890 }
891
892 static gboolean
893 picture_changed (GstFFMpegVidDec * ffmpegdec, AVFrame * picture)
894 {
895   return !(ffmpegdec->pic_width == picture->width
896       && ffmpegdec->pic_height == picture->height
897       && ffmpegdec->pic_pix_fmt == picture->format
898       && ffmpegdec->pic_par_n == picture->sample_aspect_ratio.num
899       && ffmpegdec->pic_par_d == picture->sample_aspect_ratio.den
900       && ffmpegdec->pic_interlaced == picture->interlaced_frame);
901 }
902
903 static gboolean
904 context_changed (GstFFMpegVidDec * ffmpegdec, AVCodecContext * context)
905 {
906   return !(ffmpegdec->ctx_ticks == context->ticks_per_frame
907       && ffmpegdec->ctx_time_n == context->time_base.num
908       && ffmpegdec->ctx_time_d == context->time_base.den);
909 }
910
911 static gboolean
912 update_video_context (GstFFMpegVidDec * ffmpegdec, AVCodecContext * context,
913     AVFrame * picture)
914 {
915   if (!picture_changed (ffmpegdec, picture)
916       && !context_changed (ffmpegdec, context))
917     return FALSE;
918
919   GST_DEBUG_OBJECT (ffmpegdec,
920       "Renegotiating video from %dx%d@ %d:%d PAR %d/%d fps pixfmt %d to %dx%d@ %d:%d PAR %d/%d fps pixfmt %d",
921       ffmpegdec->pic_width, ffmpegdec->pic_height,
922       ffmpegdec->pic_par_n, ffmpegdec->pic_par_d,
923       ffmpegdec->ctx_time_n, ffmpegdec->ctx_time_d,
924       ffmpegdec->pic_pix_fmt,
925       picture->width, picture->height,
926       picture->sample_aspect_ratio.num,
927       picture->sample_aspect_ratio.den,
928       context->time_base.num, context->time_base.den, picture->format);
929
930   ffmpegdec->pic_pix_fmt = picture->format;
931   ffmpegdec->pic_width = picture->width;
932   ffmpegdec->pic_height = picture->height;
933   ffmpegdec->pic_par_n = picture->sample_aspect_ratio.num;
934   ffmpegdec->pic_par_d = picture->sample_aspect_ratio.den;
935   ffmpegdec->pic_interlaced = picture->interlaced_frame;
936   ffmpegdec->ctx_ticks = context->ticks_per_frame;
937   ffmpegdec->ctx_time_n = context->time_base.num;
938   ffmpegdec->ctx_time_d = context->time_base.den;
939
940   return TRUE;
941 }
942
943 static void
944 gst_ffmpegviddec_update_par (GstFFMpegVidDec * ffmpegdec,
945     GstVideoInfo * in_info, GstVideoInfo * out_info)
946 {
947   gboolean demuxer_par_set = FALSE;
948   gboolean decoder_par_set = FALSE;
949   gint demuxer_num = 1, demuxer_denom = 1;
950   gint decoder_num = 1, decoder_denom = 1;
951
952   if (in_info->par_n && in_info->par_d) {
953     demuxer_num = in_info->par_n;
954     demuxer_denom = in_info->par_d;
955     demuxer_par_set = TRUE;
956     GST_DEBUG_OBJECT (ffmpegdec, "Demuxer PAR: %d:%d", demuxer_num,
957         demuxer_denom);
958   }
959
960   if (ffmpegdec->pic_par_n && ffmpegdec->pic_par_d) {
961     decoder_num = ffmpegdec->pic_par_n;
962     decoder_denom = ffmpegdec->pic_par_d;
963     decoder_par_set = TRUE;
964     GST_DEBUG_OBJECT (ffmpegdec, "Decoder PAR: %d:%d", decoder_num,
965         decoder_denom);
966   }
967
968   if (!demuxer_par_set && !decoder_par_set)
969     goto no_par;
970
971   if (demuxer_par_set && !decoder_par_set)
972     goto use_demuxer_par;
973
974   if (decoder_par_set && !demuxer_par_set)
975     goto use_decoder_par;
976
977   /* Both the demuxer and the decoder provide a PAR. If one of
978    * the two PARs is 1:1 and the other one is not, use the one
979    * that is not 1:1. */
980   if (demuxer_num == demuxer_denom && decoder_num != decoder_denom)
981     goto use_decoder_par;
982
983   if (decoder_num == decoder_denom && demuxer_num != demuxer_denom)
984     goto use_demuxer_par;
985
986   /* Both PARs are non-1:1, so use the PAR provided by the demuxer */
987   goto use_demuxer_par;
988
989 use_decoder_par:
990   {
991     GST_DEBUG_OBJECT (ffmpegdec,
992         "Setting decoder provided pixel-aspect-ratio of %u:%u", decoder_num,
993         decoder_denom);
994     out_info->par_n = decoder_num;
995     out_info->par_d = decoder_denom;
996     return;
997   }
998 use_demuxer_par:
999   {
1000     GST_DEBUG_OBJECT (ffmpegdec,
1001         "Setting demuxer provided pixel-aspect-ratio of %u:%u", demuxer_num,
1002         demuxer_denom);
1003     out_info->par_n = demuxer_num;
1004     out_info->par_d = demuxer_denom;
1005     return;
1006   }
1007 no_par:
1008   {
1009     GST_DEBUG_OBJECT (ffmpegdec,
1010         "Neither demuxer nor codec provide a pixel-aspect-ratio");
1011     out_info->par_n = 1;
1012     out_info->par_d = 1;
1013     return;
1014   }
1015 }
1016
1017 static gboolean
1018 gst_ffmpegviddec_negotiate (GstFFMpegVidDec * ffmpegdec,
1019     AVCodecContext * context, AVFrame * picture)
1020 {
1021   GstVideoFormat fmt;
1022   GstVideoInfo *in_info, *out_info;
1023   GstVideoCodecState *output_state;
1024   gint fps_n, fps_d;
1025
1026   if (!update_video_context (ffmpegdec, context, picture))
1027     return TRUE;
1028
1029   fmt = gst_ffmpeg_pixfmt_to_videoformat (ffmpegdec->pic_pix_fmt);
1030   if (G_UNLIKELY (fmt == GST_VIDEO_FORMAT_UNKNOWN))
1031     goto unknown_format;
1032
1033   output_state =
1034       gst_video_decoder_set_output_state (GST_VIDEO_DECODER (ffmpegdec), fmt,
1035       ffmpegdec->pic_width, ffmpegdec->pic_height, ffmpegdec->input_state);
1036   if (ffmpegdec->output_state)
1037     gst_video_codec_state_unref (ffmpegdec->output_state);
1038   ffmpegdec->output_state = output_state;
1039
1040   in_info = &ffmpegdec->input_state->info;
1041   out_info = &ffmpegdec->output_state->info;
1042
1043   /* set the interlaced flag */
1044   if (ffmpegdec->pic_interlaced)
1045     out_info->interlace_mode = GST_VIDEO_INTERLACE_MODE_MIXED;
1046   else
1047     out_info->interlace_mode = GST_VIDEO_INTERLACE_MODE_PROGRESSIVE;
1048
1049   switch (context->chroma_sample_location) {
1050     case 1:
1051       out_info->chroma_site = GST_VIDEO_CHROMA_SITE_MPEG2;
1052       break;
1053     case 2:
1054       out_info->chroma_site = GST_VIDEO_CHROMA_SITE_JPEG;
1055       break;
1056     case 3:
1057       out_info->chroma_site = GST_VIDEO_CHROMA_SITE_DV;
1058       break;
1059     case 4:
1060       out_info->chroma_site = GST_VIDEO_CHROMA_SITE_V_COSITED;
1061       break;
1062     default:
1063       break;
1064   }
1065
1066   /* try to find a good framerate */
1067   if ((in_info->fps_d && in_info->fps_n) ||
1068       GST_VIDEO_INFO_FLAG_IS_SET (in_info, GST_VIDEO_FLAG_VARIABLE_FPS)) {
1069     /* take framerate from input when it was specified (#313970) */
1070     fps_n = in_info->fps_n;
1071     fps_d = in_info->fps_d;
1072   } else {
1073     fps_n = ffmpegdec->ctx_time_d / ffmpegdec->ctx_ticks;
1074     fps_d = ffmpegdec->ctx_time_n;
1075
1076     if (!fps_d) {
1077       GST_LOG_OBJECT (ffmpegdec, "invalid framerate: %d/0, -> %d/1", fps_n,
1078           fps_n);
1079       fps_d = 1;
1080     }
1081     if (gst_util_fraction_compare (fps_n, fps_d, 1000, 1) > 0) {
1082       GST_LOG_OBJECT (ffmpegdec, "excessive framerate: %d/%d, -> 0/1", fps_n,
1083           fps_d);
1084       fps_n = 0;
1085       fps_d = 1;
1086     }
1087   }
1088
1089   GST_LOG_OBJECT (ffmpegdec, "setting framerate: %d/%d", fps_n, fps_d);
1090   out_info->fps_n = fps_n;
1091   out_info->fps_d = fps_d;
1092
1093   /* calculate and update par now */
1094   gst_ffmpegviddec_update_par (ffmpegdec, in_info, out_info);
1095
1096   /* Copy stereo/multiview info from upstream if set */
1097   if (GST_VIDEO_INFO_MULTIVIEW_MODE (in_info) != GST_VIDEO_MULTIVIEW_MODE_NONE) {
1098     GST_VIDEO_INFO_MULTIVIEW_MODE (out_info) =
1099         GST_VIDEO_INFO_MULTIVIEW_MODE (in_info);
1100     GST_VIDEO_INFO_MULTIVIEW_FLAGS (out_info) =
1101         GST_VIDEO_INFO_MULTIVIEW_FLAGS (in_info);
1102   }
1103
1104   if (!gst_video_decoder_negotiate (GST_VIDEO_DECODER (ffmpegdec)))
1105     goto negotiate_failed;
1106
1107   return TRUE;
1108
1109   /* ERRORS */
1110 unknown_format:
1111   {
1112     GST_ERROR_OBJECT (ffmpegdec,
1113         "decoder requires a video format unsupported by GStreamer");
1114     return FALSE;
1115   }
1116 negotiate_failed:
1117   {
1118     /* Reset so we try again next time even if force==FALSE */
1119     ffmpegdec->pic_pix_fmt = 0;
1120     ffmpegdec->pic_width = 0;
1121     ffmpegdec->pic_height = 0;
1122     ffmpegdec->pic_par_n = 0;
1123     ffmpegdec->pic_par_d = 0;
1124     ffmpegdec->ctx_ticks = 0;
1125     ffmpegdec->ctx_time_n = 0;
1126     ffmpegdec->ctx_time_d = 0;
1127
1128     GST_ERROR_OBJECT (ffmpegdec, "negotiation failed");
1129     return FALSE;
1130   }
1131 }
1132
1133 /* perform qos calculations before decoding the next frame.
1134  *
1135  * Sets the skip_frame flag and if things are really bad, skips to the next
1136  * keyframe.
1137  *
1138  */
1139 static void
1140 gst_ffmpegviddec_do_qos (GstFFMpegVidDec * ffmpegdec,
1141     GstVideoCodecFrame * frame, gboolean * mode_switch)
1142 {
1143   GstClockTimeDiff diff;
1144   GstSegmentFlags skip_flags =
1145       GST_VIDEO_DECODER_INPUT_SEGMENT (ffmpegdec).flags;
1146
1147   *mode_switch = FALSE;
1148
1149   if (frame == NULL)
1150     return;
1151
1152   if (skip_flags & GST_SEGMENT_FLAG_TRICKMODE_KEY_UNITS) {
1153     ffmpegdec->context->skip_frame = AVDISCARD_NONKEY;
1154     *mode_switch = TRUE;
1155   } else if (skip_flags & GST_SEGMENT_FLAG_TRICKMODE) {
1156     ffmpegdec->context->skip_frame = AVDISCARD_NONREF;
1157     *mode_switch = TRUE;
1158   }
1159
1160   diff =
1161       gst_video_decoder_get_max_decode_time (GST_VIDEO_DECODER (ffmpegdec),
1162       frame);
1163
1164   /* if we don't have timing info, then we don't do QoS */
1165   if (G_UNLIKELY (diff == G_MAXINT64))
1166     return;
1167
1168   GST_DEBUG_OBJECT (ffmpegdec, "decoding time %" G_GINT64_FORMAT, diff);
1169
1170   if (*mode_switch == FALSE) {
1171     if (diff > 0 && ffmpegdec->context->skip_frame != AVDISCARD_DEFAULT) {
1172       ffmpegdec->context->skip_frame = AVDISCARD_DEFAULT;
1173       *mode_switch = TRUE;
1174       GST_DEBUG_OBJECT (ffmpegdec, "QOS: normal mode");
1175     }
1176
1177     else if (diff <= 0 && ffmpegdec->context->skip_frame != AVDISCARD_NONREF) {
1178       ffmpegdec->context->skip_frame = AVDISCARD_NONREF;
1179       *mode_switch = TRUE;
1180       GST_DEBUG_OBJECT (ffmpegdec,
1181           "QOS: hurry up, diff %" G_GINT64_FORMAT " >= 0", diff);
1182     }
1183   }
1184 }
1185
1186 /* get an outbuf buffer with the current picture */
1187 static GstFlowReturn
1188 get_output_buffer (GstFFMpegVidDec * ffmpegdec, GstVideoCodecFrame * frame)
1189 {
1190   GstFlowReturn ret = GST_FLOW_OK;
1191   AVPicture pic, *outpic;
1192   GstVideoFrame vframe;
1193   GstVideoInfo *info;
1194   gint c;
1195
1196   GST_LOG_OBJECT (ffmpegdec, "get output buffer");
1197
1198   if (!ffmpegdec->output_state)
1199     goto not_negotiated;
1200
1201   ret =
1202       gst_video_decoder_allocate_output_frame (GST_VIDEO_DECODER (ffmpegdec),
1203       frame);
1204   if (G_UNLIKELY (ret != GST_FLOW_OK))
1205     goto alloc_failed;
1206
1207   /* original ffmpeg code does not handle odd sizes correctly.
1208    * This patched up version does */
1209   /* Fill avpicture */
1210   info = &ffmpegdec->output_state->info;
1211   if (!gst_video_frame_map (&vframe, info, frame->output_buffer,
1212           GST_MAP_READ | GST_MAP_WRITE))
1213     goto alloc_failed;
1214
1215   for (c = 0; c < AV_NUM_DATA_POINTERS; c++) {
1216     if (c < GST_VIDEO_INFO_N_PLANES (info)) {
1217       pic.data[c] = GST_VIDEO_FRAME_PLANE_DATA (&vframe, c);
1218       pic.linesize[c] = GST_VIDEO_FRAME_PLANE_STRIDE (&vframe, c);
1219       GST_LOG_OBJECT (ffmpegdec, "[%i] linesize %d, data %p", c,
1220           pic.linesize[c], pic.data[c]);
1221     } else {
1222       pic.data[c] = NULL;
1223       pic.linesize[c] = 0;
1224     }
1225   }
1226
1227   outpic = (AVPicture *) ffmpegdec->picture;
1228
1229   av_picture_copy (&pic, outpic, ffmpegdec->context->pix_fmt,
1230       GST_VIDEO_INFO_WIDTH (info), GST_VIDEO_INFO_HEIGHT (info));
1231
1232   gst_video_frame_unmap (&vframe);
1233
1234   ffmpegdec->picture->reordered_opaque = -1;
1235
1236   return ret;
1237
1238   /* special cases */
1239 alloc_failed:
1240   {
1241     GST_DEBUG_OBJECT (ffmpegdec, "allocation failed");
1242     return ret;
1243   }
1244 not_negotiated:
1245   {
1246     GST_DEBUG_OBJECT (ffmpegdec, "not negotiated");
1247     return GST_FLOW_NOT_NEGOTIATED;
1248   }
1249 }
1250
1251 static void
1252 gst_avpacket_init (AVPacket * packet, guint8 * data, guint size)
1253 {
1254   memset (packet, 0, sizeof (AVPacket));
1255   packet->data = data;
1256   packet->size = size;
1257 }
1258
1259 /* gst_ffmpegviddec_[video|audio]_frame:
1260  * ffmpegdec:
1261  * data: pointer to the data to decode
1262  * size: size of data in bytes
1263  * in_timestamp: incoming timestamp.
1264  * in_duration: incoming duration.
1265  * in_offset: incoming offset (frame number).
1266  * ret: Return flow.
1267  *
1268  * Returns: number of bytes used in decoding. The check for successful decode is
1269  *   outbuf being non-NULL.
1270  */
1271 static gint
1272 gst_ffmpegviddec_video_frame (GstFFMpegVidDec * ffmpegdec,
1273     guint8 * data, guint size, gint * have_data, GstVideoCodecFrame * frame,
1274     GstFlowReturn * ret)
1275 {
1276   gint len = -1;
1277   gboolean mode_switch;
1278   GstVideoCodecFrame *out_frame;
1279   GstFFMpegVidDecVideoFrame *out_dframe;
1280   AVPacket packet;
1281   GstBufferPool *pool;
1282
1283   *ret = GST_FLOW_OK;
1284
1285   /* in case we skip frames */
1286   ffmpegdec->picture->pict_type = -1;
1287
1288   /* run QoS code, we don't stop decoding the frame when we are late because
1289    * else we might skip a reference frame */
1290   gst_ffmpegviddec_do_qos (ffmpegdec, frame, &mode_switch);
1291
1292   if (ffmpegdec->is_realvideo && data != NULL) {
1293     gint slice_count;
1294     gint i;
1295
1296     /* setup the slice table for realvideo */
1297     if (ffmpegdec->context->slice_offset == NULL)
1298       ffmpegdec->context->slice_offset = g_malloc (sizeof (guint32) * 1000);
1299
1300     slice_count = (*data++) + 1;
1301     ffmpegdec->context->slice_count = slice_count;
1302
1303     for (i = 0; i < slice_count; i++) {
1304       data += 4;
1305       ffmpegdec->context->slice_offset[i] = GST_READ_UINT32_LE (data);
1306       data += 4;
1307     }
1308   }
1309
1310   if (frame) {
1311     /* save reference to the timing info */
1312     ffmpegdec->context->reordered_opaque = (gint64) frame->system_frame_number;
1313     ffmpegdec->picture->reordered_opaque = (gint64) frame->system_frame_number;
1314
1315     GST_DEBUG_OBJECT (ffmpegdec, "stored opaque values idx %d",
1316         frame->system_frame_number);
1317   }
1318
1319   /* now decode the frame */
1320   gst_avpacket_init (&packet, data, size);
1321
1322   if (ffmpegdec->palette) {
1323     guint8 *pal;
1324
1325     pal = av_packet_new_side_data (&packet, AV_PKT_DATA_PALETTE,
1326         AVPALETTE_SIZE);
1327     gst_buffer_extract (ffmpegdec->palette, 0, pal, AVPALETTE_SIZE);
1328     GST_DEBUG_OBJECT (ffmpegdec, "copy pal %p %p", &packet, pal);
1329   }
1330
1331   /* This might call into get_buffer() from another thread,
1332    * which would cause a deadlock. Release the lock here
1333    * and taking it again later seems safe
1334    * See https://bugzilla.gnome.org/show_bug.cgi?id=726020
1335    */
1336   GST_VIDEO_DECODER_STREAM_UNLOCK (ffmpegdec);
1337   len = avcodec_decode_video2 (ffmpegdec->context,
1338       ffmpegdec->picture, have_data, &packet);
1339   GST_VIDEO_DECODER_STREAM_LOCK (ffmpegdec);
1340
1341   GST_DEBUG_OBJECT (ffmpegdec, "after decode: len %d, have_data %d",
1342       len, *have_data);
1343
1344   /* when we are in skip_frame mode, don't complain when ffmpeg returned
1345    * no data because we told it to skip stuff. */
1346   if (len < 0 && (mode_switch || ffmpegdec->context->skip_frame))
1347     len = 0;
1348
1349   /* no data, we're done */
1350   if (len < 0 || *have_data == 0)
1351     goto beach;
1352
1353   /* get the output picture timing info again */
1354   out_dframe = ffmpegdec->picture->opaque;
1355   out_frame = gst_video_codec_frame_ref (out_dframe->frame);
1356
1357   /* also give back a buffer allocated by the frame, if any */
1358   gst_buffer_replace (&out_frame->output_buffer, out_dframe->buffer);
1359   gst_buffer_replace (&out_dframe->buffer, NULL);
1360
1361   GST_DEBUG_OBJECT (ffmpegdec,
1362       "pts %" G_GUINT64_FORMAT " duration %" G_GUINT64_FORMAT,
1363       out_frame->pts, out_frame->duration);
1364   GST_DEBUG_OBJECT (ffmpegdec, "picture: pts %" G_GUINT64_FORMAT,
1365       (guint64) ffmpegdec->picture->pts);
1366   GST_DEBUG_OBJECT (ffmpegdec, "picture: num %d",
1367       ffmpegdec->picture->coded_picture_number);
1368   GST_DEBUG_OBJECT (ffmpegdec, "picture: ref %d",
1369       ffmpegdec->picture->reference);
1370   GST_DEBUG_OBJECT (ffmpegdec, "picture: display %d",
1371       ffmpegdec->picture->display_picture_number);
1372   GST_DEBUG_OBJECT (ffmpegdec, "picture: opaque %p",
1373       ffmpegdec->picture->opaque);
1374   GST_DEBUG_OBJECT (ffmpegdec, "picture: reordered opaque %" G_GUINT64_FORMAT,
1375       (guint64) ffmpegdec->picture->reordered_opaque);
1376   GST_DEBUG_OBJECT (ffmpegdec, "repeat_pict:%d",
1377       ffmpegdec->picture->repeat_pict);
1378   GST_DEBUG_OBJECT (ffmpegdec, "corrupted frame: %d",
1379       ! !(ffmpegdec->picture->flags & AV_FRAME_FLAG_CORRUPT));
1380
1381   if (!gst_ffmpegviddec_negotiate (ffmpegdec, ffmpegdec->context,
1382           ffmpegdec->picture))
1383     goto negotiation_error;
1384
1385   pool = gst_video_decoder_get_buffer_pool (GST_VIDEO_DECODER (ffmpegdec));
1386   if (G_UNLIKELY (out_frame->output_buffer == NULL)) {
1387     *ret = get_output_buffer (ffmpegdec, out_frame);
1388   } else if (G_UNLIKELY (out_frame->output_buffer->pool != pool)) {
1389     GstBuffer *tmp = out_frame->output_buffer;
1390     out_frame->output_buffer = NULL;
1391     *ret = get_output_buffer (ffmpegdec, out_frame);
1392     gst_buffer_unref (tmp);
1393   }
1394   gst_object_unref (pool);
1395
1396   if (G_UNLIKELY (*ret != GST_FLOW_OK))
1397     goto no_output;
1398
1399   /* Mark corrupted frames as corrupted */
1400   if (ffmpegdec->picture->flags & AV_FRAME_FLAG_CORRUPT)
1401     GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_BUFFER_FLAG_CORRUPTED);
1402
1403   if (ffmpegdec->pic_interlaced) {
1404     /* set interlaced flags */
1405     if (ffmpegdec->picture->repeat_pict)
1406       GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_VIDEO_BUFFER_FLAG_RFF);
1407     if (ffmpegdec->picture->top_field_first)
1408       GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_VIDEO_BUFFER_FLAG_TFF);
1409     if (ffmpegdec->picture->interlaced_frame)
1410       GST_BUFFER_FLAG_SET (out_frame->output_buffer,
1411           GST_VIDEO_BUFFER_FLAG_INTERLACED);
1412   }
1413
1414   /* cleaning time */
1415   /* so we decoded this frame, frames preceding it in decoding order
1416    * that still do not have a buffer allocated seem rather useless,
1417    * and can be discarded, due to e.g. misparsed bogus frame
1418    * or non-keyframe in skipped decoding, ...
1419    * In any case, not likely to be seen again, so discard those,
1420    * before they pile up and/or mess with timestamping */
1421   {
1422     GList *l, *ol;
1423     GstVideoDecoder *dec = GST_VIDEO_DECODER (ffmpegdec);
1424     gboolean old = TRUE;
1425
1426     ol = l = gst_video_decoder_get_frames (dec);
1427     while (l) {
1428       GstVideoCodecFrame *tmp = l->data;
1429
1430       if (tmp == frame)
1431         old = FALSE;
1432
1433       if (old && GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (tmp)) {
1434         GST_LOG_OBJECT (dec,
1435             "discarding ghost frame %p (#%d) PTS:%" GST_TIME_FORMAT " DTS:%"
1436             GST_TIME_FORMAT, tmp, tmp->system_frame_number,
1437             GST_TIME_ARGS (tmp->pts), GST_TIME_ARGS (tmp->dts));
1438         /* drop extra ref and remove from frame list */
1439         gst_video_decoder_release_frame (dec, tmp);
1440       } else {
1441         /* drop extra ref we got */
1442         gst_video_codec_frame_unref (tmp);
1443       }
1444       l = l->next;
1445     }
1446     g_list_free (ol);
1447   }
1448
1449   av_frame_unref (ffmpegdec->picture);
1450
1451   /* FIXME: Ideally we would remap the buffer read-only now before pushing but
1452    * libav might still have a reference to it!
1453    */
1454   *ret =
1455       gst_video_decoder_finish_frame (GST_VIDEO_DECODER (ffmpegdec), out_frame);
1456
1457 beach:
1458   GST_DEBUG_OBJECT (ffmpegdec, "return flow %s, len %d",
1459       gst_flow_get_name (*ret), len);
1460   return len;
1461
1462   /* special cases */
1463 no_output:
1464   {
1465     GST_DEBUG_OBJECT (ffmpegdec, "no output buffer");
1466     gst_video_decoder_drop_frame (GST_VIDEO_DECODER (ffmpegdec), out_frame);
1467     len = -1;
1468     goto beach;
1469   }
1470
1471 negotiation_error:
1472   {
1473     if (GST_PAD_IS_FLUSHING (GST_VIDEO_DECODER_SRC_PAD (ffmpegdec))) {
1474       *ret = GST_FLOW_FLUSHING;
1475       goto beach;
1476     }
1477     GST_WARNING_OBJECT (ffmpegdec, "Error negotiating format");
1478     *ret = GST_FLOW_NOT_NEGOTIATED;
1479     goto beach;
1480   }
1481 }
1482
1483
1484 /* gst_ffmpegviddec_frame:
1485  * ffmpegdec:
1486  * data: pointer to the data to decode
1487  * size: size of data in bytes
1488  * got_data: 0 if no data was decoded, != 0 otherwise.
1489  * in_time: timestamp of data
1490  * in_duration: duration of data
1491  * ret: GstFlowReturn to return in the chain function
1492  *
1493  * Decode the given frame and pushes it downstream.
1494  *
1495  * Returns: Number of bytes used in decoding, -1 on error/failure.
1496  */
1497
1498 static gint
1499 gst_ffmpegviddec_frame (GstFFMpegVidDec * ffmpegdec,
1500     guint8 * data, guint size, gint * have_data, GstVideoCodecFrame * frame,
1501     GstFlowReturn * ret)
1502 {
1503   GstFFMpegVidDecClass *oclass;
1504   gint len = 0;
1505
1506   if (G_UNLIKELY (ffmpegdec->context->codec == NULL))
1507     goto no_codec;
1508
1509   GST_LOG_OBJECT (ffmpegdec, "data:%p, size:%d", data, size);
1510
1511   *ret = GST_FLOW_OK;
1512   ffmpegdec->context->frame_number++;
1513
1514   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1515
1516   len =
1517       gst_ffmpegviddec_video_frame (ffmpegdec, data, size, have_data, frame,
1518       ret);
1519
1520   if (len < 0) {
1521     GST_WARNING_OBJECT (ffmpegdec,
1522         "avdec_%s: decoding error (len: %d, have_data: %d)",
1523         oclass->in_plugin->name, len, *have_data);
1524   }
1525
1526   return len;
1527
1528   /* ERRORS */
1529 no_codec:
1530   {
1531     GST_ERROR_OBJECT (ffmpegdec, "no codec context");
1532     *ret = GST_FLOW_NOT_NEGOTIATED;
1533     return -1;
1534   }
1535 }
1536
1537 static void
1538 gst_ffmpegviddec_drain (GstFFMpegVidDec * ffmpegdec)
1539 {
1540   GstFFMpegVidDecClass *oclass;
1541
1542   if (!ffmpegdec->opened)
1543     return;
1544
1545   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1546
1547   if (oclass->in_plugin->capabilities & CODEC_CAP_DELAY) {
1548     gint have_data, len;
1549     GstFlowReturn ret;
1550
1551     GST_LOG_OBJECT (ffmpegdec,
1552         "codec has delay capabilities, calling until ffmpeg has drained everything");
1553
1554     do {
1555       len = gst_ffmpegviddec_frame (ffmpegdec, NULL, 0, &have_data, NULL, &ret);
1556     } while (len >= 0 && have_data == 1 && ret == GST_FLOW_OK);
1557     avcodec_flush_buffers (ffmpegdec->context);
1558   }
1559 }
1560
1561 static GstFlowReturn
1562 gst_ffmpegviddec_handle_frame (GstVideoDecoder * decoder,
1563     GstVideoCodecFrame * frame)
1564 {
1565   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1566   guint8 *data, *bdata;
1567   gint size, len, have_data, bsize;
1568   GstMapInfo minfo;
1569   GstFlowReturn ret = GST_FLOW_OK;
1570   gboolean do_padding;
1571
1572   GST_LOG_OBJECT (ffmpegdec,
1573       "Received new data of size %" G_GSIZE_FORMAT ", dts %" GST_TIME_FORMAT
1574       ", pts:%" GST_TIME_FORMAT ", dur:%" GST_TIME_FORMAT,
1575       gst_buffer_get_size (frame->input_buffer), GST_TIME_ARGS (frame->dts),
1576       GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->duration));
1577
1578   if (!gst_buffer_map (frame->input_buffer, &minfo, GST_MAP_READ)) {
1579     GST_ELEMENT_ERROR (ffmpegdec, STREAM, DECODE, ("Decoding problem"),
1580         ("Failed to map buffer for reading"));
1581     return GST_FLOW_ERROR;
1582   }
1583
1584   /* treat frame as void until a buffer is requested for it */
1585   GST_VIDEO_CODEC_FRAME_FLAG_SET (frame,
1586       GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY);
1587
1588   bdata = minfo.data;
1589   bsize = minfo.size;
1590
1591   if (bsize > 0 && (!GST_MEMORY_IS_ZERO_PADDED (minfo.memory)
1592           || (minfo.maxsize - minfo.size) < FF_INPUT_BUFFER_PADDING_SIZE)) {
1593     /* add padding */
1594     if (ffmpegdec->padded_size < bsize + FF_INPUT_BUFFER_PADDING_SIZE) {
1595       ffmpegdec->padded_size = bsize + FF_INPUT_BUFFER_PADDING_SIZE;
1596       ffmpegdec->padded = g_realloc (ffmpegdec->padded, ffmpegdec->padded_size);
1597       GST_LOG_OBJECT (ffmpegdec, "resized padding buffer to %d",
1598           ffmpegdec->padded_size);
1599     }
1600     GST_CAT_TRACE_OBJECT (GST_CAT_PERFORMANCE, ffmpegdec,
1601         "Copy input to add padding");
1602     memcpy (ffmpegdec->padded, bdata, bsize);
1603     memset (ffmpegdec->padded + bsize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1604
1605     bdata = ffmpegdec->padded;
1606     do_padding = TRUE;
1607   } else {
1608     do_padding = FALSE;
1609   }
1610
1611   do {
1612     guint8 tmp_padding[FF_INPUT_BUFFER_PADDING_SIZE];
1613
1614     /* parse, if at all possible */
1615     data = bdata;
1616     size = bsize;
1617
1618     if (do_padding) {
1619       /* add temporary padding */
1620       GST_CAT_TRACE_OBJECT (GST_CAT_PERFORMANCE, ffmpegdec,
1621           "Add temporary input padding");
1622       memcpy (tmp_padding, data + size, FF_INPUT_BUFFER_PADDING_SIZE);
1623       memset (data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1624     }
1625
1626     /* decode a frame of audio/video now */
1627     len =
1628         gst_ffmpegviddec_frame (ffmpegdec, data, size, &have_data, frame, &ret);
1629
1630     if (ret != GST_FLOW_OK) {
1631       GST_LOG_OBJECT (ffmpegdec, "breaking because of flow ret %s",
1632           gst_flow_get_name (ret));
1633       /* bad flow return, make sure we discard all data and exit */
1634       bsize = 0;
1635       break;
1636     }
1637
1638     if (do_padding) {
1639       memcpy (data + size, tmp_padding, FF_INPUT_BUFFER_PADDING_SIZE);
1640     }
1641
1642     if (len == 0 && have_data == 0) {
1643       /* nothing was decoded, this could be because no data was available or
1644        * because we were skipping frames.
1645        * If we have no context we must exit and wait for more data, we keep the
1646        * data we tried. */
1647       GST_LOG_OBJECT (ffmpegdec, "Decoding didn't return any data, breaking");
1648       break;
1649     }
1650
1651     if (len < 0) {
1652       /* a decoding error happened, we must break and try again with next data. */
1653       GST_LOG_OBJECT (ffmpegdec, "Decoding error, breaking");
1654       bsize = 0;
1655       break;
1656     }
1657
1658     /* prepare for the next round, for codecs with a context we did this
1659      * already when using the parser. */
1660     bsize -= len;
1661     bdata += len;
1662
1663     do_padding = TRUE;
1664
1665     GST_LOG_OBJECT (ffmpegdec, "Before (while bsize>0).  bsize:%d , bdata:%p",
1666         bsize, bdata);
1667   } while (bsize > 0);
1668
1669   if (bsize > 0)
1670     GST_DEBUG_OBJECT (ffmpegdec, "Dropping %d bytes of data", bsize);
1671
1672   gst_buffer_unmap (frame->input_buffer, &minfo);
1673   gst_video_codec_frame_unref (frame);
1674
1675   return ret;
1676 }
1677
1678 static gboolean
1679 gst_ffmpegviddec_start (GstVideoDecoder * decoder)
1680 {
1681   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1682   GstFFMpegVidDecClass *oclass;
1683
1684   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1685
1686   GST_OBJECT_LOCK (ffmpegdec);
1687   gst_ffmpeg_avcodec_close (ffmpegdec->context);
1688   if (avcodec_get_context_defaults3 (ffmpegdec->context, oclass->in_plugin) < 0) {
1689     GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
1690     GST_OBJECT_UNLOCK (ffmpegdec);
1691     return FALSE;
1692   }
1693   ffmpegdec->context->opaque = ffmpegdec;
1694   GST_OBJECT_UNLOCK (ffmpegdec);
1695
1696   return TRUE;
1697 }
1698
1699 static gboolean
1700 gst_ffmpegviddec_stop (GstVideoDecoder * decoder)
1701 {
1702   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1703
1704   GST_OBJECT_LOCK (ffmpegdec);
1705   gst_ffmpegviddec_close (ffmpegdec, FALSE);
1706   GST_OBJECT_UNLOCK (ffmpegdec);
1707   g_free (ffmpegdec->padded);
1708   ffmpegdec->padded = NULL;
1709   ffmpegdec->padded_size = 0;
1710   if (ffmpegdec->input_state)
1711     gst_video_codec_state_unref (ffmpegdec->input_state);
1712   ffmpegdec->input_state = NULL;
1713   if (ffmpegdec->output_state)
1714     gst_video_codec_state_unref (ffmpegdec->output_state);
1715   ffmpegdec->output_state = NULL;
1716
1717   if (ffmpegdec->internal_pool)
1718     gst_object_unref (ffmpegdec->internal_pool);
1719   ffmpegdec->internal_pool = NULL;
1720
1721   ffmpegdec->pic_pix_fmt = 0;
1722   ffmpegdec->pic_width = 0;
1723   ffmpegdec->pic_height = 0;
1724   ffmpegdec->pic_par_n = 0;
1725   ffmpegdec->pic_par_d = 0;
1726   ffmpegdec->ctx_ticks = 0;
1727   ffmpegdec->ctx_time_n = 0;
1728   ffmpegdec->ctx_time_d = 0;
1729
1730   ffmpegdec->pool_width = 0;
1731   ffmpegdec->pool_height = 0;
1732   ffmpegdec->pool_format = 0;
1733
1734   return TRUE;
1735 }
1736
1737 static GstFlowReturn
1738 gst_ffmpegviddec_finish (GstVideoDecoder * decoder)
1739 {
1740   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1741
1742   gst_ffmpegviddec_drain (ffmpegdec);
1743
1744   return GST_FLOW_OK;
1745 }
1746
1747 static gboolean
1748 gst_ffmpegviddec_flush (GstVideoDecoder * decoder)
1749 {
1750   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1751
1752   if (ffmpegdec->opened)
1753     avcodec_flush_buffers (ffmpegdec->context);
1754
1755   return TRUE;
1756 }
1757
1758 static gboolean
1759 gst_ffmpegviddec_decide_allocation (GstVideoDecoder * decoder, GstQuery * query)
1760 {
1761   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1762   GstVideoCodecState *state;
1763   GstBufferPool *pool;
1764   guint size, min, max;
1765   GstStructure *config;
1766   gboolean have_pool, have_videometa, have_alignment, update_pool = FALSE;
1767   GstAllocator *allocator = NULL;
1768   GstAllocationParams params = DEFAULT_ALLOC_PARAM;
1769
1770   have_pool = (gst_query_get_n_allocation_pools (query) != 0);
1771
1772   if (!GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
1773           query))
1774     return FALSE;
1775
1776   state = gst_video_decoder_get_output_state (decoder);
1777
1778   if (gst_query_get_n_allocation_params (query) > 0) {
1779     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1780     params.align = MAX (params.align, DEFAULT_STRIDE_ALIGN);
1781   } else {
1782     gst_query_add_allocation_param (query, allocator, &params);
1783   }
1784
1785   gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
1786
1787   /* Don't use pool that can't grow, as we don't know how many buffer we'll
1788    * need, otherwise we may stall */
1789   if (max != 0 && max < REQUIRED_POOL_MAX_BUFFERS) {
1790     gst_object_unref (pool);
1791     pool = gst_video_buffer_pool_new ();
1792     max = 0;
1793     update_pool = TRUE;
1794     have_pool = FALSE;
1795
1796     /* if there is an allocator, also drop it, as it might be the reason we
1797      * have this limit. Default will be used */
1798     if (allocator) {
1799       gst_object_unref (allocator);
1800       allocator = NULL;
1801     }
1802   }
1803
1804   config = gst_buffer_pool_get_config (pool);
1805   gst_buffer_pool_config_set_params (config, state->caps, size, min, max);
1806   gst_buffer_pool_config_set_allocator (config, allocator, &params);
1807
1808   have_videometa =
1809       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
1810
1811   if (have_videometa)
1812     gst_buffer_pool_config_add_option (config,
1813         GST_BUFFER_POOL_OPTION_VIDEO_META);
1814
1815   have_alignment =
1816       gst_buffer_pool_has_option (pool, GST_BUFFER_POOL_OPTION_VIDEO_ALIGNMENT);
1817
1818   /* If have videometa, we never have to copy */
1819   if (have_videometa && have_pool && have_alignment &&
1820       gst_ffmpegviddec_can_direct_render (ffmpegdec)) {
1821     gst_ffmpegvideodec_prepare_dr_pool (ffmpegdec, pool, &state->info, config);
1822
1823     /* FIXME validate and retry */
1824     if (gst_buffer_pool_set_config (pool, config)) {
1825       GstFlowReturn ret;
1826       GstBuffer *tmp;
1827
1828       gst_buffer_pool_set_active (pool, TRUE);
1829       ret = gst_buffer_pool_acquire_buffer (pool, &tmp, NULL);
1830       if (ret == GST_FLOW_OK) {
1831         GstVideoMeta *vmeta = gst_buffer_get_video_meta (tmp);
1832         gboolean same_stride = TRUE;
1833         gint i;
1834
1835         for (i = 0; i < vmeta->n_planes; i++) {
1836           if (vmeta->stride[i] != ffmpegdec->stride[i]) {
1837             same_stride = FALSE;
1838             break;
1839           }
1840         }
1841
1842         gst_buffer_unref (tmp);
1843
1844         if (same_stride) {
1845           if (ffmpegdec->internal_pool)
1846             gst_object_unref (ffmpegdec->internal_pool);
1847           ffmpegdec->internal_pool = gst_object_ref (pool);
1848           ffmpegdec->pool_info = state->info;
1849           goto done;
1850         }
1851       }
1852     }
1853   }
1854
1855   if (have_videometa && ffmpegdec->internal_pool) {
1856     update_pool = TRUE;
1857     gst_object_unref (pool);
1858     pool = gst_object_ref (ffmpegdec->internal_pool);
1859     goto done;
1860   }
1861
1862   /* configure */
1863   if (!gst_buffer_pool_set_config (pool, config)) {
1864     gboolean working_pool = FALSE;
1865     config = gst_buffer_pool_get_config (pool);
1866
1867     if (gst_buffer_pool_config_validate_params (config, state->caps, size, min,
1868             max)) {
1869       working_pool = gst_buffer_pool_set_config (pool, config);
1870     }
1871
1872     if (!working_pool) {
1873       gst_object_unref (pool);
1874       pool = gst_video_buffer_pool_new ();
1875       config = gst_buffer_pool_get_config (pool);
1876       gst_buffer_pool_config_set_params (config, state->caps, size, min, max);
1877       gst_buffer_pool_config_set_allocator (config, NULL, &params);
1878       gst_buffer_pool_set_config (pool, config);
1879       update_pool = TRUE;
1880     }
1881   }
1882
1883 done:
1884   /* and store */
1885   if (update_pool)
1886     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
1887
1888   gst_object_unref (pool);
1889   if (allocator)
1890     gst_object_unref (allocator);
1891   gst_video_codec_state_unref (state);
1892
1893   return TRUE;
1894 }
1895
1896 static gboolean
1897 gst_ffmpegviddec_propose_allocation (GstVideoDecoder * decoder,
1898     GstQuery * query)
1899 {
1900   GstAllocationParams params;
1901
1902   gst_allocation_params_init (&params);
1903   params.flags = GST_MEMORY_FLAG_ZERO_PADDED;
1904   params.align = DEFAULT_STRIDE_ALIGN;
1905   params.padding = FF_INPUT_BUFFER_PADDING_SIZE;
1906   /* we would like to have some padding so that we don't have to
1907    * memcpy. We don't suggest an allocator. */
1908   gst_query_add_allocation_param (query, NULL, &params);
1909
1910   return GST_VIDEO_DECODER_CLASS (parent_class)->propose_allocation (decoder,
1911       query);
1912 }
1913
1914 static void
1915 gst_ffmpegviddec_set_property (GObject * object,
1916     guint prop_id, const GValue * value, GParamSpec * pspec)
1917 {
1918   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) object;
1919
1920   switch (prop_id) {
1921     case PROP_LOWRES:
1922       ffmpegdec->lowres = ffmpegdec->context->lowres = g_value_get_enum (value);
1923       break;
1924     case PROP_SKIPFRAME:
1925       ffmpegdec->skip_frame = ffmpegdec->context->skip_frame =
1926           g_value_get_enum (value);
1927       break;
1928     case PROP_DIRECT_RENDERING:
1929       ffmpegdec->direct_rendering = g_value_get_boolean (value);
1930       break;
1931     case PROP_DEBUG_MV:
1932       ffmpegdec->debug_mv = ffmpegdec->context->debug_mv =
1933           g_value_get_boolean (value);
1934       break;
1935     case PROP_MAX_THREADS:
1936       ffmpegdec->max_threads = g_value_get_int (value);
1937       break;
1938     case PROP_OUTPUT_CORRUPT:
1939       ffmpegdec->output_corrupt = g_value_get_boolean (value);
1940       break;
1941     default:
1942       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1943       break;
1944   }
1945 }
1946
1947 static void
1948 gst_ffmpegviddec_get_property (GObject * object,
1949     guint prop_id, GValue * value, GParamSpec * pspec)
1950 {
1951   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) object;
1952
1953   switch (prop_id) {
1954     case PROP_LOWRES:
1955       g_value_set_enum (value, ffmpegdec->context->lowres);
1956       break;
1957     case PROP_SKIPFRAME:
1958       g_value_set_enum (value, ffmpegdec->context->skip_frame);
1959       break;
1960     case PROP_DIRECT_RENDERING:
1961       g_value_set_boolean (value, ffmpegdec->direct_rendering);
1962       break;
1963     case PROP_DEBUG_MV:
1964       g_value_set_boolean (value, ffmpegdec->context->debug_mv);
1965       break;
1966     case PROP_MAX_THREADS:
1967       g_value_set_int (value, ffmpegdec->max_threads);
1968       break;
1969     case PROP_OUTPUT_CORRUPT:
1970       g_value_set_boolean (value, ffmpegdec->output_corrupt);
1971       break;
1972     default:
1973       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1974       break;
1975   }
1976 }
1977
1978 gboolean
1979 gst_ffmpegviddec_register (GstPlugin * plugin)
1980 {
1981   GTypeInfo typeinfo = {
1982     sizeof (GstFFMpegVidDecClass),
1983     (GBaseInitFunc) gst_ffmpegviddec_base_init,
1984     NULL,
1985     (GClassInitFunc) gst_ffmpegviddec_class_init,
1986     NULL,
1987     NULL,
1988     sizeof (GstFFMpegVidDec),
1989     0,
1990     (GInstanceInitFunc) gst_ffmpegviddec_init,
1991   };
1992   GType type;
1993   AVCodec *in_plugin;
1994   gint rank;
1995
1996   in_plugin = av_codec_next (NULL);
1997
1998   GST_LOG ("Registering decoders");
1999
2000   while (in_plugin) {
2001     gchar *type_name;
2002     gchar *plugin_name;
2003
2004     /* only video decoders */
2005     if (!av_codec_is_decoder (in_plugin)
2006         || in_plugin->type != AVMEDIA_TYPE_VIDEO)
2007       goto next;
2008
2009     /* no quasi-codecs, please */
2010     if (in_plugin->id == AV_CODEC_ID_RAWVIDEO ||
2011         in_plugin->id == AV_CODEC_ID_V210 ||
2012         in_plugin->id == AV_CODEC_ID_V210X ||
2013         in_plugin->id == AV_CODEC_ID_R210 ||
2014         (in_plugin->id >= AV_CODEC_ID_PCM_S16LE &&
2015             in_plugin->id <= AV_CODEC_ID_PCM_BLURAY)) {
2016       goto next;
2017     }
2018
2019     /* No decoders depending on external libraries (we don't build them, but
2020      * people who build against an external ffmpeg might have them.
2021      * We have native gstreamer plugins for all of those libraries anyway. */
2022     if (!strncmp (in_plugin->name, "lib", 3)) {
2023       GST_DEBUG
2024           ("Not using external library decoder %s. Use the gstreamer-native ones instead.",
2025           in_plugin->name);
2026       goto next;
2027     }
2028
2029     /* No vdpau plugins until we can figure out how to properly use them
2030      * outside of ffmpeg. */
2031     if (g_str_has_suffix (in_plugin->name, "_vdpau")) {
2032       GST_DEBUG
2033           ("Ignoring VDPAU decoder %s. We can't handle this outside of ffmpeg",
2034           in_plugin->name);
2035       goto next;
2036     }
2037
2038     if (g_str_has_suffix (in_plugin->name, "_xvmc")) {
2039       GST_DEBUG
2040           ("Ignoring XVMC decoder %s. We can't handle this outside of ffmpeg",
2041           in_plugin->name);
2042       goto next;
2043     }
2044
2045     GST_DEBUG ("Trying plugin %s [%s]", in_plugin->name, in_plugin->long_name);
2046
2047     /* no codecs for which we're GUARANTEED to have better alternatives */
2048     /* MPEG1VIDEO : the mpeg2video decoder is preferred */
2049     /* MP1 : Use MP3 for decoding */
2050     /* MP2 : Use MP3 for decoding */
2051     /* Theora: Use libtheora based theoradec */
2052     if (!strcmp (in_plugin->name, "gif") ||
2053         !strcmp (in_plugin->name, "theora") ||
2054         !strcmp (in_plugin->name, "mpeg1video") ||
2055         strstr (in_plugin->name, "crystalhd") != NULL ||
2056         !strcmp (in_plugin->name, "ass") ||
2057         !strcmp (in_plugin->name, "srt") ||
2058         !strcmp (in_plugin->name, "pgssub") ||
2059         !strcmp (in_plugin->name, "dvdsub") ||
2060         !strcmp (in_plugin->name, "dvbsub")) {
2061       GST_LOG ("Ignoring decoder %s", in_plugin->name);
2062       goto next;
2063     }
2064
2065     /* construct the type */
2066     if (!strcmp (in_plugin->name, "hevc")) {
2067       plugin_name = g_strdup ("h265");
2068     } else {
2069       plugin_name = g_strdup ((gchar *) in_plugin->name);
2070     }
2071     g_strdelimit (plugin_name, NULL, '_');
2072     type_name = g_strdup_printf ("avdec_%s", plugin_name);
2073     g_free (plugin_name);
2074
2075     type = g_type_from_name (type_name);
2076
2077     if (!type) {
2078       /* create the gtype now */
2079       type =
2080           g_type_register_static (GST_TYPE_VIDEO_DECODER, type_name, &typeinfo,
2081           0);
2082       g_type_set_qdata (type, GST_FFDEC_PARAMS_QDATA, (gpointer) in_plugin);
2083     }
2084
2085     /* (Ronald) MPEG-4 gets a higher priority because it has been well-
2086      * tested and by far outperforms divxdec/xviddec - so we prefer it.
2087      * msmpeg4v3 same, as it outperforms divxdec for divx3 playback.
2088      * VC1/WMV3 are not working and thus unpreferred for now. */
2089     switch (in_plugin->id) {
2090       case AV_CODEC_ID_MPEG4:
2091       case AV_CODEC_ID_MSMPEG4V3:
2092       case AV_CODEC_ID_H264:
2093       case AV_CODEC_ID_HEVC:
2094       case AV_CODEC_ID_RV10:
2095       case AV_CODEC_ID_RV20:
2096       case AV_CODEC_ID_RV30:
2097       case AV_CODEC_ID_RV40:
2098         rank = GST_RANK_PRIMARY;
2099         break;
2100         /* DVVIDEO: we have a good dv decoder, fast on both ppc as well as x86.
2101          * They say libdv's quality is better though. leave as secondary.
2102          * note: if you change this, see the code in gstdv.c in good/ext/dv.
2103          */
2104       case AV_CODEC_ID_DVVIDEO:
2105         rank = GST_RANK_SECONDARY;
2106         break;
2107       default:
2108         rank = GST_RANK_MARGINAL;
2109         break;
2110     }
2111     if (!gst_element_register (plugin, type_name, rank, type)) {
2112       g_warning ("Failed to register %s", type_name);
2113       g_free (type_name);
2114       return FALSE;
2115     }
2116
2117     g_free (type_name);
2118
2119   next:
2120     in_plugin = av_codec_next (in_plugin);
2121   }
2122
2123   GST_LOG ("Finished Registering decoders");
2124
2125   return TRUE;
2126 }