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