d341174f8b4c570f921073d32e65c1fd337300be
[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   diff =
1160       gst_video_decoder_get_max_decode_time (GST_VIDEO_DECODER (ffmpegdec),
1161       frame);
1162
1163   /* if we don't have timing info, then we don't do QoS */
1164   if (G_UNLIKELY (diff == G_MAXINT64))
1165     return;
1166
1167   GST_DEBUG_OBJECT (ffmpegdec, "decoding time %" G_GINT64_FORMAT, diff);
1168
1169   if (*mode_switch == FALSE) {
1170     if (diff > 0 && ffmpegdec->context->skip_frame != AVDISCARD_DEFAULT) {
1171       ffmpegdec->context->skip_frame = AVDISCARD_DEFAULT;
1172       *mode_switch = TRUE;
1173       GST_DEBUG_OBJECT (ffmpegdec, "QOS: normal mode");
1174     }
1175
1176     else if (diff <= 0 && ffmpegdec->context->skip_frame != AVDISCARD_NONREF) {
1177       ffmpegdec->context->skip_frame = AVDISCARD_NONREF;
1178       *mode_switch = TRUE;
1179       GST_DEBUG_OBJECT (ffmpegdec,
1180           "QOS: hurry up, diff %" G_GINT64_FORMAT " >= 0", diff);
1181     }
1182   }
1183 }
1184
1185 /* get an outbuf buffer with the current picture */
1186 static GstFlowReturn
1187 get_output_buffer (GstFFMpegVidDec * ffmpegdec, GstVideoCodecFrame * frame)
1188 {
1189   GstFlowReturn ret = GST_FLOW_OK;
1190   AVFrame pic, *outpic;
1191   GstVideoFrame vframe;
1192   GstVideoInfo *info;
1193   gint c;
1194
1195   GST_LOG_OBJECT (ffmpegdec, "get output buffer");
1196
1197   if (!ffmpegdec->output_state)
1198     goto not_negotiated;
1199
1200   ret =
1201       gst_video_decoder_allocate_output_frame (GST_VIDEO_DECODER (ffmpegdec),
1202       frame);
1203   if (G_UNLIKELY (ret != GST_FLOW_OK))
1204     goto alloc_failed;
1205
1206   /* original ffmpeg code does not handle odd sizes correctly.
1207    * This patched up version does */
1208   /* Fill avpicture */
1209   info = &ffmpegdec->output_state->info;
1210   if (!gst_video_frame_map (&vframe, info, frame->output_buffer,
1211           GST_MAP_READ | GST_MAP_WRITE))
1212     goto map_failed;
1213
1214   memset (&pic, 0, sizeof (pic));
1215   pic.format = ffmpegdec->pic_pix_fmt;
1216   pic.width = GST_VIDEO_FRAME_WIDTH (&vframe);
1217   pic.height = GST_VIDEO_FRAME_HEIGHT (&vframe);
1218   for (c = 0; c < AV_NUM_DATA_POINTERS; c++) {
1219     if (c < GST_VIDEO_INFO_N_PLANES (info)) {
1220       pic.data[c] = GST_VIDEO_FRAME_PLANE_DATA (&vframe, c);
1221       pic.linesize[c] = GST_VIDEO_FRAME_PLANE_STRIDE (&vframe, c);
1222       GST_LOG_OBJECT (ffmpegdec, "[%i] linesize %d, data %p", c,
1223           pic.linesize[c], pic.data[c]);
1224     } else {
1225       pic.data[c] = NULL;
1226       pic.linesize[c] = 0;
1227     }
1228   }
1229
1230   outpic = ffmpegdec->picture;
1231
1232   if (av_frame_copy (&pic, outpic) != 0) {
1233     GST_ERROR_OBJECT (ffmpegdec, "Failed to copy output frame");
1234     ret = GST_FLOW_ERROR;
1235   }
1236
1237   gst_video_frame_unmap (&vframe);
1238
1239   ffmpegdec->picture->reordered_opaque = -1;
1240
1241   return ret;
1242
1243   /* special cases */
1244 alloc_failed:
1245   {
1246     GST_ELEMENT_ERROR (ffmpegdec, RESOURCE, FAILED,
1247         ("Unable to allocate memory"),
1248         ("The downstream pool failed to allocated buffer."));
1249     return ret;
1250   }
1251 map_failed:
1252   {
1253     GST_ELEMENT_ERROR (ffmpegdec, RESOURCE, OPEN_READ_WRITE,
1254         ("Cannot access memory for read and write operation."),
1255         ("The video memory allocated from downstream pool could not mapped for"
1256             "read and write."));
1257     return ret;
1258   }
1259 not_negotiated:
1260   {
1261     GST_DEBUG_OBJECT (ffmpegdec, "not negotiated");
1262     return GST_FLOW_NOT_NEGOTIATED;
1263   }
1264 }
1265
1266 static void
1267 gst_avpacket_init (AVPacket * packet, guint8 * data, guint size)
1268 {
1269   memset (packet, 0, sizeof (AVPacket));
1270   packet->data = data;
1271   packet->size = size;
1272 }
1273
1274 /* gst_ffmpegviddec_[video|audio]_frame:
1275  * ffmpegdec:
1276  * data: pointer to the data to decode
1277  * size: size of data in bytes
1278  * in_timestamp: incoming timestamp.
1279  * in_duration: incoming duration.
1280  * in_offset: incoming offset (frame number).
1281  * ret: Return flow.
1282  *
1283  * Returns: number of bytes used in decoding. The check for successful decode is
1284  *   outbuf being non-NULL.
1285  */
1286 static gint
1287 gst_ffmpegviddec_video_frame (GstFFMpegVidDec * ffmpegdec,
1288     guint8 * data, guint size, gint * have_data, GstVideoCodecFrame * frame,
1289     GstFlowReturn * ret)
1290 {
1291   gint len = -1;
1292   gboolean mode_switch;
1293   GstVideoCodecFrame *out_frame;
1294   GstFFMpegVidDecVideoFrame *out_dframe;
1295   AVPacket packet;
1296   GstBufferPool *pool;
1297
1298   *ret = GST_FLOW_OK;
1299
1300   /* in case we skip frames */
1301   ffmpegdec->picture->pict_type = -1;
1302
1303   /* run QoS code, we don't stop decoding the frame when we are late because
1304    * else we might skip a reference frame */
1305   gst_ffmpegviddec_do_qos (ffmpegdec, frame, &mode_switch);
1306
1307   if (frame) {
1308     /* save reference to the timing info */
1309     ffmpegdec->context->reordered_opaque = (gint64) frame->system_frame_number;
1310     ffmpegdec->picture->reordered_opaque = (gint64) frame->system_frame_number;
1311
1312     GST_DEBUG_OBJECT (ffmpegdec, "stored opaque values idx %d",
1313         frame->system_frame_number);
1314   }
1315
1316   /* now decode the frame */
1317   gst_avpacket_init (&packet, data, size);
1318
1319   if (ffmpegdec->palette) {
1320     guint8 *pal;
1321
1322     pal = av_packet_new_side_data (&packet, AV_PKT_DATA_PALETTE,
1323         AVPALETTE_SIZE);
1324     gst_buffer_extract (ffmpegdec->palette, 0, pal, AVPALETTE_SIZE);
1325     GST_DEBUG_OBJECT (ffmpegdec, "copy pal %p %p", &packet, pal);
1326   }
1327
1328   /* This might call into get_buffer() from another thread,
1329    * which would cause a deadlock. Release the lock here
1330    * and taking it again later seems safe
1331    * See https://bugzilla.gnome.org/show_bug.cgi?id=726020
1332    */
1333   GST_VIDEO_DECODER_STREAM_UNLOCK (ffmpegdec);
1334   len = avcodec_decode_video2 (ffmpegdec->context,
1335       ffmpegdec->picture, have_data, &packet);
1336   GST_VIDEO_DECODER_STREAM_LOCK (ffmpegdec);
1337
1338   GST_DEBUG_OBJECT (ffmpegdec, "after decode: len %d, have_data %d",
1339       len, *have_data);
1340
1341   /* when we are in skip_frame mode, don't complain when ffmpeg returned
1342    * no data because we told it to skip stuff. */
1343   if (len < 0 && (mode_switch || ffmpegdec->context->skip_frame))
1344     len = 0;
1345
1346   /* no data, we're done */
1347   if (len < 0 || *have_data == 0)
1348     goto beach;
1349
1350   /* get the output picture timing info again */
1351   out_dframe = ffmpegdec->picture->opaque;
1352   out_frame = gst_video_codec_frame_ref (out_dframe->frame);
1353
1354   /* also give back a buffer allocated by the frame, if any */
1355   gst_buffer_replace (&out_frame->output_buffer, out_dframe->buffer);
1356   gst_buffer_replace (&out_dframe->buffer, NULL);
1357
1358   GST_DEBUG_OBJECT (ffmpegdec,
1359       "pts %" G_GUINT64_FORMAT " duration %" G_GUINT64_FORMAT,
1360       out_frame->pts, out_frame->duration);
1361   GST_DEBUG_OBJECT (ffmpegdec, "picture: pts %" G_GUINT64_FORMAT,
1362       (guint64) ffmpegdec->picture->pts);
1363   GST_DEBUG_OBJECT (ffmpegdec, "picture: num %d",
1364       ffmpegdec->picture->coded_picture_number);
1365   GST_DEBUG_OBJECT (ffmpegdec, "picture: display %d",
1366       ffmpegdec->picture->display_picture_number);
1367   GST_DEBUG_OBJECT (ffmpegdec, "picture: opaque %p",
1368       ffmpegdec->picture->opaque);
1369   GST_DEBUG_OBJECT (ffmpegdec, "picture: reordered opaque %" G_GUINT64_FORMAT,
1370       (guint64) ffmpegdec->picture->reordered_opaque);
1371   GST_DEBUG_OBJECT (ffmpegdec, "repeat_pict:%d",
1372       ffmpegdec->picture->repeat_pict);
1373   GST_DEBUG_OBJECT (ffmpegdec, "corrupted frame: %d",
1374       ! !(ffmpegdec->picture->flags & AV_FRAME_FLAG_CORRUPT));
1375
1376   if (!gst_ffmpegviddec_negotiate (ffmpegdec, ffmpegdec->context,
1377           ffmpegdec->picture))
1378     goto negotiation_error;
1379
1380   pool = gst_video_decoder_get_buffer_pool (GST_VIDEO_DECODER (ffmpegdec));
1381   if (G_UNLIKELY (out_frame->output_buffer == NULL)) {
1382     *ret = get_output_buffer (ffmpegdec, out_frame);
1383   } else if (G_UNLIKELY (out_frame->output_buffer->pool != pool)) {
1384     GstBuffer *tmp = out_frame->output_buffer;
1385     out_frame->output_buffer = NULL;
1386     *ret = get_output_buffer (ffmpegdec, out_frame);
1387     gst_buffer_unref (tmp);
1388   }
1389 #ifndef G_DISABLE_ASSERT
1390   else {
1391     GstVideoMeta *vmeta = gst_buffer_get_video_meta (out_frame->output_buffer);
1392     if (vmeta) {
1393       GstVideoInfo *info = &ffmpegdec->output_state->info;
1394       g_assert (vmeta->width == GST_VIDEO_INFO_WIDTH (info));
1395       g_assert (vmeta->height == GST_VIDEO_INFO_HEIGHT (info));
1396     }
1397   }
1398 #endif
1399   gst_object_unref (pool);
1400
1401   if (G_UNLIKELY (*ret != GST_FLOW_OK))
1402     goto no_output;
1403
1404   /* Mark corrupted frames as corrupted */
1405   if (ffmpegdec->picture->flags & AV_FRAME_FLAG_CORRUPT)
1406     GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_BUFFER_FLAG_CORRUPTED);
1407
1408   if (ffmpegdec->pic_interlaced) {
1409     /* set interlaced flags */
1410     if (ffmpegdec->picture->repeat_pict)
1411       GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_VIDEO_BUFFER_FLAG_RFF);
1412     if (ffmpegdec->picture->top_field_first)
1413       GST_BUFFER_FLAG_SET (out_frame->output_buffer, GST_VIDEO_BUFFER_FLAG_TFF);
1414     if (ffmpegdec->picture->interlaced_frame)
1415       GST_BUFFER_FLAG_SET (out_frame->output_buffer,
1416           GST_VIDEO_BUFFER_FLAG_INTERLACED);
1417   }
1418
1419   /* cleaning time */
1420   /* so we decoded this frame, frames preceding it in decoding order
1421    * that still do not have a buffer allocated seem rather useless,
1422    * and can be discarded, due to e.g. misparsed bogus frame
1423    * or non-keyframe in skipped decoding, ...
1424    * In any case, not likely to be seen again, so discard those,
1425    * before they pile up and/or mess with timestamping */
1426   {
1427     GList *l, *ol;
1428     GstVideoDecoder *dec = GST_VIDEO_DECODER (ffmpegdec);
1429     gboolean old = TRUE;
1430
1431     ol = l = gst_video_decoder_get_frames (dec);
1432     while (l) {
1433       GstVideoCodecFrame *tmp = l->data;
1434
1435       if (tmp == frame)
1436         old = FALSE;
1437
1438       if (old && GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (tmp)) {
1439         GST_LOG_OBJECT (dec,
1440             "discarding ghost frame %p (#%d) PTS:%" GST_TIME_FORMAT " DTS:%"
1441             GST_TIME_FORMAT, tmp, tmp->system_frame_number,
1442             GST_TIME_ARGS (tmp->pts), GST_TIME_ARGS (tmp->dts));
1443         /* drop extra ref and remove from frame list */
1444         gst_video_decoder_release_frame (dec, tmp);
1445       } else {
1446         /* drop extra ref we got */
1447         gst_video_codec_frame_unref (tmp);
1448       }
1449       l = l->next;
1450     }
1451     g_list_free (ol);
1452   }
1453
1454   av_frame_unref (ffmpegdec->picture);
1455
1456   /* FIXME: Ideally we would remap the buffer read-only now before pushing but
1457    * libav might still have a reference to it!
1458    */
1459   *ret =
1460       gst_video_decoder_finish_frame (GST_VIDEO_DECODER (ffmpegdec), out_frame);
1461
1462 beach:
1463   GST_DEBUG_OBJECT (ffmpegdec, "return flow %s, len %d",
1464       gst_flow_get_name (*ret), len);
1465   return len;
1466
1467   /* special cases */
1468 no_output:
1469   {
1470     GST_DEBUG_OBJECT (ffmpegdec, "no output buffer");
1471     gst_video_decoder_drop_frame (GST_VIDEO_DECODER (ffmpegdec), out_frame);
1472     len = -1;
1473     goto beach;
1474   }
1475
1476 negotiation_error:
1477   {
1478     if (GST_PAD_IS_FLUSHING (GST_VIDEO_DECODER_SRC_PAD (ffmpegdec))) {
1479       *ret = GST_FLOW_FLUSHING;
1480       goto beach;
1481     }
1482     GST_WARNING_OBJECT (ffmpegdec, "Error negotiating format");
1483     *ret = GST_FLOW_NOT_NEGOTIATED;
1484     goto beach;
1485   }
1486 }
1487
1488
1489 /* gst_ffmpegviddec_frame:
1490  * ffmpegdec:
1491  * data: pointer to the data to decode
1492  * size: size of data in bytes
1493  * got_data: 0 if no data was decoded, != 0 otherwise.
1494  * in_time: timestamp of data
1495  * in_duration: duration of data
1496  * ret: GstFlowReturn to return in the chain function
1497  *
1498  * Decode the given frame and pushes it downstream.
1499  *
1500  * Returns: Number of bytes used in decoding, -1 on error/failure.
1501  */
1502
1503 static gint
1504 gst_ffmpegviddec_frame (GstFFMpegVidDec * ffmpegdec,
1505     guint8 * data, guint size, gint * have_data, GstVideoCodecFrame * frame,
1506     GstFlowReturn * ret)
1507 {
1508   GstFFMpegVidDecClass *oclass;
1509   gint len = 0;
1510
1511   if (G_UNLIKELY (ffmpegdec->context->codec == NULL))
1512     goto no_codec;
1513
1514   GST_LOG_OBJECT (ffmpegdec, "data:%p, size:%d", data, size);
1515
1516   *ret = GST_FLOW_OK;
1517   ffmpegdec->context->frame_number++;
1518
1519   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1520
1521   len =
1522       gst_ffmpegviddec_video_frame (ffmpegdec, data, size, have_data, frame,
1523       ret);
1524
1525   if (len < 0) {
1526     GST_WARNING_OBJECT (ffmpegdec,
1527         "avdec_%s: decoding error (len: %d, have_data: %d)",
1528         oclass->in_plugin->name, len, *have_data);
1529   }
1530
1531   return len;
1532
1533   /* ERRORS */
1534 no_codec:
1535   {
1536     GST_ERROR_OBJECT (ffmpegdec, "no codec context");
1537     *ret = GST_FLOW_NOT_NEGOTIATED;
1538     return -1;
1539   }
1540 }
1541
1542 static GstFlowReturn
1543 gst_ffmpegviddec_drain (GstVideoDecoder * decoder)
1544 {
1545   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1546   GstFFMpegVidDecClass *oclass;
1547
1548   if (!ffmpegdec->opened)
1549     return GST_FLOW_OK;
1550
1551   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1552
1553   if (oclass->in_plugin->capabilities & CODEC_CAP_DELAY) {
1554     gint have_data, len;
1555     GstFlowReturn ret;
1556
1557     GST_LOG_OBJECT (ffmpegdec,
1558         "codec has delay capabilities, calling until ffmpeg has drained everything");
1559
1560     do {
1561       len = gst_ffmpegviddec_frame (ffmpegdec, NULL, 0, &have_data, NULL, &ret);
1562     } while (len >= 0 && have_data == 1 && ret == GST_FLOW_OK);
1563   }
1564
1565   return GST_FLOW_OK;
1566 }
1567
1568 static GstFlowReturn
1569 gst_ffmpegviddec_handle_frame (GstVideoDecoder * decoder,
1570     GstVideoCodecFrame * frame)
1571 {
1572   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1573   guint8 *data, *bdata;
1574   gint size, len, have_data, bsize;
1575   GstMapInfo minfo;
1576   GstFlowReturn ret = GST_FLOW_OK;
1577   gboolean do_padding;
1578
1579   GST_LOG_OBJECT (ffmpegdec,
1580       "Received new data of size %" G_GSIZE_FORMAT ", dts %" GST_TIME_FORMAT
1581       ", pts:%" GST_TIME_FORMAT ", dur:%" GST_TIME_FORMAT,
1582       gst_buffer_get_size (frame->input_buffer), GST_TIME_ARGS (frame->dts),
1583       GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->duration));
1584
1585   if (!gst_buffer_map (frame->input_buffer, &minfo, GST_MAP_READ)) {
1586     GST_ELEMENT_ERROR (ffmpegdec, STREAM, DECODE, ("Decoding problem"),
1587         ("Failed to map buffer for reading"));
1588     return GST_FLOW_ERROR;
1589   }
1590
1591   /* treat frame as void until a buffer is requested for it */
1592   GST_VIDEO_CODEC_FRAME_FLAG_SET (frame,
1593       GST_VIDEO_CODEC_FRAME_FLAG_DECODE_ONLY);
1594
1595   bdata = minfo.data;
1596   bsize = minfo.size;
1597
1598   if (bsize > 0 && (!GST_MEMORY_IS_ZERO_PADDED (minfo.memory)
1599           || (minfo.maxsize - minfo.size) < FF_INPUT_BUFFER_PADDING_SIZE)) {
1600     /* add padding */
1601     if (ffmpegdec->padded_size < bsize + FF_INPUT_BUFFER_PADDING_SIZE) {
1602       ffmpegdec->padded_size = bsize + FF_INPUT_BUFFER_PADDING_SIZE;
1603       ffmpegdec->padded = g_realloc (ffmpegdec->padded, ffmpegdec->padded_size);
1604       GST_LOG_OBJECT (ffmpegdec, "resized padding buffer to %d",
1605           ffmpegdec->padded_size);
1606     }
1607     GST_CAT_TRACE_OBJECT (CAT_PERFORMANCE, ffmpegdec,
1608         "Copy input to add padding");
1609     memcpy (ffmpegdec->padded, bdata, bsize);
1610     memset (ffmpegdec->padded + bsize, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1611
1612     bdata = ffmpegdec->padded;
1613     do_padding = TRUE;
1614   } else {
1615     do_padding = FALSE;
1616   }
1617
1618   do {
1619     guint8 tmp_padding[FF_INPUT_BUFFER_PADDING_SIZE];
1620
1621     /* parse, if at all possible */
1622     data = bdata;
1623     size = bsize;
1624
1625     if (do_padding) {
1626       /* add temporary padding */
1627       GST_CAT_TRACE_OBJECT (CAT_PERFORMANCE, ffmpegdec,
1628           "Add temporary input padding");
1629       memcpy (tmp_padding, data + size, FF_INPUT_BUFFER_PADDING_SIZE);
1630       memset (data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
1631     }
1632
1633     /* decode a frame of audio/video now */
1634     len =
1635         gst_ffmpegviddec_frame (ffmpegdec, data, size, &have_data, frame, &ret);
1636
1637     if (ret != GST_FLOW_OK) {
1638       GST_LOG_OBJECT (ffmpegdec, "breaking because of flow ret %s",
1639           gst_flow_get_name (ret));
1640       /* bad flow return, make sure we discard all data and exit */
1641       bsize = 0;
1642       break;
1643     }
1644
1645     if (do_padding) {
1646       memcpy (data + size, tmp_padding, FF_INPUT_BUFFER_PADDING_SIZE);
1647     }
1648
1649     if (len == 0 && have_data == 0) {
1650       /* nothing was decoded, this could be because no data was available or
1651        * because we were skipping frames.
1652        * If we have no context we must exit and wait for more data, we keep the
1653        * data we tried. */
1654       GST_LOG_OBJECT (ffmpegdec, "Decoding didn't return any data, breaking");
1655       break;
1656     }
1657
1658     if (len < 0) {
1659       /* a decoding error happened, we must break and try again with next data. */
1660       GST_LOG_OBJECT (ffmpegdec, "Decoding error, breaking");
1661       bsize = 0;
1662       break;
1663     }
1664
1665     /* prepare for the next round, for codecs with a context we did this
1666      * already when using the parser. */
1667     bsize -= len;
1668     bdata += len;
1669
1670     do_padding = TRUE;
1671
1672     GST_LOG_OBJECT (ffmpegdec, "Before (while bsize>0).  bsize:%d , bdata:%p",
1673         bsize, bdata);
1674   } while (bsize > 0);
1675
1676   if (bsize > 0)
1677     GST_DEBUG_OBJECT (ffmpegdec, "Dropping %d bytes of data", bsize);
1678
1679   gst_buffer_unmap (frame->input_buffer, &minfo);
1680   gst_video_codec_frame_unref (frame);
1681
1682   return ret;
1683 }
1684
1685 static gboolean
1686 gst_ffmpegviddec_start (GstVideoDecoder * decoder)
1687 {
1688   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1689   GstFFMpegVidDecClass *oclass;
1690
1691   oclass = (GstFFMpegVidDecClass *) (G_OBJECT_GET_CLASS (ffmpegdec));
1692
1693   GST_OBJECT_LOCK (ffmpegdec);
1694   gst_ffmpeg_avcodec_close (ffmpegdec->context);
1695   if (avcodec_get_context_defaults3 (ffmpegdec->context, oclass->in_plugin) < 0) {
1696     GST_DEBUG_OBJECT (ffmpegdec, "Failed to set context defaults");
1697     GST_OBJECT_UNLOCK (ffmpegdec);
1698     return FALSE;
1699   }
1700   ffmpegdec->context->opaque = ffmpegdec;
1701   GST_OBJECT_UNLOCK (ffmpegdec);
1702
1703   return TRUE;
1704 }
1705
1706 static gboolean
1707 gst_ffmpegviddec_stop (GstVideoDecoder * decoder)
1708 {
1709   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1710
1711   GST_OBJECT_LOCK (ffmpegdec);
1712   gst_ffmpegviddec_close (ffmpegdec, FALSE);
1713   GST_OBJECT_UNLOCK (ffmpegdec);
1714   g_free (ffmpegdec->padded);
1715   ffmpegdec->padded = NULL;
1716   ffmpegdec->padded_size = 0;
1717   if (ffmpegdec->input_state)
1718     gst_video_codec_state_unref (ffmpegdec->input_state);
1719   ffmpegdec->input_state = NULL;
1720   if (ffmpegdec->output_state)
1721     gst_video_codec_state_unref (ffmpegdec->output_state);
1722   ffmpegdec->output_state = NULL;
1723
1724   if (ffmpegdec->internal_pool)
1725     gst_object_unref (ffmpegdec->internal_pool);
1726   ffmpegdec->internal_pool = NULL;
1727
1728   ffmpegdec->pic_pix_fmt = 0;
1729   ffmpegdec->pic_width = 0;
1730   ffmpegdec->pic_height = 0;
1731   ffmpegdec->pic_par_n = 0;
1732   ffmpegdec->pic_par_d = 0;
1733   ffmpegdec->ctx_ticks = 0;
1734   ffmpegdec->ctx_time_n = 0;
1735   ffmpegdec->ctx_time_d = 0;
1736
1737   ffmpegdec->pool_width = 0;
1738   ffmpegdec->pool_height = 0;
1739   ffmpegdec->pool_format = 0;
1740
1741   return TRUE;
1742 }
1743
1744 static GstFlowReturn
1745 gst_ffmpegviddec_finish (GstVideoDecoder * decoder)
1746 {
1747   gst_ffmpegviddec_drain (decoder);
1748   /* note that finish can and should clean up more drastically,
1749    * but drain is also invoked on e.g. packet loss in GAP handling */
1750   gst_ffmpegviddec_flush (decoder);
1751
1752   return GST_FLOW_OK;
1753 }
1754
1755 static gboolean
1756 gst_ffmpegviddec_flush (GstVideoDecoder * decoder)
1757 {
1758   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1759
1760   if (ffmpegdec->opened) {
1761     GST_LOG_OBJECT (decoder, "flushing buffers");
1762     avcodec_flush_buffers (ffmpegdec->context);
1763   }
1764
1765   return TRUE;
1766 }
1767
1768 static gboolean
1769 gst_ffmpegviddec_decide_allocation (GstVideoDecoder * decoder, GstQuery * query)
1770 {
1771   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) decoder;
1772   GstVideoCodecState *state;
1773   GstBufferPool *pool;
1774   guint size, min, max;
1775   GstStructure *config;
1776   gboolean have_pool, have_videometa, have_alignment, update_pool = FALSE;
1777   GstAllocator *allocator = NULL;
1778   GstAllocationParams params = DEFAULT_ALLOC_PARAM;
1779
1780   have_pool = (gst_query_get_n_allocation_pools (query) != 0);
1781
1782   if (!GST_VIDEO_DECODER_CLASS (parent_class)->decide_allocation (decoder,
1783           query))
1784     return FALSE;
1785
1786   state = gst_video_decoder_get_output_state (decoder);
1787
1788   if (gst_query_get_n_allocation_params (query) > 0) {
1789     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1790     params.align = MAX (params.align, DEFAULT_STRIDE_ALIGN);
1791   } else {
1792     gst_query_add_allocation_param (query, allocator, &params);
1793   }
1794
1795   gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
1796
1797   /* Don't use pool that can't grow, as we don't know how many buffer we'll
1798    * need, otherwise we may stall */
1799   if (max != 0 && max < REQUIRED_POOL_MAX_BUFFERS) {
1800     gst_object_unref (pool);
1801     pool = gst_video_buffer_pool_new ();
1802     max = 0;
1803     update_pool = TRUE;
1804     have_pool = FALSE;
1805
1806     /* if there is an allocator, also drop it, as it might be the reason we
1807      * have this limit. Default will be used */
1808     if (allocator) {
1809       gst_object_unref (allocator);
1810       allocator = NULL;
1811     }
1812   }
1813
1814   config = gst_buffer_pool_get_config (pool);
1815   gst_buffer_pool_config_set_params (config, state->caps, size, min, max);
1816   gst_buffer_pool_config_set_allocator (config, allocator, &params);
1817
1818   have_videometa =
1819       gst_query_find_allocation_meta (query, GST_VIDEO_META_API_TYPE, NULL);
1820
1821   if (have_videometa)
1822     gst_buffer_pool_config_add_option (config,
1823         GST_BUFFER_POOL_OPTION_VIDEO_META);
1824
1825   have_alignment =
1826       gst_buffer_pool_has_option (pool, GST_BUFFER_POOL_OPTION_VIDEO_ALIGNMENT);
1827
1828   /* If we have videometa, we never have to copy */
1829   if (have_videometa && have_pool && have_alignment &&
1830       gst_ffmpegviddec_can_direct_render (ffmpegdec)) {
1831     GstStructure *config_copy = gst_structure_copy (config);
1832
1833     gst_ffmpegvideodec_prepare_dr_pool (ffmpegdec, pool, &state->info,
1834         config_copy);
1835
1836     /* FIXME validate and retry */
1837     if (gst_buffer_pool_set_config (pool, config_copy)) {
1838       GstFlowReturn ret;
1839       GstBuffer *tmp;
1840
1841       gst_buffer_pool_set_active (pool, TRUE);
1842       ret = gst_buffer_pool_acquire_buffer (pool, &tmp, NULL);
1843       if (ret == GST_FLOW_OK) {
1844         GstVideoMeta *vmeta = gst_buffer_get_video_meta (tmp);
1845         gboolean same_stride = TRUE;
1846         gint i;
1847
1848         for (i = 0; i < vmeta->n_planes; i++) {
1849           if (vmeta->stride[i] != ffmpegdec->stride[i]) {
1850             same_stride = FALSE;
1851             break;
1852           }
1853         }
1854
1855         gst_buffer_unref (tmp);
1856
1857         if (same_stride) {
1858           if (ffmpegdec->internal_pool)
1859             gst_object_unref (ffmpegdec->internal_pool);
1860           ffmpegdec->internal_pool = gst_object_ref (pool);
1861           ffmpegdec->pool_info = state->info;
1862           gst_structure_free (config);
1863           goto done;
1864         }
1865       }
1866     }
1867   }
1868
1869   if (have_videometa && ffmpegdec->internal_pool
1870       && ffmpegdec->pool_width == state->info.width
1871       && ffmpegdec->pool_height == state->info.height) {
1872     update_pool = TRUE;
1873     gst_object_unref (pool);
1874     pool = gst_object_ref (ffmpegdec->internal_pool);
1875     gst_structure_free (config);
1876     goto done;
1877   }
1878
1879   /* configure */
1880   if (!gst_buffer_pool_set_config (pool, config)) {
1881     gboolean working_pool = FALSE;
1882     config = gst_buffer_pool_get_config (pool);
1883
1884     if (gst_buffer_pool_config_validate_params (config, state->caps, size, min,
1885             max)) {
1886       working_pool = gst_buffer_pool_set_config (pool, config);
1887     } else {
1888       gst_structure_free (config);
1889     }
1890
1891     if (!working_pool) {
1892       gst_object_unref (pool);
1893       pool = gst_video_buffer_pool_new ();
1894       config = gst_buffer_pool_get_config (pool);
1895       gst_buffer_pool_config_set_params (config, state->caps, size, min, max);
1896       gst_buffer_pool_config_set_allocator (config, NULL, &params);
1897       gst_buffer_pool_set_config (pool, config);
1898       update_pool = TRUE;
1899     }
1900   }
1901
1902 done:
1903   /* and store */
1904   if (update_pool)
1905     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
1906
1907   gst_object_unref (pool);
1908   if (allocator)
1909     gst_object_unref (allocator);
1910   gst_video_codec_state_unref (state);
1911
1912   return TRUE;
1913 }
1914
1915 static gboolean
1916 gst_ffmpegviddec_propose_allocation (GstVideoDecoder * decoder,
1917     GstQuery * query)
1918 {
1919   GstAllocationParams params;
1920
1921   gst_allocation_params_init (&params);
1922   params.flags = GST_MEMORY_FLAG_ZERO_PADDED;
1923   params.align = DEFAULT_STRIDE_ALIGN;
1924   params.padding = FF_INPUT_BUFFER_PADDING_SIZE;
1925   /* we would like to have some padding so that we don't have to
1926    * memcpy. We don't suggest an allocator. */
1927   gst_query_add_allocation_param (query, NULL, &params);
1928
1929   return GST_VIDEO_DECODER_CLASS (parent_class)->propose_allocation (decoder,
1930       query);
1931 }
1932
1933 static void
1934 gst_ffmpegviddec_set_property (GObject * object,
1935     guint prop_id, const GValue * value, GParamSpec * pspec)
1936 {
1937   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) object;
1938
1939   switch (prop_id) {
1940     case PROP_LOWRES:
1941       ffmpegdec->lowres = ffmpegdec->context->lowres = g_value_get_enum (value);
1942       break;
1943     case PROP_SKIPFRAME:
1944       ffmpegdec->skip_frame = ffmpegdec->context->skip_frame =
1945           g_value_get_enum (value);
1946       break;
1947     case PROP_DIRECT_RENDERING:
1948       ffmpegdec->direct_rendering = g_value_get_boolean (value);
1949       break;
1950     case PROP_DEBUG_MV:
1951       ffmpegdec->debug_mv = ffmpegdec->context->debug_mv =
1952           g_value_get_boolean (value);
1953       break;
1954     case PROP_MAX_THREADS:
1955       ffmpegdec->max_threads = g_value_get_int (value);
1956       break;
1957     case PROP_OUTPUT_CORRUPT:
1958       ffmpegdec->output_corrupt = g_value_get_boolean (value);
1959       break;
1960     default:
1961       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1962       break;
1963   }
1964 }
1965
1966 static void
1967 gst_ffmpegviddec_get_property (GObject * object,
1968     guint prop_id, GValue * value, GParamSpec * pspec)
1969 {
1970   GstFFMpegVidDec *ffmpegdec = (GstFFMpegVidDec *) object;
1971
1972   switch (prop_id) {
1973     case PROP_LOWRES:
1974       g_value_set_enum (value, ffmpegdec->context->lowres);
1975       break;
1976     case PROP_SKIPFRAME:
1977       g_value_set_enum (value, ffmpegdec->context->skip_frame);
1978       break;
1979     case PROP_DIRECT_RENDERING:
1980       g_value_set_boolean (value, ffmpegdec->direct_rendering);
1981       break;
1982     case PROP_DEBUG_MV:
1983       g_value_set_boolean (value, ffmpegdec->context->debug_mv);
1984       break;
1985     case PROP_MAX_THREADS:
1986       g_value_set_int (value, ffmpegdec->max_threads);
1987       break;
1988     case PROP_OUTPUT_CORRUPT:
1989       g_value_set_boolean (value, ffmpegdec->output_corrupt);
1990       break;
1991     default:
1992       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1993       break;
1994   }
1995 }
1996
1997 gboolean
1998 gst_ffmpegviddec_register (GstPlugin * plugin)
1999 {
2000   GTypeInfo typeinfo = {
2001     sizeof (GstFFMpegVidDecClass),
2002     (GBaseInitFunc) gst_ffmpegviddec_base_init,
2003     NULL,
2004     (GClassInitFunc) gst_ffmpegviddec_class_init,
2005     NULL,
2006     NULL,
2007     sizeof (GstFFMpegVidDec),
2008     0,
2009     (GInstanceInitFunc) gst_ffmpegviddec_init,
2010   };
2011   GType type;
2012   AVCodec *in_plugin;
2013   gint rank;
2014
2015   in_plugin = av_codec_next (NULL);
2016
2017   GST_LOG ("Registering decoders");
2018
2019   while (in_plugin) {
2020     gchar *type_name;
2021     gchar *plugin_name;
2022
2023     /* only video decoders */
2024     if (!av_codec_is_decoder (in_plugin)
2025         || in_plugin->type != AVMEDIA_TYPE_VIDEO)
2026       goto next;
2027
2028     /* no quasi codecs, please */
2029     if (in_plugin->id == AV_CODEC_ID_RAWVIDEO ||
2030         in_plugin->id == AV_CODEC_ID_V210 ||
2031         in_plugin->id == AV_CODEC_ID_V210X ||
2032         in_plugin->id == AV_CODEC_ID_V308 ||
2033         in_plugin->id == AV_CODEC_ID_V408 ||
2034         in_plugin->id == AV_CODEC_ID_V410 ||
2035         in_plugin->id == AV_CODEC_ID_R210
2036         || in_plugin->id == AV_CODEC_ID_AYUV
2037         || in_plugin->id == AV_CODEC_ID_Y41P
2038         || in_plugin->id == AV_CODEC_ID_012V
2039         || in_plugin->id == AV_CODEC_ID_YUV4
2040         || in_plugin->id == AV_CODEC_ID_ZLIB
2041         || in_plugin->id == AV_CODEC_ID_WRAPPED_AVFRAME) {
2042       goto next;
2043     }
2044
2045     /* No decoders depending on external libraries (we don't build them, but
2046      * people who build against an external ffmpeg might have them.
2047      * We have native gstreamer plugins for all of those libraries anyway. */
2048     if (!strncmp (in_plugin->name, "lib", 3)) {
2049       GST_DEBUG
2050           ("Not using external library decoder %s. Use the gstreamer-native ones instead.",
2051           in_plugin->name);
2052       goto next;
2053     }
2054
2055     /* No vdpau plugins until we can figure out how to properly use them
2056      * outside of ffmpeg. */
2057     if (g_str_has_suffix (in_plugin->name, "_vdpau")) {
2058       GST_DEBUG
2059           ("Ignoring VDPAU decoder %s. We can't handle this outside of ffmpeg",
2060           in_plugin->name);
2061       goto next;
2062     }
2063
2064     if (g_str_has_suffix (in_plugin->name, "_xvmc")) {
2065       GST_DEBUG
2066           ("Ignoring XVMC decoder %s. We can't handle this outside of ffmpeg",
2067           in_plugin->name);
2068       goto next;
2069     }
2070
2071     if (strstr (in_plugin->name, "vaapi")) {
2072       GST_DEBUG
2073           ("Ignoring VAAPI decoder %s. We can't handle this outside of ffmpeg",
2074           in_plugin->name);
2075       goto next;
2076     }
2077
2078     GST_DEBUG ("Trying plugin %s [%s]", in_plugin->name, in_plugin->long_name);
2079
2080     /* no codecs for which we're GUARANTEED to have better alternatives */
2081     /* MPEG1VIDEO : the mpeg2video decoder is preferred */
2082     /* MP1 : Use MP3 for decoding */
2083     /* MP2 : Use MP3 for decoding */
2084     /* Theora: Use libtheora based theoradec */
2085     if (!strcmp (in_plugin->name, "gif") ||
2086         !strcmp (in_plugin->name, "theora") ||
2087         !strcmp (in_plugin->name, "mpeg1video") ||
2088         strstr (in_plugin->name, "crystalhd") != NULL ||
2089         !strcmp (in_plugin->name, "ass") ||
2090         !strcmp (in_plugin->name, "srt") ||
2091         !strcmp (in_plugin->name, "pgssub") ||
2092         !strcmp (in_plugin->name, "dvdsub") ||
2093         !strcmp (in_plugin->name, "dvbsub")) {
2094       GST_LOG ("Ignoring decoder %s", in_plugin->name);
2095       goto next;
2096     }
2097
2098     /* construct the type */
2099     if (!strcmp (in_plugin->name, "hevc")) {
2100       plugin_name = g_strdup ("h265");
2101     } else {
2102       plugin_name = g_strdup ((gchar *) in_plugin->name);
2103     }
2104     g_strdelimit (plugin_name, NULL, '_');
2105     type_name = g_strdup_printf ("avdec_%s", plugin_name);
2106     g_free (plugin_name);
2107
2108     type = g_type_from_name (type_name);
2109
2110     if (!type) {
2111       /* create the gtype now */
2112       type =
2113           g_type_register_static (GST_TYPE_VIDEO_DECODER, type_name, &typeinfo,
2114           0);
2115       g_type_set_qdata (type, GST_FFDEC_PARAMS_QDATA, (gpointer) in_plugin);
2116     }
2117
2118     /* (Ronald) MPEG-4 gets a higher priority because it has been well-
2119      * tested and by far outperforms divxdec/xviddec - so we prefer it.
2120      * msmpeg4v3 same, as it outperforms divxdec for divx3 playback.
2121      * VC1/WMV3 are not working and thus unpreferred for now. */
2122     switch (in_plugin->id) {
2123       case AV_CODEC_ID_MPEG1VIDEO:
2124       case AV_CODEC_ID_MPEG2VIDEO:
2125       case AV_CODEC_ID_MPEG4:
2126       case AV_CODEC_ID_MSMPEG4V3:
2127       case AV_CODEC_ID_H264:
2128       case AV_CODEC_ID_HEVC:
2129       case AV_CODEC_ID_RV10:
2130       case AV_CODEC_ID_RV20:
2131       case AV_CODEC_ID_RV30:
2132       case AV_CODEC_ID_RV40:
2133         rank = GST_RANK_PRIMARY;
2134         break;
2135         /* DVVIDEO: we have a good dv decoder, fast on both ppc as well as x86.
2136          * They say libdv's quality is better though. leave as secondary.
2137          * note: if you change this, see the code in gstdv.c in good/ext/dv.
2138          */
2139       case AV_CODEC_ID_DVVIDEO:
2140         rank = GST_RANK_SECONDARY;
2141         break;
2142       default:
2143         rank = GST_RANK_MARGINAL;
2144         break;
2145     }
2146     if (!gst_element_register (plugin, type_name, rank, type)) {
2147       g_warning ("Failed to register %s", type_name);
2148       g_free (type_name);
2149       return FALSE;
2150     }
2151
2152     g_free (type_name);
2153
2154   next:
2155     in_plugin = av_codec_next (in_plugin);
2156   }
2157
2158   GST_LOG ("Finished Registering decoders");
2159
2160   return TRUE;
2161 }