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