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