8e935c3b3ca7846764f91fd6a024c6a6cfda13d0
[platform/upstream/gstreamer.git] / gst-libs / gst / video / gstvideodecoder.c
1 /* GStreamer
2  * Copyright (C) 2008 David Schleef <ds@schleef.org>
3  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
4  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
5  *   Contact: Stefan Kost <stefan.kost@nokia.com>
6  * Copyright (C) 2012 Collabora Ltd.
7  *      Author : Edward Hervey <edward@collabora.com>
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Library General Public
11  * License as published by the Free Software Foundation; either
12  * version 2 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Library General Public License for more details.
18  *
19  * You should have received a copy of the GNU Library General Public
20  * License along with this library; if not, write to the
21  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
22  * Boston, MA 02110-1301, USA.
23  */
24
25 /**
26  * SECTION:gstvideodecoder
27  * @short_description: Base class for video decoders
28  * @see_also: 
29  *
30  * This base class is for video decoders turning encoded data into raw video
31  * frames.
32  *
33  * The GstVideoDecoder base class and derived subclasses should cooperate as follows:
34  * <orderedlist>
35  * <listitem>
36  *   <itemizedlist><title>Configuration</title>
37  *   <listitem><para>
38  *     Initially, GstVideoDecoder calls @start when the decoder element
39  *     is activated, which allows the subclass to perform any global setup.
40  *   </para></listitem>
41  *   <listitem><para>
42  *     GstVideoDecoder calls @set_format to inform the subclass of caps
43  *     describing input video data that it is about to receive, including
44  *     possibly configuration data.
45  *     While unlikely, it might be called more than once, if changing input
46  *     parameters require reconfiguration.
47  *   </para></listitem>
48  *   <listitem><para>
49  *     Incoming data buffers are processed as needed, described in Data Processing below.
50  *   </para></listitem>
51  *   <listitem><para>
52  *     GstVideoDecoder calls @stop at end of all processing.
53  *   </para></listitem>
54  *   </itemizedlist>
55  * </listitem>
56  * <listitem>
57  *   <itemizedlist>
58  *   <title>Data processing</title>
59  *     <listitem><para>
60  *       The base class gathers input data, and optionally allows subclass
61  *       to parse this into subsequently manageable chunks, typically
62  *       corresponding to and referred to as 'frames'.
63  *     </para></listitem>
64  *     <listitem><para>
65  *       Each input frame is provided in turn to the subclass' @handle_frame callback.
66  *       The ownership of the frame is given to the @handle_frame callback.
67  *     </para></listitem>
68  *     <listitem><para>
69  *       If codec processing results in decoded data, the subclass should call
70  *       @gst_video_decoder_finish_frame to have decoded data pushed.
71  *       downstream. Otherwise, the subclass must call @gst_video_decoder_drop_frame, to
72  *       allow the base class to do timestamp and offset tracking, and possibly to
73  *       requeue the frame for a later attempt in the case of reverse playback.
74  *     </para></listitem>
75  *   </itemizedlist>
76  * </listitem>
77  * <listitem>
78  *   <itemizedlist><title>Shutdown phase</title>
79  *   <listitem><para>
80  *     The GstVideoDecoder class calls @stop to inform the subclass that data
81  *     parsing will be stopped.
82  *   </para></listitem>
83  *   </itemizedlist>
84  * </listitem>
85  * <listitem>
86  *   <itemizedlist><title>Additional Notes</title>
87  *   <listitem>
88  *     <itemizedlist><title>Seeking/Flushing</title>
89  *     <listitem><para>
90  *   When the pipeline is seeked or otherwise flushed, the subclass is informed via a call
91  *   to its @reset callback, with the hard parameter set to true. This indicates the
92  *   subclass should drop any internal data queues and timestamps and prepare for a fresh
93  *   set of buffers to arrive for parsing and decoding.
94  *     </para></listitem>
95  *     </itemizedlist>
96  *   </listitem>
97  *   <listitem>
98  *     <itemizedlist><title>End Of Stream</title>
99  *     <listitem><para>
100  *   At end-of-stream, the subclass @parse function may be called some final times with the 
101  *   at_eos parameter set to true, indicating that the element should not expect any more data
102  *   to be arriving, and it should parse and remaining frames and call
103  *   gst_video_decoder_have_frame() if possible.
104  *     </para></listitem>
105  *     </itemizedlist>
106  *   </listitem>
107  *   </itemizedlist>
108  * </listitem>
109  * </orderedlist>
110  *
111  * The subclass is responsible for providing pad template caps for
112  * source and sink pads. The pads need to be named "sink" and "src". It also
113  * needs to provide information about the ouptput caps, when they are known.
114  * This may be when the base class calls the subclass' @set_format function,
115  * though it might be during decoding, before calling
116  * @gst_video_decoder_finish_frame. This is done via
117  * @gst_video_decoder_set_output_state
118  *
119  * The subclass is also responsible for providing (presentation) timestamps
120  * (likely based on corresponding input ones).  If that is not applicable
121  * or possible, the base class provides limited framerate based interpolation.
122  *
123  * Similarly, the base class provides some limited (legacy) seeking support
124  * if specifically requested by the subclass, as full-fledged support
125  * should rather be left to upstream demuxer, parser or alike.  This simple
126  * approach caters for seeking and duration reporting using estimated input
127  * bitrates. To enable it, a subclass should call
128  * @gst_video_decoder_set_estimate_rate to enable handling of incoming byte-streams.
129  *
130  * The base class provides some support for reverse playback, in particular
131  * in case incoming data is not packetized or upstream does not provide
132  * fragments on keyframe boundaries.  However, the subclass should then be prepared
133  * for the parsing and frame processing stage to occur separately (in normal
134  * forward processing, the latter immediately follows the former),
135  * The subclass also needs to ensure the parsing stage properly marks keyframes,
136  * unless it knows the upstream elements will do so properly for incoming data.
137  *
138  * The bare minimum that a functional subclass needs to implement is:
139  * <itemizedlist>
140  *   <listitem><para>Provide pad templates</para></listitem>
141  *   <listitem><para>
142  *      Inform the base class of output caps via @gst_video_decoder_set_output_state
143  *   </para></listitem>
144  *   <listitem><para>
145  *      Parse input data, if it is not considered packetized from upstream
146  *      Data will be provided to @parse which should invoke @gst_video_decoder_add_to_frame and
147  *      @gst_video_decoder_have_frame to separate the data belonging to each video frame.
148  *   </para></listitem>
149  *   <listitem><para>
150  *      Accept data in @handle_frame and provide decoded results to
151  *      @gst_video_decoder_finish_frame, or call @gst_video_decoder_drop_frame.
152  *   </para></listitem>
153  * </itemizedlist>
154  */
155
156 #ifdef HAVE_CONFIG_H
157 #include "config.h"
158 #endif
159
160 /* TODO
161  *
162  * * Add a flag/boolean for I-frame-only/image decoders so we can do extra
163  *   features, like applying QoS on input (as opposed to after the frame is
164  *   decoded).
165  * * Add a flag/boolean for decoders that require keyframes, so the base
166  *   class can automatically discard non-keyframes before one has arrived
167  * * Detect reordered frame/timestamps and fix the pts/dts
168  * * Support for GstIndex (or shall we not care ?)
169  * * Calculate actual latency based on input/output timestamp/frame_number
170  *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
171  * * Emit latency message when it changes
172  *
173  */
174
175 /* Implementation notes:
176  * The Video Decoder base class operates in 2 primary processing modes, depending
177  * on whether forward or reverse playback is requested.
178  *
179  * Forward playback:
180  *   * Incoming buffer -> @parse() -> add_to_frame()/have_frame() -> handle_frame() -> 
181  *     push downstream
182  *
183  * Reverse playback is more complicated, since it involves gathering incoming data regions
184  * as we loop backwards through the upstream data. The processing concept (using incoming
185  * buffers as containing one frame each to simplify things) is:
186  *
187  * Upstream data we want to play:
188  *  Buffer encoded order:  1  2  3  4  5  6  7  8  9  EOS
189  *  Keyframe flag:            K        K        
190  *  Groupings:             AAAAAAA  BBBBBBB  CCCCCCC
191  *
192  * Input:
193  *  Buffer reception order:  7  8  9  4  5  6  1  2  3  EOS
194  *  Keyframe flag:                       K        K
195  *  Discont flag:            D        D        D
196  *
197  * - Each Discont marks a discont in the decoding order.
198  * - The keyframes mark where we can start decoding.
199  *
200  * Initially, we prepend incoming buffers to the gather queue. Whenever the
201  * discont flag is set on an incoming buffer, the gather queue is flushed out
202  * before the new buffer is collected.
203  *
204  * The above data will be accumulated in the gather queue like this:
205  *
206  *   gather queue:  9  8  7
207  *                        D
208  *
209  * Whe buffer 4 is received (with a DISCONT), we flush the gather queue like
210  * this:
211  *
212  *   while (gather)
213  *     take head of queue and prepend to parse queue (this reverses the sequence,
214  *     so parse queue is 7 -> 8 -> 9)
215  *
216  *   Next, we process the parse queue, which now contains all un-parsed packets (including
217  *   any leftover ones from the previous decode section)
218  *
219  *   for each buffer now in the parse queue:
220  *     Call the subclass parse function, prepending each resulting frame to
221  *     the parse_gather queue. Buffers which precede the first one that
222  *     produces a parsed frame are retained in the parse queue for re-processing on
223  *     the next cycle of parsing.
224  *
225  *   The parse_gather queue now contains frame objects ready for decoding, in reverse order.
226  *   parse_gather: 9 -> 8 -> 7
227  *
228  *   while (parse_gather)
229  *     Take the head of the queue and prepend it to the decode queue
230  *     If the frame was a keyframe, process the decode queue
231  *   decode is now 7-8-9
232  *
233  *  Processing the decode queue results in frames with attached output buffers
234  *  stored in the 'output_queue' ready for outputting in reverse order.
235  *
236  * After we flushed the gather queue and parsed it, we add 4 to the (now empty) gather queue.
237  * We get the following situation:
238  *
239  *  gather queue:    4
240  *  decode queue:    7  8  9
241  *
242  * After we received 5 (Keyframe) and 6:
243  *
244  *  gather queue:    6  5  4
245  *  decode queue:    7  8  9
246  *
247  * When we receive 1 (DISCONT) which triggers a flush of the gather queue:
248  *
249  *   Copy head of the gather queue (6) to decode queue:
250  *
251  *    gather queue:    5  4
252  *    decode queue:    6  7  8  9
253  *
254  *   Copy head of the gather queue (5) to decode queue. This is a keyframe so we
255  *   can start decoding.
256  *
257  *    gather queue:    4
258  *    decode queue:    5  6  7  8  9
259  *
260  *   Decode frames in decode queue, store raw decoded data in output queue, we
261  *   can take the head of the decode queue and prepend the decoded result in the
262  *   output queue:
263  *
264  *    gather queue:    4
265  *    decode queue:    
266  *    output queue:    9  8  7  6  5
267  *
268  *   Now output all the frames in the output queue, picking a frame from the
269  *   head of the queue.
270  *
271  *   Copy head of the gather queue (4) to decode queue, we flushed the gather
272  *   queue and can now store input buffer in the gather queue:
273  *
274  *    gather queue:    1
275  *    decode queue:    4
276  *
277  *  When we receive EOS, the queue looks like:
278  *
279  *    gather queue:    3  2  1
280  *    decode queue:    4
281  *
282  *  Fill decode queue, first keyframe we copy is 2:
283  *
284  *    gather queue:    1
285  *    decode queue:    2  3  4
286  *
287  *  Decoded output:
288  *
289  *    gather queue:    1
290  *    decode queue:    
291  *    output queue:    4  3  2
292  *
293  *  Leftover buffer 1 cannot be decoded and must be discarded.
294  */
295
296 #include "gstvideodecoder.h"
297 #include "gstvideoutils.h"
298
299 #include <gst/video/video.h>
300 #include <gst/video/video-event.h>
301 #include <gst/video/gstvideopool.h>
302 #include <gst/video/gstvideometa.h>
303 #include <string.h>
304
305 GST_DEBUG_CATEGORY (videodecoder_debug);
306 #define GST_CAT_DEFAULT videodecoder_debug
307
308 #define GST_VIDEO_DECODER_GET_PRIVATE(obj)  \
309     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_DECODER, \
310         GstVideoDecoderPrivate))
311
312 struct _GstVideoDecoderPrivate
313 {
314   /* FIXME introduce a context ? */
315
316   GstBufferPool *pool;
317   GstAllocator *allocator;
318   GstAllocationParams params;
319
320   /* parse tracking */
321   /* input data */
322   GstAdapter *input_adapter;
323   /* assembles current frame */
324   GstAdapter *output_adapter;
325
326   /* Whether we attempt to convert newsegment from bytes to
327    * time using a bitrate estimation */
328   gboolean do_estimate_rate;
329
330   /* Whether input is considered packetized or not */
331   gboolean packetized;
332
333   /* Error handling */
334   gint max_errors;
335   gint error_count;
336
337   gboolean do_caps;
338
339   /* ... being tracked here;
340    * only available during parsing */
341   GstVideoCodecFrame *current_frame;
342   /* events that should apply to the current frame */
343   GList *current_frame_events;
344
345   /* relative offset of input data */
346   guint64 input_offset;
347   /* relative offset of frame */
348   guint64 frame_offset;
349   /* tracking ts and offsets */
350   GList *timestamps;
351
352   /* last outgoing ts */
353   GstClockTime last_timestamp_out;
354   /* incoming pts - dts */
355   GstClockTime pts_delta;
356   gboolean reordered_output;
357
358   /* reverse playback */
359   /* collect input */
360   GList *gather;
361   /* to-be-parsed */
362   GList *parse;
363   /* collected parsed frames */
364   GList *parse_gather;
365   /* frames to be handled == decoded */
366   GList *decode;
367   /* collected output - of buffer objects, not frames */
368   GList *output_queued;
369
370
371   /* base_picture_number is the picture number of the reference picture */
372   guint64 base_picture_number;
373   /* combine with base_picture_number, framerate and calcs to yield (presentation) ts */
374   GstClockTime base_timestamp;
375
376   /* FIXME : reorder_depth is never set */
377   int reorder_depth;
378   int distance_from_sync;
379
380   guint32 system_frame_number;
381   guint32 decode_frame_number;
382
383   GList *frames;                /* Protected with OBJECT_LOCK */
384   GstVideoCodecState *input_state;
385   GstVideoCodecState *output_state;     /* OBJECT_LOCK and STREAM_LOCK */
386   gboolean output_state_changed;
387
388   /* QoS properties */
389   gdouble proportion;           /* OBJECT_LOCK */
390   GstClockTime earliest_time;   /* OBJECT_LOCK */
391   GstClockTime qos_frame_duration;      /* OBJECT_LOCK */
392   gboolean discont;
393   /* qos messages: frames dropped/processed */
394   guint dropped;
395   guint processed;
396
397   /* Outgoing byte size ? */
398   gint64 bytes_out;
399   gint64 time;
400
401   gint64 min_latency;
402   gint64 max_latency;
403
404   GstTagList *tags;
405   gboolean tags_changed;
406 };
407
408 static GstElementClass *parent_class = NULL;
409 static void gst_video_decoder_class_init (GstVideoDecoderClass * klass);
410 static void gst_video_decoder_init (GstVideoDecoder * dec,
411     GstVideoDecoderClass * klass);
412
413 static void gst_video_decoder_finalize (GObject * object);
414
415 static gboolean gst_video_decoder_setcaps (GstVideoDecoder * dec,
416     GstCaps * caps);
417 static gboolean gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
418     GstEvent * event);
419 static gboolean gst_video_decoder_src_event (GstPad * pad, GstObject * parent,
420     GstEvent * event);
421 static GstFlowReturn gst_video_decoder_chain (GstPad * pad, GstObject * parent,
422     GstBuffer * buf);
423 static gboolean gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
424     GstQuery * query);
425 static GstStateChangeReturn gst_video_decoder_change_state (GstElement *
426     element, GstStateChange transition);
427 static gboolean gst_video_decoder_src_query (GstPad * pad, GstObject * parent,
428     GstQuery * query);
429 static void gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full);
430
431 static GstFlowReturn gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
432     GstVideoCodecFrame * frame);
433
434 static void gst_video_decoder_release_frame (GstVideoDecoder * dec,
435     GstVideoCodecFrame * frame);
436 static GstClockTime gst_video_decoder_get_frame_duration (GstVideoDecoder *
437     decoder, GstVideoCodecFrame * frame);
438 static GstVideoCodecFrame *gst_video_decoder_new_frame (GstVideoDecoder *
439     decoder);
440 static GstFlowReturn gst_video_decoder_clip_and_push_buf (GstVideoDecoder *
441     decoder, GstBuffer * buf);
442 static GstFlowReturn gst_video_decoder_flush_parse (GstVideoDecoder * dec,
443     gboolean at_eos);
444
445 static void gst_video_decoder_clear_queues (GstVideoDecoder * dec);
446
447 static gboolean gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
448     GstEvent * event);
449 static gboolean gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
450     GstEvent * event);
451 static gboolean gst_video_decoder_decide_allocation_default (GstVideoDecoder *
452     decoder, GstQuery * query);
453 static gboolean gst_video_decoder_propose_allocation_default (GstVideoDecoder *
454     decoder, GstQuery * query);
455 static gboolean gst_video_decoder_negotiate_default (GstVideoDecoder * decoder);
456
457 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
458  * method to get to the padtemplates */
459 GType
460 gst_video_decoder_get_type (void)
461 {
462   static volatile gsize type = 0;
463
464   if (g_once_init_enter (&type)) {
465     GType _type;
466     static const GTypeInfo info = {
467       sizeof (GstVideoDecoderClass),
468       NULL,
469       NULL,
470       (GClassInitFunc) gst_video_decoder_class_init,
471       NULL,
472       NULL,
473       sizeof (GstVideoDecoder),
474       0,
475       (GInstanceInitFunc) gst_video_decoder_init,
476     };
477
478     _type = g_type_register_static (GST_TYPE_ELEMENT,
479         "GstVideoDecoder", &info, G_TYPE_FLAG_ABSTRACT);
480     g_once_init_leave (&type, _type);
481   }
482   return type;
483 }
484
485 static void
486 gst_video_decoder_class_init (GstVideoDecoderClass * klass)
487 {
488   GObjectClass *gobject_class;
489   GstElementClass *gstelement_class;
490
491   gobject_class = G_OBJECT_CLASS (klass);
492   gstelement_class = GST_ELEMENT_CLASS (klass);
493
494   GST_DEBUG_CATEGORY_INIT (videodecoder_debug, "videodecoder", 0,
495       "Base Video Decoder");
496
497   parent_class = g_type_class_peek_parent (klass);
498   g_type_class_add_private (klass, sizeof (GstVideoDecoderPrivate));
499
500   gobject_class->finalize = gst_video_decoder_finalize;
501
502   gstelement_class->change_state =
503       GST_DEBUG_FUNCPTR (gst_video_decoder_change_state);
504
505   klass->sink_event = gst_video_decoder_sink_event_default;
506   klass->src_event = gst_video_decoder_src_event_default;
507   klass->decide_allocation = gst_video_decoder_decide_allocation_default;
508   klass->propose_allocation = gst_video_decoder_propose_allocation_default;
509   klass->negotiate = gst_video_decoder_negotiate_default;
510 }
511
512 static void
513 gst_video_decoder_init (GstVideoDecoder * decoder, GstVideoDecoderClass * klass)
514 {
515   GstPadTemplate *pad_template;
516   GstPad *pad;
517
518   GST_DEBUG_OBJECT (decoder, "gst_video_decoder_init");
519
520   decoder->priv = GST_VIDEO_DECODER_GET_PRIVATE (decoder);
521
522   pad_template =
523       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
524   g_return_if_fail (pad_template != NULL);
525
526   decoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
527
528   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_decoder_chain));
529   gst_pad_set_event_function (pad,
530       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_event));
531   gst_pad_set_query_function (pad,
532       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_query));
533   gst_element_add_pad (GST_ELEMENT (decoder), decoder->sinkpad);
534
535   pad_template =
536       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
537   g_return_if_fail (pad_template != NULL);
538
539   decoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
540
541   gst_pad_set_event_function (pad,
542       GST_DEBUG_FUNCPTR (gst_video_decoder_src_event));
543   gst_pad_set_query_function (pad,
544       GST_DEBUG_FUNCPTR (gst_video_decoder_src_query));
545   gst_pad_use_fixed_caps (pad);
546   gst_element_add_pad (GST_ELEMENT (decoder), decoder->srcpad);
547
548   gst_segment_init (&decoder->input_segment, GST_FORMAT_TIME);
549   gst_segment_init (&decoder->output_segment, GST_FORMAT_TIME);
550
551   g_rec_mutex_init (&decoder->stream_lock);
552
553   decoder->priv->input_adapter = gst_adapter_new ();
554   decoder->priv->output_adapter = gst_adapter_new ();
555   decoder->priv->packetized = TRUE;
556
557   gst_video_decoder_reset (decoder, TRUE);
558 }
559
560 static gboolean
561 gst_video_rawvideo_convert (GstVideoCodecState * state,
562     GstFormat src_format, gint64 src_value,
563     GstFormat * dest_format, gint64 * dest_value)
564 {
565   gboolean res = FALSE;
566   guint vidsize;
567   guint fps_n, fps_d;
568
569   g_return_val_if_fail (dest_format != NULL, FALSE);
570   g_return_val_if_fail (dest_value != NULL, FALSE);
571
572   if (src_format == *dest_format || src_value == 0 || src_value == -1) {
573     *dest_value = src_value;
574     return TRUE;
575   }
576
577   vidsize = GST_VIDEO_INFO_SIZE (&state->info);
578   fps_n = GST_VIDEO_INFO_FPS_N (&state->info);
579   fps_d = GST_VIDEO_INFO_FPS_D (&state->info);
580
581   if (src_format == GST_FORMAT_BYTES &&
582       *dest_format == GST_FORMAT_DEFAULT && vidsize) {
583     /* convert bytes to frames */
584     *dest_value = gst_util_uint64_scale_int (src_value, 1, vidsize);
585     res = TRUE;
586   } else if (src_format == GST_FORMAT_DEFAULT &&
587       *dest_format == GST_FORMAT_BYTES && vidsize) {
588     /* convert bytes to frames */
589     *dest_value = src_value * vidsize;
590     res = TRUE;
591   } else if (src_format == GST_FORMAT_DEFAULT &&
592       *dest_format == GST_FORMAT_TIME && fps_n) {
593     /* convert frames to time */
594     *dest_value = gst_util_uint64_scale (src_value, GST_SECOND * fps_d, fps_n);
595     res = TRUE;
596   } else if (src_format == GST_FORMAT_TIME &&
597       *dest_format == GST_FORMAT_DEFAULT && fps_d) {
598     /* convert time to frames */
599     *dest_value = gst_util_uint64_scale (src_value, fps_n, GST_SECOND * fps_d);
600     res = TRUE;
601   } else if (src_format == GST_FORMAT_TIME &&
602       *dest_format == GST_FORMAT_BYTES && fps_d && vidsize) {
603     /* convert time to frames */
604     *dest_value = gst_util_uint64_scale (src_value,
605         fps_n * vidsize, GST_SECOND * fps_d);
606     res = TRUE;
607   } else if (src_format == GST_FORMAT_BYTES &&
608       *dest_format == GST_FORMAT_TIME && fps_n && vidsize) {
609     /* convert frames to time */
610     *dest_value = gst_util_uint64_scale (src_value,
611         GST_SECOND * fps_d, fps_n * vidsize);
612     res = TRUE;
613   }
614
615   return res;
616 }
617
618 static gboolean
619 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
620     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
621     gint64 * dest_value)
622 {
623   gboolean res = FALSE;
624
625   g_return_val_if_fail (dest_format != NULL, FALSE);
626   g_return_val_if_fail (dest_value != NULL, FALSE);
627
628   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
629           src_value == -1)) {
630     if (dest_value)
631       *dest_value = src_value;
632     return TRUE;
633   }
634
635   if (bytes <= 0 || time <= 0) {
636     GST_DEBUG ("not enough metadata yet to convert");
637     goto exit;
638   }
639
640   switch (src_format) {
641     case GST_FORMAT_BYTES:
642       switch (*dest_format) {
643         case GST_FORMAT_TIME:
644           *dest_value = gst_util_uint64_scale (src_value, time, bytes);
645           res = TRUE;
646           break;
647         default:
648           res = FALSE;
649       }
650       break;
651     case GST_FORMAT_TIME:
652       switch (*dest_format) {
653         case GST_FORMAT_BYTES:
654           *dest_value = gst_util_uint64_scale (src_value, bytes, time);
655           res = TRUE;
656           break;
657         default:
658           res = FALSE;
659       }
660       break;
661     default:
662       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
663           *dest_format);
664       res = FALSE;
665   }
666
667 exit:
668   return res;
669 }
670
671 static GstVideoCodecState *
672 _new_input_state (GstCaps * caps)
673 {
674   GstVideoCodecState *state;
675   GstStructure *structure;
676   const GValue *codec_data;
677
678   state = g_slice_new0 (GstVideoCodecState);
679   state->ref_count = 1;
680   gst_video_info_init (&state->info);
681   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
682     goto parse_fail;
683   state->caps = gst_caps_ref (caps);
684
685   structure = gst_caps_get_structure (caps, 0);
686
687   codec_data = gst_structure_get_value (structure, "codec_data");
688   if (codec_data && G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER)
689     state->codec_data = GST_BUFFER (g_value_dup_boxed (codec_data));
690
691   return state;
692
693 parse_fail:
694   {
695     g_slice_free (GstVideoCodecState, state);
696     return NULL;
697   }
698 }
699
700 static GstVideoCodecState *
701 _new_output_state (GstVideoFormat fmt, guint width, guint height,
702     GstVideoCodecState * reference)
703 {
704   GstVideoCodecState *state;
705
706   state = g_slice_new0 (GstVideoCodecState);
707   state->ref_count = 1;
708   gst_video_info_init (&state->info);
709   gst_video_info_set_format (&state->info, fmt, width, height);
710
711   if (reference) {
712     GstVideoInfo *tgt, *ref;
713
714     tgt = &state->info;
715     ref = &reference->info;
716
717     /* Copy over extra fields from reference state */
718     tgt->interlace_mode = ref->interlace_mode;
719     tgt->flags = ref->flags;
720     tgt->chroma_site = ref->chroma_site;
721     /* only copy values that are not unknown so that we don't override the
722      * defaults. subclasses should really fill these in when they know. */
723     if (ref->colorimetry.range)
724       tgt->colorimetry.range = ref->colorimetry.range;
725     if (ref->colorimetry.matrix)
726       tgt->colorimetry.matrix = ref->colorimetry.matrix;
727     if (ref->colorimetry.transfer)
728       tgt->colorimetry.transfer = ref->colorimetry.transfer;
729     if (ref->colorimetry.primaries)
730       tgt->colorimetry.primaries = ref->colorimetry.primaries;
731     GST_DEBUG ("reference par %d/%d fps %d/%d",
732         ref->par_n, ref->par_d, ref->fps_n, ref->fps_d);
733     tgt->par_n = ref->par_n;
734     tgt->par_d = ref->par_d;
735     tgt->fps_n = ref->fps_n;
736     tgt->fps_d = ref->fps_d;
737   }
738
739   GST_DEBUG ("reference par %d/%d fps %d/%d",
740       state->info.par_n, state->info.par_d,
741       state->info.fps_n, state->info.fps_d);
742
743   return state;
744 }
745
746 static gboolean
747 gst_video_decoder_setcaps (GstVideoDecoder * decoder, GstCaps * caps)
748 {
749   GstVideoDecoderClass *decoder_class;
750   GstVideoCodecState *state;
751   gboolean ret = TRUE;
752
753   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
754
755   GST_DEBUG_OBJECT (decoder, "setcaps %" GST_PTR_FORMAT, caps);
756
757   state = _new_input_state (caps);
758
759   if (G_UNLIKELY (state == NULL))
760     goto parse_fail;
761
762   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
763
764   if (decoder_class->set_format)
765     ret = decoder_class->set_format (decoder, state);
766
767   if (!ret)
768     goto refused_format;
769
770   if (decoder->priv->input_state)
771     gst_video_codec_state_unref (decoder->priv->input_state);
772   decoder->priv->input_state = state;
773
774   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
775
776   return ret;
777
778   /* ERRORS */
779
780 parse_fail:
781   {
782     GST_WARNING_OBJECT (decoder, "Failed to parse caps");
783     return FALSE;
784   }
785
786 refused_format:
787   {
788     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
789     GST_WARNING_OBJECT (decoder, "Subclass refused caps");
790     gst_video_codec_state_unref (state);
791     return FALSE;
792   }
793 }
794
795 static void
796 gst_video_decoder_finalize (GObject * object)
797 {
798   GstVideoDecoder *decoder;
799
800   decoder = GST_VIDEO_DECODER (object);
801
802   GST_DEBUG_OBJECT (object, "finalize");
803
804   g_rec_mutex_clear (&decoder->stream_lock);
805
806   if (decoder->priv->input_adapter) {
807     g_object_unref (decoder->priv->input_adapter);
808     decoder->priv->input_adapter = NULL;
809   }
810   if (decoder->priv->output_adapter) {
811     g_object_unref (decoder->priv->output_adapter);
812     decoder->priv->output_adapter = NULL;
813   }
814
815   if (decoder->priv->input_state)
816     gst_video_codec_state_unref (decoder->priv->input_state);
817   if (decoder->priv->output_state)
818     gst_video_codec_state_unref (decoder->priv->output_state);
819
820   if (decoder->priv->pool) {
821     gst_object_unref (decoder->priv->pool);
822     decoder->priv->pool = NULL;
823   }
824
825   if (decoder->priv->allocator) {
826     gst_object_unref (decoder->priv->allocator);
827     decoder->priv->allocator = NULL;
828   }
829
830   G_OBJECT_CLASS (parent_class)->finalize (object);
831 }
832
833 /* hard == FLUSH, otherwise discont */
834 static GstFlowReturn
835 gst_video_decoder_flush (GstVideoDecoder * dec, gboolean hard)
836 {
837   GstVideoDecoderClass *klass;
838   GstVideoDecoderPrivate *priv = dec->priv;
839   GstFlowReturn ret = GST_FLOW_OK;
840
841   klass = GST_VIDEO_DECODER_GET_CLASS (dec);
842
843   GST_LOG_OBJECT (dec, "flush hard %d", hard);
844
845   /* Inform subclass */
846   if (klass->reset)
847     klass->reset (dec, hard);
848
849   /* FIXME make some more distinction between hard and soft,
850    * but subclass may not be prepared for that */
851   /* FIXME perhaps also clear pending frames ?,
852    * but again, subclass may still come up with one of those */
853   if (!hard) {
854     /* TODO ? finish/drain some stuff */
855   } else {
856     gst_segment_init (&dec->input_segment, GST_FORMAT_UNDEFINED);
857     gst_segment_init (&dec->output_segment, GST_FORMAT_UNDEFINED);
858     gst_video_decoder_clear_queues (dec);
859     priv->error_count = 0;
860     g_list_free_full (priv->current_frame_events,
861         (GDestroyNotify) gst_event_unref);
862     priv->current_frame_events = NULL;
863   }
864   /* and get (re)set for the sequel */
865   gst_video_decoder_reset (dec, FALSE);
866
867   return ret;
868 }
869
870 static gboolean
871 gst_video_decoder_push_event (GstVideoDecoder * decoder, GstEvent * event)
872 {
873   switch (GST_EVENT_TYPE (event)) {
874     case GST_EVENT_SEGMENT:
875     {
876       GstSegment segment;
877
878       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
879
880       gst_event_copy_segment (event, &segment);
881
882       GST_DEBUG_OBJECT (decoder, "segment %" GST_SEGMENT_FORMAT, &segment);
883
884       if (segment.format != GST_FORMAT_TIME) {
885         GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
886         GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
887         break;
888       }
889
890       decoder->output_segment = segment;
891       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
892       break;
893     }
894     default:
895       break;
896   }
897
898   return gst_pad_push_event (decoder->srcpad, event);
899 }
900
901 static GstFlowReturn
902 gst_video_decoder_drain_out (GstVideoDecoder * dec, gboolean at_eos)
903 {
904   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_GET_CLASS (dec);
905   GstVideoDecoderPrivate *priv = dec->priv;
906   GstFlowReturn ret = GST_FLOW_OK;
907
908   GST_VIDEO_DECODER_STREAM_LOCK (dec);
909
910   if (dec->input_segment.rate > 0.0) {
911     /* Forward mode, if unpacketized, give the child class
912      * a final chance to flush out packets */
913     if (!priv->packetized) {
914       while (ret == GST_FLOW_OK && gst_adapter_available (priv->input_adapter)) {
915         if (priv->current_frame == NULL)
916           priv->current_frame = gst_video_decoder_new_frame (dec);
917
918         ret = decoder_class->parse (dec, priv->current_frame,
919             priv->input_adapter, TRUE);
920       }
921     }
922   } else {
923     /* Reverse playback mode */
924     ret = gst_video_decoder_flush_parse (dec, TRUE);
925   }
926
927   if (at_eos) {
928     if (decoder_class->finish)
929       ret = decoder_class->finish (dec);
930   }
931
932   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
933
934   return ret;
935 }
936
937 static gboolean
938 gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
939     GstEvent * event)
940 {
941   GstVideoDecoderPrivate *priv;
942   gboolean ret = FALSE;
943   gboolean forward_immediate = FALSE;
944
945   priv = decoder->priv;
946
947   switch (GST_EVENT_TYPE (event)) {
948     case GST_EVENT_CAPS:
949     {
950       GstCaps *caps;
951
952       gst_event_parse_caps (event, &caps);
953       ret = TRUE;
954       decoder->priv->do_caps = TRUE;
955       gst_event_unref (event);
956       event = NULL;
957       break;
958     }
959     case GST_EVENT_EOS:
960     {
961       GstFlowReturn flow_ret = GST_FLOW_OK;
962
963       flow_ret = gst_video_decoder_drain_out (decoder, TRUE);
964       ret = (flow_ret == GST_FLOW_OK);
965       /* Forward EOS immediately. This is required because no
966        * buffer or serialized event will come after EOS and
967        * nothing could trigger another _finish_frame() call.
968        *
969        * The subclass can override this behaviour by overriding
970        * the ::sink_event() vfunc and not chaining up to the
971        * parent class' ::sink_event() until a later time.
972        */
973       forward_immediate = TRUE;
974       break;
975     }
976     case GST_EVENT_GAP:
977     {
978       GstFlowReturn flow_ret = GST_FLOW_OK;
979
980       flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
981       ret = (flow_ret == GST_FLOW_OK);
982
983       /* Forward GAP immediately. Everything is drained after
984        * the GAP event and we can forward this event immediately
985        * now without having buffers out of order.
986        */
987       forward_immediate = TRUE;
988       break;
989     }
990     case GST_EVENT_CUSTOM_DOWNSTREAM:
991     {
992       gboolean in_still;
993       GstFlowReturn flow_ret = GST_FLOW_OK;
994
995       if (gst_video_event_parse_still_frame (event, &in_still)) {
996         if (in_still) {
997           GST_DEBUG_OBJECT (decoder, "draining current data for still-frame");
998           flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
999           ret = (flow_ret == GST_FLOW_OK);
1000         }
1001         /* Forward STILL_FRAME immediately. Everything is drained after
1002          * the STILL_FRAME event and we can forward this event immediately
1003          * now without having buffers out of order.
1004          */
1005         forward_immediate = TRUE;
1006       }
1007       break;
1008     }
1009     case GST_EVENT_SEGMENT:
1010     {
1011       GstSegment segment;
1012
1013       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1014
1015       gst_event_copy_segment (event, &segment);
1016
1017       if (segment.format == GST_FORMAT_TIME) {
1018         GST_DEBUG_OBJECT (decoder,
1019             "received TIME SEGMENT %" GST_SEGMENT_FORMAT, &segment);
1020       } else {
1021         gint64 start;
1022
1023         GST_DEBUG_OBJECT (decoder,
1024             "received SEGMENT %" GST_SEGMENT_FORMAT, &segment);
1025
1026         /* handle newsegment as a result from our legacy simple seeking */
1027         /* note that initial 0 should convert to 0 in any case */
1028         if (priv->do_estimate_rate &&
1029             gst_pad_query_convert (decoder->sinkpad, GST_FORMAT_BYTES,
1030                 segment.start, GST_FORMAT_TIME, &start)) {
1031           /* best attempt convert */
1032           /* as these are only estimates, stop is kept open-ended to avoid
1033            * premature cutting */
1034           GST_DEBUG_OBJECT (decoder,
1035               "converted to TIME start %" GST_TIME_FORMAT,
1036               GST_TIME_ARGS (start));
1037           segment.start = start;
1038           segment.stop = GST_CLOCK_TIME_NONE;
1039           segment.time = start;
1040           /* replace event */
1041           gst_event_unref (event);
1042           event = gst_event_new_segment (&segment);
1043         } else {
1044           GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1045           goto newseg_wrong_format;
1046         }
1047       }
1048
1049       gst_video_decoder_flush (decoder, FALSE);
1050
1051       priv->base_timestamp = GST_CLOCK_TIME_NONE;
1052       priv->base_picture_number = 0;
1053
1054       decoder->input_segment = segment;
1055
1056       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1057       break;
1058     }
1059     case GST_EVENT_FLUSH_STOP:
1060     {
1061       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1062       /* well, this is kind of worse than a DISCONT */
1063       gst_video_decoder_flush (decoder, TRUE);
1064       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1065       /* Forward FLUSH_STOP immediately. This is required because it is
1066        * expected to be forwarded immediately and no buffers are queued
1067        * anyway.
1068        */
1069       forward_immediate = TRUE;
1070       break;
1071     }
1072     case GST_EVENT_TAG:
1073     {
1074       GstTagList *tags;
1075
1076       gst_event_parse_tag (event, &tags);
1077
1078       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1079         gst_video_decoder_merge_tags (decoder, tags, GST_TAG_MERGE_REPLACE);
1080         gst_event_unref (event);
1081         event = NULL;
1082         ret = TRUE;
1083       }
1084       break;
1085     }
1086     default:
1087       break;
1088   }
1089
1090   /* Forward non-serialized events immediately, and all other
1091    * events which can be forwarded immediately without potentially
1092    * causing the event to go out of order with other events and
1093    * buffers as decided above.
1094    */
1095   if (event) {
1096     if (!GST_EVENT_IS_SERIALIZED (event) || forward_immediate) {
1097       ret = gst_video_decoder_push_event (decoder, event);
1098     } else {
1099       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1100       decoder->priv->current_frame_events =
1101           g_list_prepend (decoder->priv->current_frame_events, event);
1102       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1103       ret = TRUE;
1104     }
1105   }
1106
1107   return ret;
1108
1109 newseg_wrong_format:
1110   {
1111     GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
1112     gst_event_unref (event);
1113     /* SWALLOW EVENT */
1114     return TRUE;
1115   }
1116 }
1117
1118 static gboolean
1119 gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
1120     GstEvent * event)
1121 {
1122   GstVideoDecoder *decoder;
1123   GstVideoDecoderClass *decoder_class;
1124   gboolean ret = FALSE;
1125
1126   decoder = GST_VIDEO_DECODER (parent);
1127   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1128
1129   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1130       GST_EVENT_TYPE_NAME (event));
1131
1132   if (decoder_class->sink_event)
1133     ret = decoder_class->sink_event (decoder, event);
1134
1135   return ret;
1136 }
1137
1138 /* perform upstream byte <-> time conversion (duration, seeking)
1139  * if subclass allows and if enough data for moderately decent conversion */
1140 static inline gboolean
1141 gst_video_decoder_do_byte (GstVideoDecoder * dec)
1142 {
1143   return dec->priv->do_estimate_rate && (dec->priv->bytes_out > 0)
1144       && (dec->priv->time > GST_SECOND);
1145 }
1146
1147 static gboolean
1148 gst_video_decoder_do_seek (GstVideoDecoder * dec, GstEvent * event)
1149 {
1150   GstFormat format;
1151   GstSeekFlags flags;
1152   GstSeekType start_type, end_type;
1153   gdouble rate;
1154   gint64 start, start_time, end_time;
1155   GstSegment seek_segment;
1156   guint32 seqnum;
1157
1158   gst_event_parse_seek (event, &rate, &format, &flags, &start_type,
1159       &start_time, &end_type, &end_time);
1160
1161   /* we'll handle plain open-ended flushing seeks with the simple approach */
1162   if (rate != 1.0) {
1163     GST_DEBUG_OBJECT (dec, "unsupported seek: rate");
1164     return FALSE;
1165   }
1166
1167   if (start_type != GST_SEEK_TYPE_SET) {
1168     GST_DEBUG_OBJECT (dec, "unsupported seek: start time");
1169     return FALSE;
1170   }
1171
1172   if (end_type != GST_SEEK_TYPE_NONE ||
1173       (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) {
1174     GST_DEBUG_OBJECT (dec, "unsupported seek: end time");
1175     return FALSE;
1176   }
1177
1178   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
1179     GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing");
1180     return FALSE;
1181   }
1182
1183   memcpy (&seek_segment, &dec->output_segment, sizeof (seek_segment));
1184   gst_segment_do_seek (&seek_segment, rate, format, flags, start_type,
1185       start_time, end_type, end_time, NULL);
1186   start_time = seek_segment.position;
1187
1188   if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time,
1189           GST_FORMAT_BYTES, &start)) {
1190     GST_DEBUG_OBJECT (dec, "conversion failed");
1191     return FALSE;
1192   }
1193
1194   seqnum = gst_event_get_seqnum (event);
1195   event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags,
1196       GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1);
1197   gst_event_set_seqnum (event, seqnum);
1198
1199   GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %"
1200       G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start);
1201
1202   return gst_pad_push_event (dec->sinkpad, event);
1203 }
1204
1205 static gboolean
1206 gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
1207     GstEvent * event)
1208 {
1209   GstVideoDecoderPrivate *priv;
1210   gboolean res = FALSE;
1211
1212   priv = decoder->priv;
1213
1214   GST_DEBUG_OBJECT (decoder,
1215       "received event %d, %s", GST_EVENT_TYPE (event),
1216       GST_EVENT_TYPE_NAME (event));
1217
1218   switch (GST_EVENT_TYPE (event)) {
1219     case GST_EVENT_SEEK:
1220     {
1221       GstFormat format;
1222       gdouble rate;
1223       GstSeekFlags flags;
1224       GstSeekType start_type, stop_type;
1225       gint64 start, stop;
1226       gint64 tstart, tstop;
1227       guint32 seqnum;
1228
1229       gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
1230           &stop_type, &stop);
1231       seqnum = gst_event_get_seqnum (event);
1232
1233       /* upstream gets a chance first */
1234       if ((res = gst_pad_push_event (decoder->sinkpad, event)))
1235         break;
1236
1237       /* if upstream fails for a time seek, maybe we can help if allowed */
1238       if (format == GST_FORMAT_TIME) {
1239         if (gst_video_decoder_do_byte (decoder))
1240           res = gst_video_decoder_do_seek (decoder, event);
1241         break;
1242       }
1243
1244       /* ... though a non-time seek can be aided as well */
1245       /* First bring the requested format to time */
1246       if (!(res =
1247               gst_pad_query_convert (decoder->srcpad, format, start,
1248                   GST_FORMAT_TIME, &tstart)))
1249         goto convert_error;
1250       if (!(res =
1251               gst_pad_query_convert (decoder->srcpad, format, stop,
1252                   GST_FORMAT_TIME, &tstop)))
1253         goto convert_error;
1254
1255       /* then seek with time on the peer */
1256       event = gst_event_new_seek (rate, GST_FORMAT_TIME,
1257           flags, start_type, tstart, stop_type, tstop);
1258       gst_event_set_seqnum (event, seqnum);
1259
1260       res = gst_pad_push_event (decoder->sinkpad, event);
1261       break;
1262     }
1263     case GST_EVENT_QOS:
1264     {
1265       GstQOSType type;
1266       gdouble proportion;
1267       GstClockTimeDiff diff;
1268       GstClockTime timestamp;
1269
1270       gst_event_parse_qos (event, &type, &proportion, &diff, &timestamp);
1271
1272       GST_OBJECT_LOCK (decoder);
1273       priv->proportion = proportion;
1274       if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (timestamp))) {
1275         if (G_UNLIKELY (diff > 0)) {
1276           priv->earliest_time = timestamp + 2 * diff + priv->qos_frame_duration;
1277         } else {
1278           priv->earliest_time = timestamp + diff;
1279         }
1280       } else {
1281         priv->earliest_time = GST_CLOCK_TIME_NONE;
1282       }
1283       GST_OBJECT_UNLOCK (decoder);
1284
1285       GST_DEBUG_OBJECT (decoder,
1286           "got QoS %" GST_TIME_FORMAT ", %" G_GINT64_FORMAT ", %g",
1287           GST_TIME_ARGS (timestamp), diff, proportion);
1288
1289       res = gst_pad_push_event (decoder->sinkpad, event);
1290       break;
1291     }
1292     default:
1293       res = gst_pad_push_event (decoder->sinkpad, event);
1294       break;
1295   }
1296 done:
1297   return res;
1298
1299 convert_error:
1300   GST_DEBUG_OBJECT (decoder, "could not convert format");
1301   goto done;
1302 }
1303
1304 static gboolean
1305 gst_video_decoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1306 {
1307   GstVideoDecoder *decoder;
1308   GstVideoDecoderClass *decoder_class;
1309   gboolean ret = FALSE;
1310
1311   decoder = GST_VIDEO_DECODER (parent);
1312   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1313
1314   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1315       GST_EVENT_TYPE_NAME (event));
1316
1317   if (decoder_class->src_event)
1318     ret = decoder_class->src_event (decoder, event);
1319
1320   return ret;
1321 }
1322
1323 static gboolean
1324 gst_video_decoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1325 {
1326   GstVideoDecoder *dec;
1327   gboolean res = TRUE;
1328
1329   dec = GST_VIDEO_DECODER (parent);
1330
1331   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
1332
1333   switch (GST_QUERY_TYPE (query)) {
1334     case GST_QUERY_POSITION:
1335     {
1336       GstFormat format;
1337       gint64 time, value;
1338
1339       /* upstream gets a chance first */
1340       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
1341         GST_LOG_OBJECT (dec, "returning peer response");
1342         break;
1343       }
1344
1345       /* we start from the last seen time */
1346       time = dec->priv->last_timestamp_out;
1347       /* correct for the segment values */
1348       time = gst_segment_to_stream_time (&dec->output_segment,
1349           GST_FORMAT_TIME, time);
1350
1351       GST_LOG_OBJECT (dec,
1352           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
1353
1354       /* and convert to the final format */
1355       gst_query_parse_position (query, &format, NULL);
1356       if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time,
1357                   format, &value)))
1358         break;
1359
1360       gst_query_set_position (query, format, value);
1361
1362       GST_LOG_OBJECT (dec,
1363           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
1364           format);
1365       break;
1366     }
1367     case GST_QUERY_DURATION:
1368     {
1369       GstFormat format;
1370
1371       /* upstream in any case */
1372       if ((res = gst_pad_query_default (pad, parent, query)))
1373         break;
1374
1375       gst_query_parse_duration (query, &format, NULL);
1376       /* try answering TIME by converting from BYTE if subclass allows  */
1377       if (format == GST_FORMAT_TIME && gst_video_decoder_do_byte (dec)) {
1378         gint64 value;
1379
1380         if (gst_pad_peer_query_duration (dec->sinkpad, GST_FORMAT_BYTES,
1381                 &value)) {
1382           GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value);
1383           if (gst_pad_query_convert (dec->sinkpad,
1384                   GST_FORMAT_BYTES, value, GST_FORMAT_TIME, &value)) {
1385             gst_query_set_duration (query, GST_FORMAT_TIME, value);
1386             res = TRUE;
1387           }
1388         }
1389       }
1390       break;
1391     }
1392     case GST_QUERY_CONVERT:
1393     {
1394       GstFormat src_fmt, dest_fmt;
1395       gint64 src_val, dest_val;
1396
1397       GST_DEBUG_OBJECT (dec, "convert query");
1398
1399       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1400       GST_OBJECT_LOCK (dec);
1401       if (dec->priv->output_state != NULL)
1402         res = gst_video_rawvideo_convert (dec->priv->output_state,
1403             src_fmt, src_val, &dest_fmt, &dest_val);
1404       else
1405         res = FALSE;
1406       GST_OBJECT_UNLOCK (dec);
1407       if (!res)
1408         goto error;
1409       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1410       break;
1411     }
1412     case GST_QUERY_LATENCY:
1413     {
1414       gboolean live;
1415       GstClockTime min_latency, max_latency;
1416
1417       res = gst_pad_peer_query (dec->sinkpad, query);
1418       if (res) {
1419         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1420         GST_DEBUG_OBJECT (dec, "Peer qlatency: live %d, min %"
1421             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1422             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1423
1424         GST_OBJECT_LOCK (dec);
1425         min_latency += dec->priv->min_latency;
1426         if (dec->priv->max_latency == GST_CLOCK_TIME_NONE) {
1427           max_latency = GST_CLOCK_TIME_NONE;
1428         } else if (max_latency != GST_CLOCK_TIME_NONE) {
1429           max_latency += dec->priv->max_latency;
1430         }
1431         GST_OBJECT_UNLOCK (dec);
1432
1433         gst_query_set_latency (query, live, min_latency, max_latency);
1434       }
1435     }
1436       break;
1437     default:
1438       res = gst_pad_query_default (pad, parent, query);
1439   }
1440   return res;
1441
1442 error:
1443   GST_ERROR_OBJECT (dec, "query failed");
1444   return res;
1445 }
1446
1447 static gboolean
1448 gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
1449     GstQuery * query)
1450 {
1451   GstVideoDecoder *decoder;
1452   GstVideoDecoderPrivate *priv;
1453   gboolean res = FALSE;
1454
1455   decoder = GST_VIDEO_DECODER (parent);
1456   priv = decoder->priv;
1457
1458   GST_LOG_OBJECT (decoder, "handling query: %" GST_PTR_FORMAT, query);
1459
1460   switch (GST_QUERY_TYPE (query)) {
1461     case GST_QUERY_CONVERT:
1462     {
1463       GstFormat src_fmt, dest_fmt;
1464       gint64 src_val, dest_val;
1465
1466       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1467       res =
1468           gst_video_encoded_video_convert (priv->bytes_out, priv->time, src_fmt,
1469           src_val, &dest_fmt, &dest_val);
1470       if (!res)
1471         goto error;
1472       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1473       break;
1474     }
1475     case GST_QUERY_ALLOCATION:{
1476       GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
1477
1478       if (klass->propose_allocation)
1479         res = klass->propose_allocation (decoder, query);
1480       break;
1481     }
1482     default:
1483       res = gst_pad_query_default (pad, parent, query);
1484       break;
1485   }
1486 done:
1487
1488   return res;
1489 error:
1490   GST_DEBUG_OBJECT (decoder, "query failed");
1491   goto done;
1492 }
1493
1494 typedef struct _Timestamp Timestamp;
1495 struct _Timestamp
1496 {
1497   guint64 offset;
1498   GstClockTime pts;
1499   GstClockTime dts;
1500   GstClockTime duration;
1501 };
1502
1503 static void
1504 timestamp_free (Timestamp * ts)
1505 {
1506   g_slice_free (Timestamp, ts);
1507 }
1508
1509 static void
1510 gst_video_decoder_add_timestamp (GstVideoDecoder * decoder, GstBuffer * buffer)
1511 {
1512   GstVideoDecoderPrivate *priv = decoder->priv;
1513   Timestamp *ts;
1514
1515   ts = g_slice_new (Timestamp);
1516
1517   GST_LOG_OBJECT (decoder,
1518       "adding PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT
1519       " (offset:%" G_GUINT64_FORMAT ")",
1520       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1521       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), priv->input_offset);
1522
1523   ts->offset = priv->input_offset;
1524   ts->pts = GST_BUFFER_PTS (buffer);
1525   ts->dts = GST_BUFFER_DTS (buffer);
1526   ts->duration = GST_BUFFER_DURATION (buffer);
1527
1528   priv->timestamps = g_list_append (priv->timestamps, ts);
1529 }
1530
1531 static void
1532 gst_video_decoder_get_timestamp_at_offset (GstVideoDecoder *
1533     decoder, guint64 offset, GstClockTime * pts, GstClockTime * dts,
1534     GstClockTime * duration)
1535 {
1536 #ifndef GST_DISABLE_GST_DEBUG
1537   guint64 got_offset = 0;
1538 #endif
1539   Timestamp *ts;
1540   GList *g;
1541
1542   *pts = GST_CLOCK_TIME_NONE;
1543   *dts = GST_CLOCK_TIME_NONE;
1544   *duration = GST_CLOCK_TIME_NONE;
1545
1546   g = decoder->priv->timestamps;
1547   while (g) {
1548     ts = g->data;
1549     if (ts->offset <= offset) {
1550 #ifndef GST_DISABLE_GST_DEBUG
1551       got_offset = ts->offset;
1552 #endif
1553       *pts = ts->pts;
1554       *dts = ts->dts;
1555       *duration = ts->duration;
1556       timestamp_free (ts);
1557       g = g->next;
1558       decoder->priv->timestamps = g_list_remove (decoder->priv->timestamps, ts);
1559     } else {
1560       break;
1561     }
1562   }
1563
1564   GST_LOG_OBJECT (decoder,
1565       "got PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT " @ offs %"
1566       G_GUINT64_FORMAT " (wanted offset:%" G_GUINT64_FORMAT ")",
1567       GST_TIME_ARGS (*pts), GST_TIME_ARGS (*dts), got_offset, offset);
1568 }
1569
1570 static void
1571 gst_video_decoder_clear_queues (GstVideoDecoder * dec)
1572 {
1573   GstVideoDecoderPrivate *priv = dec->priv;
1574
1575   g_list_free_full (priv->output_queued,
1576       (GDestroyNotify) gst_mini_object_unref);
1577   priv->output_queued = NULL;
1578
1579   g_list_free_full (priv->gather, (GDestroyNotify) gst_mini_object_unref);
1580   priv->gather = NULL;
1581   g_list_free_full (priv->decode, (GDestroyNotify) gst_video_codec_frame_unref);
1582   priv->decode = NULL;
1583   g_list_free_full (priv->parse, (GDestroyNotify) gst_mini_object_unref);
1584   priv->parse = NULL;
1585   g_list_free_full (priv->parse_gather,
1586       (GDestroyNotify) gst_video_codec_frame_unref);
1587   priv->parse_gather = NULL;
1588   g_list_free_full (priv->frames, (GDestroyNotify) gst_video_codec_frame_unref);
1589   priv->frames = NULL;
1590 }
1591
1592 static void
1593 gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full)
1594 {
1595   GstVideoDecoderPrivate *priv = decoder->priv;
1596
1597   GST_DEBUG_OBJECT (decoder, "reset full %d", full);
1598
1599   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1600
1601   if (full) {
1602     gst_segment_init (&decoder->input_segment, GST_FORMAT_UNDEFINED);
1603     gst_segment_init (&decoder->output_segment, GST_FORMAT_UNDEFINED);
1604     gst_video_decoder_clear_queues (decoder);
1605     priv->error_count = 0;
1606     priv->max_errors = GST_VIDEO_DECODER_MAX_ERRORS;
1607     if (priv->input_state)
1608       gst_video_codec_state_unref (priv->input_state);
1609     priv->input_state = NULL;
1610     GST_OBJECT_LOCK (decoder);
1611     if (priv->output_state)
1612       gst_video_codec_state_unref (priv->output_state);
1613     priv->output_state = NULL;
1614
1615     priv->qos_frame_duration = 0;
1616     GST_OBJECT_UNLOCK (decoder);
1617
1618     priv->min_latency = 0;
1619     priv->max_latency = 0;
1620
1621     if (priv->tags)
1622       gst_tag_list_unref (priv->tags);
1623     priv->tags = NULL;
1624     priv->tags_changed = FALSE;
1625     priv->reordered_output = FALSE;
1626   }
1627
1628   priv->discont = TRUE;
1629
1630   priv->base_timestamp = GST_CLOCK_TIME_NONE;
1631   priv->last_timestamp_out = GST_CLOCK_TIME_NONE;
1632   priv->pts_delta = GST_CLOCK_TIME_NONE;
1633
1634   priv->input_offset = 0;
1635   priv->frame_offset = 0;
1636   gst_adapter_clear (priv->input_adapter);
1637   gst_adapter_clear (priv->output_adapter);
1638   g_list_free_full (priv->timestamps, (GDestroyNotify) timestamp_free);
1639   priv->timestamps = NULL;
1640
1641   if (priv->current_frame) {
1642     gst_video_codec_frame_unref (priv->current_frame);
1643     priv->current_frame = NULL;
1644   }
1645
1646   priv->dropped = 0;
1647   priv->processed = 0;
1648
1649   priv->decode_frame_number = 0;
1650   priv->base_picture_number = 0;
1651
1652   g_list_free_full (priv->frames, (GDestroyNotify) gst_video_codec_frame_unref);
1653   priv->frames = NULL;
1654
1655   priv->bytes_out = 0;
1656   priv->time = 0;
1657
1658   GST_OBJECT_LOCK (decoder);
1659   priv->earliest_time = GST_CLOCK_TIME_NONE;
1660   priv->proportion = 0.5;
1661   GST_OBJECT_UNLOCK (decoder);
1662
1663   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1664 }
1665
1666 static GstFlowReturn
1667 gst_video_decoder_chain_forward (GstVideoDecoder * decoder,
1668     GstBuffer * buf, gboolean at_eos)
1669 {
1670   GstVideoDecoderPrivate *priv;
1671   GstVideoDecoderClass *klass;
1672   GstFlowReturn ret = GST_FLOW_OK;
1673
1674   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
1675   priv = decoder->priv;
1676
1677   g_return_val_if_fail (priv->packetized || klass->parse, GST_FLOW_ERROR);
1678
1679   if (priv->current_frame == NULL)
1680     priv->current_frame = gst_video_decoder_new_frame (decoder);
1681
1682   if (GST_BUFFER_PTS_IS_VALID (buf) && !priv->packetized) {
1683     gst_video_decoder_add_timestamp (decoder, buf);
1684   }
1685   priv->input_offset += gst_buffer_get_size (buf);
1686
1687   if (priv->packetized) {
1688     if (!GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
1689       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (priv->current_frame);
1690     }
1691
1692     priv->current_frame->input_buffer = buf;
1693
1694     if (decoder->input_segment.rate < 0.0) {
1695       priv->parse_gather =
1696           g_list_prepend (priv->parse_gather, priv->current_frame);
1697     } else {
1698       ret = gst_video_decoder_decode_frame (decoder, priv->current_frame);
1699     }
1700     priv->current_frame = NULL;
1701   } else {
1702
1703     gst_adapter_push (priv->input_adapter, buf);
1704
1705     if (G_UNLIKELY (!gst_adapter_available (priv->input_adapter)))
1706       goto beach;
1707
1708     do {
1709       /* current frame may have been parsed and handled,
1710        * so we need to set up a new one when asking subclass to parse */
1711       if (priv->current_frame == NULL)
1712         priv->current_frame = gst_video_decoder_new_frame (decoder);
1713
1714       ret = klass->parse (decoder, priv->current_frame,
1715           priv->input_adapter, at_eos);
1716     } while (ret == GST_FLOW_OK && gst_adapter_available (priv->input_adapter));
1717   }
1718
1719 beach:
1720   if (ret == GST_VIDEO_DECODER_FLOW_NEED_DATA)
1721     return GST_FLOW_OK;
1722
1723   return ret;
1724 }
1725
1726 static GstFlowReturn
1727 gst_video_decoder_flush_decode (GstVideoDecoder * dec)
1728 {
1729   GstVideoDecoderPrivate *priv = dec->priv;
1730   GstFlowReturn res = GST_FLOW_OK;
1731   GList *walk;
1732
1733   GST_DEBUG_OBJECT (dec, "flushing buffers to decode");
1734
1735   /* clear buffer and decoder state */
1736   gst_video_decoder_flush (dec, FALSE);
1737
1738   walk = priv->decode;
1739   while (walk) {
1740     GList *next;
1741     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
1742
1743     GST_DEBUG_OBJECT (dec, "decoding frame %p buffer %p, PTS %" GST_TIME_FORMAT
1744         ", DTS %" GST_TIME_FORMAT, frame, frame->input_buffer,
1745         GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)),
1746         GST_TIME_ARGS (GST_BUFFER_DTS (frame->input_buffer)));
1747
1748     next = walk->next;
1749
1750     priv->decode = g_list_delete_link (priv->decode, walk);
1751
1752     /* decode buffer, resulting data prepended to queue */
1753     res = gst_video_decoder_decode_frame (dec, frame);
1754     if (res != GST_FLOW_OK)
1755       break;
1756
1757     walk = next;
1758   }
1759
1760   return res;
1761 }
1762
1763 /* gst_video_decoder_flush_parse is called from the
1764  * chain_reverse() function when a buffer containing
1765  * a DISCONT - indicating that reverse playback
1766  * looped back to the next data block, and therefore
1767  * all available data should be fed through the
1768  * decoder and frames gathered for reversed output
1769  */
1770 static GstFlowReturn
1771 gst_video_decoder_flush_parse (GstVideoDecoder * dec, gboolean at_eos)
1772 {
1773   GstVideoDecoderPrivate *priv = dec->priv;
1774   GstFlowReturn res = GST_FLOW_OK;
1775   GList *walk;
1776
1777   GST_DEBUG_OBJECT (dec, "flushing buffers to parsing");
1778
1779   /* Reverse the gather list, and prepend it to the parse list,
1780    * then flush to parse whatever we can */
1781   priv->gather = g_list_reverse (priv->gather);
1782   priv->parse = g_list_concat (priv->gather, priv->parse);
1783   priv->gather = NULL;
1784
1785   /* clear buffer and decoder state */
1786   gst_video_decoder_flush (dec, FALSE);
1787
1788   walk = priv->parse;
1789   while (walk) {
1790     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1791     GList *next = walk->next;
1792
1793     GST_DEBUG_OBJECT (dec, "parsing buffer %p, PTS %" GST_TIME_FORMAT
1794         ", DTS %" GST_TIME_FORMAT, buf, GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1795         GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
1796
1797     /* parse buffer, resulting frames prepended to parse_gather queue */
1798     gst_buffer_ref (buf);
1799     res = gst_video_decoder_chain_forward (dec, buf, at_eos);
1800
1801     /* if we generated output, we can discard the buffer, else we
1802      * keep it in the queue */
1803     if (priv->parse_gather) {
1804       GST_DEBUG_OBJECT (dec, "parsed buffer to %p", priv->parse_gather->data);
1805       priv->parse = g_list_delete_link (priv->parse, walk);
1806       gst_buffer_unref (buf);
1807     } else {
1808       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1809     }
1810     walk = next;
1811   }
1812
1813   /* now we can process frames. Start by moving each frame from the parse_gather
1814    * to the decode list, reverse the order as we go, and stopping when/if we
1815    * copy a keyframe. */
1816   GST_DEBUG_OBJECT (dec, "checking parsed frames for a keyframe to decode");
1817   walk = priv->parse_gather;
1818   while (walk) {
1819     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
1820
1821     /* remove from the gather list */
1822     priv->parse_gather = g_list_remove_link (priv->parse_gather, walk);
1823
1824     /* move it to the front of the decode queue */
1825     priv->decode = g_list_concat (walk, priv->decode);
1826
1827     /* if we copied a keyframe, flush and decode the decode queue */
1828     if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1829       GST_DEBUG_OBJECT (dec, "found keyframe %p with PTS %" GST_TIME_FORMAT
1830           ", DTS %" GST_TIME_FORMAT, frame,
1831           GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)),
1832           GST_TIME_ARGS (GST_BUFFER_DTS (frame->input_buffer)));
1833       res = gst_video_decoder_flush_decode (dec);
1834       if (res != GST_FLOW_OK)
1835         goto done;
1836     }
1837
1838     walk = priv->parse_gather;
1839   }
1840
1841   /* now send queued data downstream */
1842   walk = priv->output_queued;
1843   while (walk) {
1844     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1845
1846     if (G_LIKELY (res == GST_FLOW_OK)) {
1847       /* avoid stray DISCONT from forward processing,
1848        * which have no meaning in reverse pushing */
1849       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
1850
1851       /* Last chance to calculate a timestamp as we loop backwards
1852        * through the list */
1853       if (GST_BUFFER_TIMESTAMP (buf) != GST_CLOCK_TIME_NONE)
1854         priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
1855       else if (priv->last_timestamp_out != GST_CLOCK_TIME_NONE &&
1856           GST_BUFFER_DURATION (buf) != GST_CLOCK_TIME_NONE) {
1857         GST_BUFFER_TIMESTAMP (buf) =
1858             priv->last_timestamp_out - GST_BUFFER_DURATION (buf);
1859         priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
1860         GST_LOG_OBJECT (dec,
1861             "Calculated TS %" GST_TIME_FORMAT " working backwards",
1862             GST_TIME_ARGS (priv->last_timestamp_out));
1863       }
1864
1865       res = gst_video_decoder_clip_and_push_buf (dec, buf);
1866     } else {
1867       gst_buffer_unref (buf);
1868     }
1869
1870     priv->output_queued =
1871         g_list_delete_link (priv->output_queued, priv->output_queued);
1872     walk = priv->output_queued;
1873   }
1874
1875 done:
1876   return res;
1877 }
1878
1879 static GstFlowReturn
1880 gst_video_decoder_chain_reverse (GstVideoDecoder * dec, GstBuffer * buf)
1881 {
1882   GstVideoDecoderPrivate *priv = dec->priv;
1883   GstFlowReturn result = GST_FLOW_OK;
1884
1885   /* if we have a discont, move buffers to the decode list */
1886   if (!buf || GST_BUFFER_IS_DISCONT (buf)) {
1887     GST_DEBUG_OBJECT (dec, "received discont");
1888
1889     /* parse and decode stuff in the gather and parse queues */
1890     gst_video_decoder_flush_parse (dec, FALSE);
1891   }
1892
1893   if (G_LIKELY (buf)) {
1894     GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %" G_GSIZE_FORMAT ", "
1895         "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
1896         GST_TIME_FORMAT, buf, gst_buffer_get_size (buf),
1897         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1898         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
1899         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1900
1901     /* add buffer to gather queue */
1902     priv->gather = g_list_prepend (priv->gather, buf);
1903   }
1904
1905   return result;
1906 }
1907
1908 static GstFlowReturn
1909 gst_video_decoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1910 {
1911   GstVideoDecoder *decoder;
1912   GstFlowReturn ret = GST_FLOW_OK;
1913
1914   decoder = GST_VIDEO_DECODER (parent);
1915
1916   if (G_UNLIKELY (decoder->priv->do_caps)) {
1917     GstCaps *caps = gst_pad_get_current_caps (decoder->sinkpad);
1918     if (caps) {
1919       if (!gst_video_decoder_setcaps (decoder, caps)) {
1920         gst_caps_unref (caps);
1921         goto not_negotiated;
1922       }
1923       gst_caps_unref (caps);
1924     }
1925     decoder->priv->do_caps = FALSE;
1926   }
1927
1928   GST_LOG_OBJECT (decoder,
1929       "chain PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT " duration %"
1930       GST_TIME_FORMAT " size %" G_GSIZE_FORMAT,
1931       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1932       GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
1933       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), gst_buffer_get_size (buf));
1934
1935   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1936
1937   /* NOTE:
1938    * requiring the pad to be negotiated makes it impossible to use
1939    * oggdemux or filesrc ! decoder */
1940
1941   if (decoder->input_segment.format == GST_FORMAT_UNDEFINED) {
1942     GstEvent *event;
1943     GstSegment *segment = &decoder->input_segment;
1944
1945     GST_WARNING_OBJECT (decoder,
1946         "Received buffer without a new-segment. "
1947         "Assuming timestamps start from 0.");
1948
1949     gst_segment_init (segment, GST_FORMAT_TIME);
1950
1951     event = gst_event_new_segment (segment);
1952
1953     decoder->priv->current_frame_events =
1954         g_list_prepend (decoder->priv->current_frame_events, event);
1955   }
1956
1957   if (decoder->input_segment.rate > 0.0)
1958     ret = gst_video_decoder_chain_forward (decoder, buf, FALSE);
1959   else
1960     ret = gst_video_decoder_chain_reverse (decoder, buf);
1961
1962   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1963   return ret;
1964
1965   /* ERRORS */
1966 not_negotiated:
1967   {
1968     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION, (NULL),
1969         ("encoder not initialized"));
1970     gst_buffer_unref (buf);
1971     return GST_FLOW_NOT_NEGOTIATED;
1972   }
1973 }
1974
1975 static GstStateChangeReturn
1976 gst_video_decoder_change_state (GstElement * element, GstStateChange transition)
1977 {
1978   GstVideoDecoder *decoder;
1979   GstVideoDecoderClass *decoder_class;
1980   GstStateChangeReturn ret;
1981
1982   decoder = GST_VIDEO_DECODER (element);
1983   decoder_class = GST_VIDEO_DECODER_GET_CLASS (element);
1984
1985   switch (transition) {
1986     case GST_STATE_CHANGE_NULL_TO_READY:
1987       /* open device/library if needed */
1988       if (decoder_class->open && !decoder_class->open (decoder))
1989         goto open_failed;
1990       break;
1991     case GST_STATE_CHANGE_READY_TO_PAUSED:
1992       /* Initialize device/library if needed */
1993       if (decoder_class->start && !decoder_class->start (decoder))
1994         goto start_failed;
1995       break;
1996     default:
1997       break;
1998   }
1999
2000   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2001
2002   switch (transition) {
2003     case GST_STATE_CHANGE_PAUSED_TO_READY:
2004       if (decoder_class->stop && !decoder_class->stop (decoder))
2005         goto stop_failed;
2006
2007       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2008       gst_video_decoder_reset (decoder, TRUE);
2009       g_list_free_full (decoder->priv->current_frame_events,
2010           (GDestroyNotify) gst_event_unref);
2011       decoder->priv->current_frame_events = NULL;
2012       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2013       break;
2014     case GST_STATE_CHANGE_READY_TO_NULL:
2015       /* close device/library if needed */
2016       if (decoder_class->close && !decoder_class->close (decoder))
2017         goto close_failed;
2018       break;
2019     default:
2020       break;
2021   }
2022
2023   return ret;
2024
2025   /* Errors */
2026 open_failed:
2027   {
2028     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2029         ("Failed to open decoder"));
2030     return GST_STATE_CHANGE_FAILURE;
2031   }
2032
2033 start_failed:
2034   {
2035     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2036         ("Failed to start decoder"));
2037     return GST_STATE_CHANGE_FAILURE;
2038   }
2039
2040 stop_failed:
2041   {
2042     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2043         ("Failed to stop decoder"));
2044     return GST_STATE_CHANGE_FAILURE;
2045   }
2046
2047 close_failed:
2048   {
2049     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2050         ("Failed to close decoder"));
2051     return GST_STATE_CHANGE_FAILURE;
2052   }
2053 }
2054
2055 static GstVideoCodecFrame *
2056 gst_video_decoder_new_frame (GstVideoDecoder * decoder)
2057 {
2058   GstVideoDecoderPrivate *priv = decoder->priv;
2059   GstVideoCodecFrame *frame;
2060
2061   frame = g_slice_new0 (GstVideoCodecFrame);
2062
2063   frame->ref_count = 1;
2064
2065   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2066   frame->system_frame_number = priv->system_frame_number;
2067   priv->system_frame_number++;
2068   frame->decode_frame_number = priv->decode_frame_number;
2069   priv->decode_frame_number++;
2070
2071   frame->dts = GST_CLOCK_TIME_NONE;
2072   frame->pts = GST_CLOCK_TIME_NONE;
2073   frame->duration = GST_CLOCK_TIME_NONE;
2074   frame->events = priv->current_frame_events;
2075   priv->current_frame_events = NULL;
2076   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2077
2078   GST_LOG_OBJECT (decoder, "Created new frame %p (sfn:%d)",
2079       frame, frame->system_frame_number);
2080
2081   return frame;
2082 }
2083
2084 static void
2085 gst_video_decoder_prepare_finish_frame (GstVideoDecoder *
2086     decoder, GstVideoCodecFrame * frame, gboolean dropping)
2087 {
2088   GstVideoDecoderPrivate *priv = decoder->priv;
2089   GList *l, *events = NULL;
2090
2091 #ifndef GST_DISABLE_GST_DEBUG
2092   GST_LOG_OBJECT (decoder, "n %d in %" G_GSIZE_FORMAT " out %" G_GSIZE_FORMAT,
2093       g_list_length (priv->frames),
2094       gst_adapter_available (priv->input_adapter),
2095       gst_adapter_available (priv->output_adapter));
2096 #endif
2097
2098   GST_LOG_OBJECT (decoder,
2099       "finish frame %p (#%d) sync:%d PTS:%" GST_TIME_FORMAT " DTS:%"
2100       GST_TIME_FORMAT,
2101       frame, frame->system_frame_number,
2102       GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame), GST_TIME_ARGS (frame->pts),
2103       GST_TIME_ARGS (frame->dts));
2104
2105   /* Push all pending events that arrived before this frame */
2106   for (l = priv->frames; l; l = l->next) {
2107     GstVideoCodecFrame *tmp = l->data;
2108
2109     if (tmp->events) {
2110       events = g_list_concat (events, tmp->events);
2111       tmp->events = NULL;
2112     }
2113
2114     if (tmp == frame)
2115       break;
2116   }
2117
2118   for (l = g_list_last (events); l; l = g_list_previous (l)) {
2119     GST_LOG_OBJECT (decoder, "pushing %s event", GST_EVENT_TYPE_NAME (l->data));
2120     gst_video_decoder_push_event (decoder, l->data);
2121   }
2122   g_list_free (events);
2123
2124   /* Check if the data should not be displayed. For example altref/invisible
2125    * frame in vp8. In this case we should not update the timestamps. */
2126   if (GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame))
2127     return;
2128
2129   /* If the frame is meant to be output but we don't have an output_buffer
2130    * we have a problem :) */
2131   if (G_UNLIKELY ((frame->output_buffer == NULL) && !dropping))
2132     goto no_output_buffer;
2133
2134   if (GST_CLOCK_TIME_IS_VALID (frame->pts)) {
2135     if (frame->pts != priv->base_timestamp) {
2136       GST_DEBUG_OBJECT (decoder,
2137           "sync timestamp %" GST_TIME_FORMAT " diff %" GST_TIME_FORMAT,
2138           GST_TIME_ARGS (frame->pts),
2139           GST_TIME_ARGS (frame->pts - decoder->output_segment.start));
2140       priv->base_timestamp = frame->pts;
2141       priv->base_picture_number = frame->decode_frame_number;
2142     }
2143   }
2144
2145   if (frame->duration == GST_CLOCK_TIME_NONE) {
2146     frame->duration = gst_video_decoder_get_frame_duration (decoder, frame);
2147     GST_LOG_OBJECT (decoder,
2148         "Guessing duration %" GST_TIME_FORMAT " for frame...",
2149         GST_TIME_ARGS (frame->duration));
2150   }
2151
2152   /* PTS is expected montone ascending,
2153    * so a good guess is lowest unsent DTS */
2154   {
2155     GstClockTime min_ts = GST_CLOCK_TIME_NONE;
2156     GstVideoCodecFrame *oframe = NULL;
2157     gboolean seen_none = FALSE;
2158
2159     /* some maintenance regardless */
2160     for (l = priv->frames; l; l = l->next) {
2161       GstVideoCodecFrame *tmp = l->data;
2162
2163       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
2164         seen_none = TRUE;
2165         continue;
2166       }
2167
2168       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
2169         min_ts = tmp->abidata.ABI.ts;
2170         oframe = tmp;
2171       }
2172     }
2173     /* save a ts if needed */
2174     if (oframe && oframe != frame) {
2175       oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
2176     }
2177
2178     /* and set if needed;
2179      * valid delta means we have reasonable DTS input */
2180     /* also, if we ended up reordered, means this approach is conflicting
2181      * with some sparse existing PTS, and so it does not work out */
2182     if (!priv->reordered_output &&
2183         !GST_CLOCK_TIME_IS_VALID (frame->pts) && !seen_none &&
2184         GST_CLOCK_TIME_IS_VALID (priv->pts_delta)) {
2185       frame->pts = min_ts + priv->pts_delta;
2186       GST_DEBUG_OBJECT (decoder,
2187           "no valid PTS, using oldest DTS %" GST_TIME_FORMAT,
2188           GST_TIME_ARGS (frame->pts));
2189     }
2190
2191     /* some more maintenance, ts2 holds PTS */
2192     min_ts = GST_CLOCK_TIME_NONE;
2193     seen_none = FALSE;
2194     for (l = priv->frames; l; l = l->next) {
2195       GstVideoCodecFrame *tmp = l->data;
2196
2197       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts2)) {
2198         seen_none = TRUE;
2199         continue;
2200       }
2201
2202       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts2 < min_ts) {
2203         min_ts = tmp->abidata.ABI.ts2;
2204         oframe = tmp;
2205       }
2206     }
2207     /* save a ts if needed */
2208     if (oframe && oframe != frame) {
2209       oframe->abidata.ABI.ts2 = frame->abidata.ABI.ts2;
2210     }
2211
2212     /* if we detected reordered output, then PTS are void,
2213      * however those were obtained; bogus input, subclass etc */
2214     if (priv->reordered_output && !seen_none) {
2215       GST_DEBUG_OBJECT (decoder, "invaliding PTS");
2216       frame->pts = GST_CLOCK_TIME_NONE;
2217     }
2218
2219     if (!GST_CLOCK_TIME_IS_VALID (frame->pts) && !seen_none) {
2220       frame->pts = min_ts;
2221       GST_DEBUG_OBJECT (decoder,
2222           "no valid PTS, using oldest PTS %" GST_TIME_FORMAT,
2223           GST_TIME_ARGS (frame->pts));
2224     }
2225   }
2226
2227
2228   if (frame->pts == GST_CLOCK_TIME_NONE) {
2229     /* Last ditch timestamp guess: Just add the duration to the previous
2230      * frame */
2231     if (priv->last_timestamp_out != GST_CLOCK_TIME_NONE &&
2232         frame->duration != GST_CLOCK_TIME_NONE) {
2233       frame->pts = priv->last_timestamp_out + frame->duration;
2234       GST_LOG_OBJECT (decoder,
2235           "Guessing timestamp %" GST_TIME_FORMAT " for frame...",
2236           GST_TIME_ARGS (frame->pts));
2237     }
2238   }
2239
2240   if (GST_CLOCK_TIME_IS_VALID (priv->last_timestamp_out)) {
2241     if (frame->pts < priv->last_timestamp_out) {
2242       GST_WARNING_OBJECT (decoder,
2243           "decreasing timestamp (%" GST_TIME_FORMAT " < %"
2244           GST_TIME_FORMAT ")",
2245           GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (priv->last_timestamp_out));
2246       priv->reordered_output = TRUE;
2247     }
2248   }
2249
2250   if (GST_CLOCK_TIME_IS_VALID (frame->pts))
2251     priv->last_timestamp_out = frame->pts;
2252
2253   return;
2254
2255   /* ERRORS */
2256 no_output_buffer:
2257   {
2258     GST_ERROR_OBJECT (decoder, "No buffer to output !");
2259   }
2260 }
2261
2262 static void
2263 gst_video_decoder_release_frame (GstVideoDecoder * dec,
2264     GstVideoCodecFrame * frame)
2265 {
2266   GList *link;
2267
2268   /* unref once from the list */
2269   link = g_list_find (dec->priv->frames, frame);
2270   if (link) {
2271     gst_video_codec_frame_unref (frame);
2272     dec->priv->frames = g_list_delete_link (dec->priv->frames, link);
2273   }
2274
2275   /* unref because this function takes ownership */
2276   gst_video_codec_frame_unref (frame);
2277 }
2278
2279 /**
2280  * gst_video_decoder_drop_frame:
2281  * @dec: a #GstVideoDecoder
2282  * @frame: (transfer full): the #GstVideoCodecFrame to drop
2283  *
2284  * Similar to gst_video_decoder_finish_frame(), but drops @frame in any
2285  * case and posts a QoS message with the frame's details on the bus.
2286  * In any case, the frame is considered finished and released.
2287  *
2288  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
2289  */
2290 GstFlowReturn
2291 gst_video_decoder_drop_frame (GstVideoDecoder * dec, GstVideoCodecFrame * frame)
2292 {
2293   GstClockTime stream_time, jitter, earliest_time, qostime, timestamp;
2294   GstSegment *segment;
2295   GstMessage *qos_msg;
2296   gdouble proportion;
2297
2298   GST_LOG_OBJECT (dec, "drop frame %p", frame);
2299
2300   GST_VIDEO_DECODER_STREAM_LOCK (dec);
2301
2302   gst_video_decoder_prepare_finish_frame (dec, frame, TRUE);
2303
2304   GST_DEBUG_OBJECT (dec, "dropping frame %" GST_TIME_FORMAT,
2305       GST_TIME_ARGS (frame->pts));
2306
2307   dec->priv->dropped++;
2308
2309   /* post QoS message */
2310   GST_OBJECT_LOCK (dec);
2311   proportion = dec->priv->proportion;
2312   earliest_time = dec->priv->earliest_time;
2313   GST_OBJECT_UNLOCK (dec);
2314
2315   timestamp = frame->pts;
2316   segment = &dec->output_segment;
2317   stream_time =
2318       gst_segment_to_stream_time (segment, GST_FORMAT_TIME, timestamp);
2319   qostime = gst_segment_to_running_time (segment, GST_FORMAT_TIME, timestamp);
2320   jitter = GST_CLOCK_DIFF (qostime, earliest_time);
2321   qos_msg =
2322       gst_message_new_qos (GST_OBJECT_CAST (dec), FALSE, qostime, stream_time,
2323       timestamp, GST_CLOCK_TIME_NONE);
2324   gst_message_set_qos_values (qos_msg, jitter, proportion, 1000000);
2325   gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS,
2326       dec->priv->processed, dec->priv->dropped);
2327   gst_element_post_message (GST_ELEMENT_CAST (dec), qos_msg);
2328
2329   /* now free the frame */
2330   gst_video_decoder_release_frame (dec, frame);
2331
2332   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
2333
2334   return GST_FLOW_OK;
2335 }
2336
2337 /**
2338  * gst_video_decoder_finish_frame:
2339  * @decoder: a #GstVideoDecoder
2340  * @frame: (transfer full): a decoded #GstVideoCodecFrame
2341  *
2342  * @frame should have a valid decoded data buffer, whose metadata fields
2343  * are then appropriately set according to frame data and pushed downstream.
2344  * If no output data is provided, @frame is considered skipped.
2345  * In any case, the frame is considered finished and released.
2346  *
2347  * After calling this function the output buffer of the frame is to be
2348  * considered read-only. This function will also change the metadata
2349  * of the buffer.
2350  *
2351  * Returns: a #GstFlowReturn resulting from sending data downstream
2352  */
2353 GstFlowReturn
2354 gst_video_decoder_finish_frame (GstVideoDecoder * decoder,
2355     GstVideoCodecFrame * frame)
2356 {
2357   GstFlowReturn ret = GST_FLOW_OK;
2358   GstVideoDecoderPrivate *priv = decoder->priv;
2359   GstBuffer *output_buffer;
2360
2361   GST_LOG_OBJECT (decoder, "finish frame %p", frame);
2362
2363   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2364
2365   if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
2366               && gst_pad_check_reconfigure (decoder->srcpad))))
2367     gst_video_decoder_negotiate (decoder);
2368
2369   gst_video_decoder_prepare_finish_frame (decoder, frame, FALSE);
2370   priv->processed++;
2371
2372   if (priv->tags && priv->tags_changed) {
2373     gst_video_decoder_push_event (decoder,
2374         gst_event_new_tag (gst_tag_list_ref (priv->tags)));
2375     priv->tags_changed = FALSE;
2376   }
2377
2378   /* no buffer data means this frame is skipped */
2379   if (!frame->output_buffer || GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame)) {
2380     GST_DEBUG_OBJECT (decoder, "skipping frame %" GST_TIME_FORMAT,
2381         GST_TIME_ARGS (frame->pts));
2382     goto done;
2383   }
2384
2385   output_buffer = frame->output_buffer;
2386
2387   GST_BUFFER_FLAG_UNSET (output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2388
2389   /* set PTS and DTS to both the PTS for decoded frames */
2390   GST_BUFFER_PTS (output_buffer) = frame->pts;
2391   GST_BUFFER_DTS (output_buffer) = frame->pts;
2392   GST_BUFFER_DURATION (output_buffer) = frame->duration;
2393
2394   GST_BUFFER_OFFSET (output_buffer) = GST_BUFFER_OFFSET_NONE;
2395   GST_BUFFER_OFFSET_END (output_buffer) = GST_BUFFER_OFFSET_NONE;
2396
2397   if (priv->discont) {
2398     GST_BUFFER_FLAG_SET (output_buffer, GST_BUFFER_FLAG_DISCONT);
2399     priv->discont = FALSE;
2400   }
2401
2402   /* Get an additional ref to the buffer, which is going to be pushed
2403    * downstream, the original ref is owned by the frame
2404    *
2405    * FIXME: clip_and_push_buf() changes buffer metadata but the buffer
2406    * might have a refcount > 1 */
2407   output_buffer = gst_buffer_ref (output_buffer);
2408   if (decoder->output_segment.rate < 0.0) {
2409     GST_LOG_OBJECT (decoder, "queued frame");
2410     priv->output_queued = g_list_prepend (priv->output_queued, output_buffer);
2411   } else {
2412     ret = gst_video_decoder_clip_and_push_buf (decoder, output_buffer);
2413   }
2414
2415 done:
2416   gst_video_decoder_release_frame (decoder, frame);
2417   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2418   return ret;
2419 }
2420
2421
2422 /* With stream lock, takes the frame reference */
2423 static GstFlowReturn
2424 gst_video_decoder_clip_and_push_buf (GstVideoDecoder * decoder, GstBuffer * buf)
2425 {
2426   GstFlowReturn ret = GST_FLOW_OK;
2427   GstVideoDecoderPrivate *priv = decoder->priv;
2428   guint64 start, stop;
2429   guint64 cstart, cstop;
2430   GstSegment *segment;
2431   GstClockTime duration;
2432
2433   /* Check for clipping */
2434   start = GST_BUFFER_PTS (buf);
2435   duration = GST_BUFFER_DURATION (buf);
2436
2437   stop = GST_CLOCK_TIME_NONE;
2438
2439   if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (duration)) {
2440     stop = start + duration;
2441   }
2442
2443   segment = &decoder->output_segment;
2444   if (gst_segment_clip (segment, GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
2445
2446     GST_BUFFER_PTS (buf) = cstart;
2447
2448     if (stop != GST_CLOCK_TIME_NONE)
2449       GST_BUFFER_DURATION (buf) = cstop - cstart;
2450
2451     GST_LOG_OBJECT (decoder,
2452         "accepting buffer inside segment: %" GST_TIME_FORMAT " %"
2453         GST_TIME_FORMAT " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
2454         " time %" GST_TIME_FORMAT,
2455         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2456         GST_TIME_ARGS (GST_BUFFER_PTS (buf) +
2457             GST_BUFFER_DURATION (buf)),
2458         GST_TIME_ARGS (segment->start), GST_TIME_ARGS (segment->stop),
2459         GST_TIME_ARGS (segment->time));
2460   } else {
2461     GST_LOG_OBJECT (decoder,
2462         "dropping buffer outside segment: %" GST_TIME_FORMAT
2463         " %" GST_TIME_FORMAT
2464         " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
2465         " time %" GST_TIME_FORMAT,
2466         GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
2467         GST_TIME_ARGS (segment->start),
2468         GST_TIME_ARGS (segment->stop), GST_TIME_ARGS (segment->time));
2469     gst_buffer_unref (buf);
2470     goto done;
2471   }
2472
2473   /* update rate estimate */
2474   priv->bytes_out += gst_buffer_get_size (buf);
2475   if (GST_CLOCK_TIME_IS_VALID (duration)) {
2476     priv->time += duration;
2477   } else {
2478     /* FIXME : Use difference between current and previous outgoing
2479      * timestamp, and relate to difference between current and previous
2480      * bytes */
2481     /* better none than nothing valid */
2482     priv->time = GST_CLOCK_TIME_NONE;
2483   }
2484
2485   GST_DEBUG_OBJECT (decoder, "pushing buffer %p of size %" G_GSIZE_FORMAT ", "
2486       "PTS %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
2487       gst_buffer_get_size (buf),
2488       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2489       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2490
2491   /* we got data, so note things are looking up again, reduce
2492    * the error count, if there is one */
2493   if (G_UNLIKELY (priv->error_count))
2494     priv->error_count = 0;
2495
2496   ret = gst_pad_push (decoder->srcpad, buf);
2497
2498 done:
2499   return ret;
2500 }
2501
2502 /**
2503  * gst_video_decoder_add_to_frame:
2504  * @decoder: a #GstVideoDecoder
2505  * @n_bytes: the number of bytes to add
2506  *
2507  * Removes next @n_bytes of input data and adds it to currently parsed frame.
2508  */
2509 void
2510 gst_video_decoder_add_to_frame (GstVideoDecoder * decoder, int n_bytes)
2511 {
2512   GstVideoDecoderPrivate *priv = decoder->priv;
2513   GstBuffer *buf;
2514
2515   GST_LOG_OBJECT (decoder, "add %d bytes to frame", n_bytes);
2516
2517   if (n_bytes == 0)
2518     return;
2519
2520   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2521   if (gst_adapter_available (priv->output_adapter) == 0) {
2522     priv->frame_offset =
2523         priv->input_offset - gst_adapter_available (priv->input_adapter);
2524   }
2525   buf = gst_adapter_take_buffer (priv->input_adapter, n_bytes);
2526
2527   gst_adapter_push (priv->output_adapter, buf);
2528   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2529 }
2530
2531 static guint64
2532 gst_video_decoder_get_frame_duration (GstVideoDecoder * decoder,
2533     GstVideoCodecFrame * frame)
2534 {
2535   GstVideoCodecState *state = decoder->priv->output_state;
2536
2537   /* it's possible that we don't have a state yet when we are dropping the
2538    * initial buffers */
2539   if (state == NULL)
2540     return GST_CLOCK_TIME_NONE;
2541
2542   if (state->info.fps_d == 0 || state->info.fps_n == 0) {
2543     return GST_CLOCK_TIME_NONE;
2544   }
2545
2546   /* FIXME: For interlaced frames this needs to take into account
2547    * the number of valid fields in the frame
2548    */
2549
2550   return gst_util_uint64_scale (GST_SECOND, state->info.fps_d,
2551       state->info.fps_n);
2552 }
2553
2554 /**
2555  * gst_video_decoder_have_frame:
2556  * @decoder: a #GstVideoDecoder
2557  *
2558  * Gathers all data collected for currently parsed frame, gathers corresponding
2559  * metadata and passes it along for further processing, i.e. @handle_frame.
2560  *
2561  * Returns: a #GstFlowReturn
2562  */
2563 GstFlowReturn
2564 gst_video_decoder_have_frame (GstVideoDecoder * decoder)
2565 {
2566   GstVideoDecoderPrivate *priv = decoder->priv;
2567   GstBuffer *buffer;
2568   int n_available;
2569   GstClockTime pts, dts, duration;
2570   GstFlowReturn ret = GST_FLOW_OK;
2571
2572   GST_LOG_OBJECT (decoder, "have_frame");
2573
2574   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2575
2576   n_available = gst_adapter_available (priv->output_adapter);
2577   if (n_available) {
2578     buffer = gst_adapter_take_buffer (priv->output_adapter, n_available);
2579   } else {
2580     buffer = gst_buffer_new_and_alloc (0);
2581   }
2582
2583   priv->current_frame->input_buffer = buffer;
2584
2585   gst_video_decoder_get_timestamp_at_offset (decoder,
2586       priv->frame_offset, &pts, &dts, &duration);
2587
2588   GST_BUFFER_PTS (buffer) = pts;
2589   GST_BUFFER_DTS (buffer) = dts;
2590   GST_BUFFER_DURATION (buffer) = duration;
2591
2592   GST_LOG_OBJECT (decoder, "collected frame size %d, "
2593       "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
2594       GST_TIME_FORMAT, n_available, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts),
2595       GST_TIME_ARGS (duration));
2596
2597   /* In reverse playback, just capture and queue frames for later processing */
2598   if (decoder->output_segment.rate < 0.0) {
2599     priv->parse_gather =
2600         g_list_prepend (priv->parse_gather, priv->current_frame);
2601   } else {
2602     /* Otherwise, decode the frame, which gives away our ref */
2603     ret = gst_video_decoder_decode_frame (decoder, priv->current_frame);
2604   }
2605   /* Current frame is gone now, either way */
2606   priv->current_frame = NULL;
2607
2608   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2609
2610   return ret;
2611 }
2612
2613 /* Pass the frame in priv->current_frame through the
2614  * handle_frame() callback for decoding and passing to gvd_finish_frame(), 
2615  * or dropping by passing to gvd_drop_frame() */
2616 static GstFlowReturn
2617 gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
2618     GstVideoCodecFrame * frame)
2619 {
2620   GstVideoDecoderPrivate *priv = decoder->priv;
2621   GstVideoDecoderClass *decoder_class;
2622   GstFlowReturn ret = GST_FLOW_OK;
2623
2624   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
2625
2626   /* FIXME : This should only have to be checked once (either the subclass has an 
2627    * implementation, or it doesn't) */
2628   g_return_val_if_fail (decoder_class->handle_frame != NULL, GST_FLOW_ERROR);
2629
2630   frame->distance_from_sync = priv->distance_from_sync;
2631   priv->distance_from_sync++;
2632   frame->pts = GST_BUFFER_PTS (frame->input_buffer);
2633   frame->dts = GST_BUFFER_DTS (frame->input_buffer);
2634   frame->duration = GST_BUFFER_DURATION (frame->input_buffer);
2635
2636   /* For keyframes, PTS = DTS */
2637   /* FIXME upstream can be quite wrong about the keyframe aspect,
2638    * so we could be going off here as well,
2639    * maybe let subclass decide if it really is/was a keyframe */
2640   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
2641     if (!GST_CLOCK_TIME_IS_VALID (frame->pts)) {
2642       frame->pts = frame->dts;
2643     } else if (GST_CLOCK_TIME_IS_VALID (frame->dts)) {
2644       /* just in case they are not equal as might ideally be,
2645        * e.g. quicktime has a (positive) delta approach */
2646       priv->pts_delta = frame->pts - frame->dts;
2647       GST_DEBUG_OBJECT (decoder, "PTS delta %d ms",
2648           (gint) (priv->pts_delta / GST_MSECOND));
2649     }
2650   }
2651
2652   frame->abidata.ABI.ts = frame->dts;
2653   frame->abidata.ABI.ts2 = frame->pts;
2654
2655   GST_LOG_OBJECT (decoder, "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT,
2656       GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->dts));
2657   GST_LOG_OBJECT (decoder, "dist %d", frame->distance_from_sync);
2658
2659   gst_video_codec_frame_ref (frame);
2660   priv->frames = g_list_append (priv->frames, frame);
2661
2662   if (g_list_length (priv->frames) > 10) {
2663     GST_WARNING_OBJECT (decoder, "decoder frame list getting long: %d frames,"
2664         "possible internal leaking?", g_list_length (priv->frames));
2665   }
2666
2667   frame->deadline =
2668       gst_segment_to_running_time (&decoder->input_segment, GST_FORMAT_TIME,
2669       frame->pts);
2670
2671   /* do something with frame */
2672   ret = decoder_class->handle_frame (decoder, frame);
2673   if (ret != GST_FLOW_OK)
2674     GST_DEBUG_OBJECT (decoder, "flow error %s", gst_flow_get_name (ret));
2675
2676   /* the frame has either been added to parse_gather or sent to
2677      handle frame so there is no need to unref it */
2678   return ret;
2679 }
2680
2681
2682 /**
2683  * gst_video_decoder_get_output_state:
2684  * @decoder: a #GstVideoDecoder
2685  *
2686  * Get the #GstVideoCodecState currently describing the output stream.
2687  *
2688  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
2689  */
2690 GstVideoCodecState *
2691 gst_video_decoder_get_output_state (GstVideoDecoder * decoder)
2692 {
2693   GstVideoCodecState *state = NULL;
2694
2695   GST_OBJECT_LOCK (decoder);
2696   if (decoder->priv->output_state)
2697     state = gst_video_codec_state_ref (decoder->priv->output_state);
2698   GST_OBJECT_UNLOCK (decoder);
2699
2700   return state;
2701 }
2702
2703 /**
2704  * gst_video_decoder_set_output_state:
2705  * @decoder: a #GstVideoDecoder
2706  * @fmt: a #GstVideoFormat
2707  * @width: The width in pixels
2708  * @height: The height in pixels
2709  * @reference: (allow-none) (transfer none): An optional reference #GstVideoCodecState
2710  *
2711  * Creates a new #GstVideoCodecState with the specified @fmt, @width and @height
2712  * as the output state for the decoder.
2713  * Any previously set output state on @decoder will be replaced by the newly
2714  * created one.
2715  *
2716  * If the subclass wishes to copy over existing fields (like pixel aspec ratio,
2717  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
2718  * @reference.
2719  *
2720  * If the subclass wishes to override some fields from the output state (like
2721  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
2722  *
2723  * The new output state will only take effect (set on pads and buffers) starting
2724  * from the next call to #gst_video_decoder_finish_frame().
2725  *
2726  * Returns: (transfer full): the newly configured output state.
2727  */
2728 GstVideoCodecState *
2729 gst_video_decoder_set_output_state (GstVideoDecoder * decoder,
2730     GstVideoFormat fmt, guint width, guint height,
2731     GstVideoCodecState * reference)
2732 {
2733   GstVideoDecoderPrivate *priv = decoder->priv;
2734   GstVideoCodecState *state;
2735
2736   GST_DEBUG_OBJECT (decoder, "fmt:%d, width:%d, height:%d, reference:%p",
2737       fmt, width, height, reference);
2738
2739   /* Create the new output state */
2740   state = _new_output_state (fmt, width, height, reference);
2741
2742   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2743
2744   GST_OBJECT_LOCK (decoder);
2745   /* Replace existing output state by new one */
2746   if (priv->output_state)
2747     gst_video_codec_state_unref (priv->output_state);
2748   priv->output_state = gst_video_codec_state_ref (state);
2749
2750   if (priv->output_state != NULL && priv->output_state->info.fps_n > 0) {
2751     priv->qos_frame_duration =
2752         gst_util_uint64_scale (GST_SECOND, priv->output_state->info.fps_d,
2753         priv->output_state->info.fps_n);
2754   } else {
2755     priv->qos_frame_duration = 0;
2756   }
2757   priv->output_state_changed = TRUE;
2758   GST_OBJECT_UNLOCK (decoder);
2759
2760   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2761
2762   return state;
2763 }
2764
2765
2766 /**
2767  * gst_video_decoder_get_oldest_frame:
2768  * @decoder: a #GstVideoDecoder
2769  *
2770  * Get the oldest pending unfinished #GstVideoCodecFrame
2771  *
2772  * Returns: (transfer full): oldest pending unfinished #GstVideoCodecFrame.
2773  */
2774 GstVideoCodecFrame *
2775 gst_video_decoder_get_oldest_frame (GstVideoDecoder * decoder)
2776 {
2777   GstVideoCodecFrame *frame = NULL;
2778
2779   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2780   if (decoder->priv->frames)
2781     frame = gst_video_codec_frame_ref (decoder->priv->frames->data);
2782   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2783
2784   return (GstVideoCodecFrame *) frame;
2785 }
2786
2787 /**
2788  * gst_video_decoder_get_frame:
2789  * @decoder: a #GstVideoDecoder
2790  * @frame_number: system_frame_number of a frame
2791  *
2792  * Get a pending unfinished #GstVideoCodecFrame
2793  * 
2794  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
2795  */
2796 GstVideoCodecFrame *
2797 gst_video_decoder_get_frame (GstVideoDecoder * decoder, int frame_number)
2798 {
2799   GList *g;
2800   GstVideoCodecFrame *frame = NULL;
2801
2802   GST_DEBUG_OBJECT (decoder, "frame_number : %d", frame_number);
2803
2804   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2805   for (g = decoder->priv->frames; g; g = g->next) {
2806     GstVideoCodecFrame *tmp = g->data;
2807
2808     if (tmp->system_frame_number == frame_number) {
2809       frame = gst_video_codec_frame_ref (tmp);
2810       break;
2811     }
2812   }
2813   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2814
2815   return frame;
2816 }
2817
2818 /**
2819  * gst_video_decoder_get_frames:
2820  * @decoder: a #GstVideoDecoder
2821  *
2822  * Get all pending unfinished #GstVideoCodecFrame
2823  * 
2824  * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
2825  */
2826 GList *
2827 gst_video_decoder_get_frames (GstVideoDecoder * decoder)
2828 {
2829   GList *frames;
2830
2831   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2832   frames = g_list_copy (decoder->priv->frames);
2833   g_list_foreach (frames, (GFunc) gst_video_codec_frame_ref, NULL);
2834   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2835
2836   return frames;
2837 }
2838
2839 static gboolean
2840 gst_video_decoder_decide_allocation_default (GstVideoDecoder * decoder,
2841     GstQuery * query)
2842 {
2843   GstCaps *outcaps;
2844   GstBufferPool *pool = NULL;
2845   guint size, min, max;
2846   GstAllocator *allocator = NULL;
2847   GstAllocationParams params;
2848   GstStructure *config;
2849   gboolean update_pool, update_allocator;
2850   GstVideoInfo vinfo;
2851
2852   gst_query_parse_allocation (query, &outcaps, NULL);
2853   gst_video_info_init (&vinfo);
2854   gst_video_info_from_caps (&vinfo, outcaps);
2855
2856   /* we got configuration from our peer or the decide_allocation method,
2857    * parse them */
2858   if (gst_query_get_n_allocation_params (query) > 0) {
2859     /* try the allocator */
2860     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2861     update_allocator = TRUE;
2862   } else {
2863     allocator = NULL;
2864     gst_allocation_params_init (&params);
2865     update_allocator = FALSE;
2866   }
2867
2868   if (gst_query_get_n_allocation_pools (query) > 0) {
2869     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
2870     size = MAX (size, vinfo.size);
2871     update_pool = TRUE;
2872   } else {
2873     pool = NULL;
2874     size = vinfo.size;
2875     min = max = 0;
2876
2877     update_pool = FALSE;
2878   }
2879
2880   if (pool == NULL) {
2881     /* no pool, we can make our own */
2882     GST_DEBUG_OBJECT (decoder, "no pool, making new pool");
2883     pool = gst_video_buffer_pool_new ();
2884   }
2885
2886   /* now configure */
2887   config = gst_buffer_pool_get_config (pool);
2888   gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
2889   gst_buffer_pool_config_set_allocator (config, allocator, &params);
2890   gst_buffer_pool_set_config (pool, config);
2891
2892   if (update_allocator)
2893     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
2894   else
2895     gst_query_add_allocation_param (query, allocator, &params);
2896   if (allocator)
2897     gst_object_unref (allocator);
2898
2899   if (update_pool)
2900     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
2901   else
2902     gst_query_add_allocation_pool (query, pool, size, min, max);
2903
2904   if (pool)
2905     gst_object_unref (pool);
2906
2907   return TRUE;
2908 }
2909
2910 static gboolean
2911 gst_video_decoder_propose_allocation_default (GstVideoDecoder * decoder,
2912     GstQuery * query)
2913 {
2914   return TRUE;
2915 }
2916
2917 static gboolean
2918 gst_video_decoder_negotiate_default (GstVideoDecoder * decoder)
2919 {
2920   GstVideoCodecState *state = decoder->priv->output_state;
2921   GstVideoDecoderClass *klass;
2922   GstQuery *query = NULL;
2923   GstBufferPool *pool = NULL;
2924   GstAllocator *allocator;
2925   GstAllocationParams params;
2926   gboolean ret = TRUE;
2927
2928   g_return_val_if_fail (GST_VIDEO_INFO_WIDTH (&state->info) != 0, FALSE);
2929   g_return_val_if_fail (GST_VIDEO_INFO_HEIGHT (&state->info) != 0, FALSE);
2930
2931   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
2932
2933   GST_DEBUG_OBJECT (decoder, "output_state par %d/%d fps %d/%d",
2934       state->info.par_n, state->info.par_d,
2935       state->info.fps_n, state->info.fps_d);
2936
2937   if (state->caps == NULL)
2938     state->caps = gst_video_info_to_caps (&state->info);
2939
2940   GST_DEBUG_OBJECT (decoder, "setting caps %" GST_PTR_FORMAT, state->caps);
2941
2942   ret = gst_pad_set_caps (decoder->srcpad, state->caps);
2943   if (!ret)
2944     goto done;
2945   decoder->priv->output_state_changed = FALSE;
2946
2947   /* Negotiate pool */
2948   query = gst_query_new_allocation (state->caps, TRUE);
2949
2950   if (!gst_pad_peer_query (decoder->srcpad, query)) {
2951     GST_DEBUG_OBJECT (decoder, "didn't get downstream ALLOCATION hints");
2952   }
2953
2954   g_assert (klass->decide_allocation != NULL);
2955   ret = klass->decide_allocation (decoder, query);
2956
2957   GST_DEBUG_OBJECT (decoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
2958       query);
2959
2960   if (!ret)
2961     goto no_decide_allocation;
2962
2963   /* we got configuration from our peer or the decide_allocation method,
2964    * parse them */
2965   if (gst_query_get_n_allocation_params (query) > 0) {
2966     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2967   } else {
2968     allocator = NULL;
2969     gst_allocation_params_init (&params);
2970   }
2971
2972   if (gst_query_get_n_allocation_pools (query) > 0)
2973     gst_query_parse_nth_allocation_pool (query, 0, &pool, NULL, NULL, NULL);
2974   if (!pool) {
2975     if (allocator)
2976       gst_object_unref (allocator);
2977     ret = FALSE;
2978     goto no_decide_allocation;
2979   }
2980
2981   if (decoder->priv->allocator)
2982     gst_object_unref (decoder->priv->allocator);
2983   decoder->priv->allocator = allocator;
2984   decoder->priv->params = params;
2985
2986   if (decoder->priv->pool) {
2987     gst_buffer_pool_set_active (decoder->priv->pool, FALSE);
2988     gst_object_unref (decoder->priv->pool);
2989   }
2990   decoder->priv->pool = pool;
2991
2992   /* and activate */
2993   gst_buffer_pool_set_active (pool, TRUE);
2994
2995 done:
2996   if (query)
2997     gst_query_unref (query);
2998
2999   return ret;
3000
3001   /* Errors */
3002 no_decide_allocation:
3003   {
3004     GST_WARNING_OBJECT (decoder, "Subclass failed to decide allocation");
3005     goto done;
3006   }
3007 }
3008
3009 /**
3010  * gst_video_decoder_negotiate:
3011  * @decoder: a #GstVideoDecoder
3012  *
3013  * Negotiate with downstreame elements to currently configured #GstVideoCodecState.
3014  *
3015  * Returns: #TRUE if the negotiation succeeded, else #FALSE.
3016  */
3017 gboolean
3018 gst_video_decoder_negotiate (GstVideoDecoder * decoder)
3019 {
3020   GstVideoDecoderClass *klass;
3021   gboolean ret = TRUE;
3022
3023   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), FALSE);
3024
3025   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
3026
3027   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3028   if (klass->negotiate)
3029     ret = klass->negotiate (decoder);
3030   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3031
3032   return ret;
3033 }
3034
3035 /**
3036  * gst_video_decoder_allocate_output_buffer:
3037  * @decoder: a #GstVideoDecoder
3038  *
3039  * Helper function that allocates a buffer to hold a video frame for @decoder's
3040  * current #GstVideoCodecState.
3041  *
3042  * You should use gst_video_decoder_allocate_output_frame() instead of this
3043  * function, if possible at all.
3044  *
3045  * Returns: (transfer full): allocated buffer, or NULL if no buffer could be
3046  *     allocated (e.g. when downstream is flushing or shutting down)
3047  */
3048 GstBuffer *
3049 gst_video_decoder_allocate_output_buffer (GstVideoDecoder * decoder)
3050 {
3051   GstFlowReturn flow;
3052   GstBuffer *buffer;
3053
3054   GST_DEBUG ("alloc src buffer");
3055
3056   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3057   if (G_UNLIKELY (decoder->priv->output_state_changed
3058           || (decoder->priv->output_state
3059               && gst_pad_check_reconfigure (decoder->srcpad))))
3060     gst_video_decoder_negotiate (decoder);
3061
3062   flow = gst_buffer_pool_acquire_buffer (decoder->priv->pool, &buffer, NULL);
3063
3064   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3065
3066   if (flow != GST_FLOW_OK) {
3067     GST_INFO_OBJECT (decoder, "couldn't allocate output buffer, flow %s",
3068         gst_flow_get_name (flow));
3069     buffer = NULL;
3070   }
3071
3072   return buffer;
3073 }
3074
3075 /**
3076  * gst_video_decoder_allocate_output_frame:
3077  * @decoder: a #GstVideoDecoder
3078  * @frame: a #GstVideoCodecFrame
3079  *
3080  * Helper function that allocates a buffer to hold a video frame for @decoder's
3081  * current #GstVideoCodecState.  Subclass should already have configured video
3082  * state and set src pad caps.
3083  *
3084  * The buffer allocated here is owned by the frame and you should only
3085  * keep references to the frame, not the buffer.
3086  *
3087  * Returns: %GST_FLOW_OK if an output buffer could be allocated
3088  */
3089 GstFlowReturn
3090 gst_video_decoder_allocate_output_frame (GstVideoDecoder *
3091     decoder, GstVideoCodecFrame * frame)
3092 {
3093   GstFlowReturn flow_ret;
3094   GstVideoCodecState *state;
3095   int num_bytes;
3096
3097   g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
3098
3099   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3100
3101   state = decoder->priv->output_state;
3102   if (state == NULL) {
3103     g_warning ("Output state should be set before allocating frame");
3104     goto error;
3105   }
3106   num_bytes = GST_VIDEO_INFO_SIZE (&state->info);
3107   if (num_bytes == 0) {
3108     g_warning ("Frame size should not be 0");
3109     goto error;
3110   }
3111
3112   if (G_UNLIKELY (decoder->priv->output_state_changed
3113           || (decoder->priv->output_state
3114               && gst_pad_check_reconfigure (decoder->srcpad))))
3115     gst_video_decoder_negotiate (decoder);
3116
3117   GST_LOG_OBJECT (decoder, "alloc buffer size %d", num_bytes);
3118
3119   flow_ret = gst_buffer_pool_acquire_buffer (decoder->priv->pool,
3120       &frame->output_buffer, NULL);
3121
3122   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3123
3124   return flow_ret;
3125
3126 error:
3127   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3128   return GST_FLOW_ERROR;
3129 }
3130
3131 /**
3132  * gst_video_decoder_get_max_decode_time:
3133  * @decoder: a #GstVideoDecoder
3134  * @frame: a #GstVideoCodecFrame
3135  *
3136  * Determines maximum possible decoding time for @frame that will
3137  * allow it to decode and arrive in time (as determined by QoS events).
3138  * In particular, a negative result means decoding in time is no longer possible
3139  * and should therefore occur as soon/skippy as possible.
3140  *
3141  * Returns: max decoding time.
3142  */
3143 GstClockTimeDiff
3144 gst_video_decoder_get_max_decode_time (GstVideoDecoder *
3145     decoder, GstVideoCodecFrame * frame)
3146 {
3147   GstClockTimeDiff deadline;
3148   GstClockTime earliest_time;
3149
3150   GST_OBJECT_LOCK (decoder);
3151   earliest_time = decoder->priv->earliest_time;
3152   if (GST_CLOCK_TIME_IS_VALID (earliest_time)
3153       && GST_CLOCK_TIME_IS_VALID (frame->deadline))
3154     deadline = GST_CLOCK_DIFF (earliest_time, frame->deadline);
3155   else
3156     deadline = G_MAXINT64;
3157
3158   GST_LOG_OBJECT (decoder, "earliest %" GST_TIME_FORMAT
3159       ", frame deadline %" GST_TIME_FORMAT ", deadline %" GST_TIME_FORMAT,
3160       GST_TIME_ARGS (earliest_time), GST_TIME_ARGS (frame->deadline),
3161       GST_TIME_ARGS (deadline));
3162
3163   GST_OBJECT_UNLOCK (decoder);
3164
3165   return deadline;
3166 }
3167
3168 /**
3169  * gst_video_decoder_get_qos_proportion:
3170  * @decoder: a #GstVideoDecoder
3171  *     current QoS proportion, or %NULL
3172  *
3173  * Returns: The current QoS proportion.
3174  *
3175  * Since: 1.0.3
3176  */
3177 gdouble
3178 gst_video_decoder_get_qos_proportion (GstVideoDecoder * decoder)
3179 {
3180   gdouble proportion;
3181
3182   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), 1.0);
3183
3184   GST_OBJECT_LOCK (decoder);
3185   proportion = decoder->priv->proportion;
3186   GST_OBJECT_UNLOCK (decoder);
3187
3188   return proportion;
3189 }
3190
3191 GstFlowReturn
3192 _gst_video_decoder_error (GstVideoDecoder * dec, gint weight,
3193     GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file,
3194     const gchar * function, gint line)
3195 {
3196   if (txt)
3197     GST_WARNING_OBJECT (dec, "error: %s", txt);
3198   if (dbg)
3199     GST_WARNING_OBJECT (dec, "error: %s", dbg);
3200   dec->priv->error_count += weight;
3201   dec->priv->discont = TRUE;
3202   if (dec->priv->max_errors < dec->priv->error_count) {
3203     gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR,
3204         domain, code, txt, dbg, file, function, line);
3205     return GST_FLOW_ERROR;
3206   } else {
3207     g_free (txt);
3208     g_free (dbg);
3209     return GST_FLOW_OK;
3210   }
3211 }
3212
3213 /**
3214  * gst_video_decoder_set_max_errors:
3215  * @dec: a #GstVideoDecoder
3216  * @num: max tolerated errors
3217  *
3218  * Sets numbers of tolerated decoder errors, where a tolerated one is then only
3219  * warned about, but more than tolerated will lead to fatal error.  Default
3220  * is set to GST_VIDEO_DECODER_MAX_ERRORS.
3221  */
3222 void
3223 gst_video_decoder_set_max_errors (GstVideoDecoder * dec, gint num)
3224 {
3225   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
3226
3227   dec->priv->max_errors = num;
3228 }
3229
3230 /**
3231  * gst_video_decoder_get_max_errors:
3232  * @dec: a #GstVideoDecoder
3233  *
3234  * Returns: currently configured decoder tolerated error count.
3235  */
3236 gint
3237 gst_video_decoder_get_max_errors (GstVideoDecoder * dec)
3238 {
3239   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
3240
3241   return dec->priv->max_errors;
3242 }
3243
3244 /**
3245  * gst_video_decoder_set_packetized:
3246  * @decoder: a #GstVideoDecoder
3247  * @packetized: whether the input data should be considered as packetized.
3248  *
3249  * Allows baseclass to consider input data as packetized or not. If the
3250  * input is packetized, then the @parse method will not be called.
3251  */
3252 void
3253 gst_video_decoder_set_packetized (GstVideoDecoder * decoder,
3254     gboolean packetized)
3255 {
3256   decoder->priv->packetized = packetized;
3257 }
3258
3259 /**
3260  * gst_video_decoder_get_packetized:
3261  * @decoder: a #GstVideoDecoder
3262  *
3263  * Queries whether input data is considered packetized or not by the
3264  * base class.
3265  *
3266  * Returns: TRUE if input data is considered packetized.
3267  */
3268 gboolean
3269 gst_video_decoder_get_packetized (GstVideoDecoder * decoder)
3270 {
3271   return decoder->priv->packetized;
3272 }
3273
3274 /**
3275  * gst_video_decoder_set_estimate_rate:
3276  * @dec: a #GstVideoDecoder
3277  * @enabled: whether to enable byte to time conversion
3278  *
3279  * Allows baseclass to perform byte to time estimated conversion.
3280  */
3281 void
3282 gst_video_decoder_set_estimate_rate (GstVideoDecoder * dec, gboolean enabled)
3283 {
3284   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
3285
3286   dec->priv->do_estimate_rate = enabled;
3287 }
3288
3289 /**
3290  * gst_video_decoder_get_estimate_rate:
3291  * @dec: a #GstVideoDecoder
3292  *
3293  * Returns: currently configured byte to time conversion setting
3294  */
3295 gboolean
3296 gst_video_decoder_get_estimate_rate (GstVideoDecoder * dec)
3297 {
3298   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
3299
3300   return dec->priv->do_estimate_rate;
3301 }
3302
3303 /**
3304  * gst_video_decoder_set_latency:
3305  * @decoder: a #GstVideoDecoder
3306  * @min_latency: minimum latency
3307  * @max_latency: maximum latency
3308  *
3309  * Lets #GstVideoDecoder sub-classes tell the baseclass what the decoder
3310  * latency is. Will also post a LATENCY message on the bus so the pipeline
3311  * can reconfigure its global latency.
3312  */
3313 void
3314 gst_video_decoder_set_latency (GstVideoDecoder * decoder,
3315     GstClockTime min_latency, GstClockTime max_latency)
3316 {
3317   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
3318   g_return_if_fail (max_latency >= min_latency);
3319
3320   GST_OBJECT_LOCK (decoder);
3321   decoder->priv->min_latency = min_latency;
3322   decoder->priv->max_latency = max_latency;
3323   GST_OBJECT_UNLOCK (decoder);
3324
3325   gst_element_post_message (GST_ELEMENT_CAST (decoder),
3326       gst_message_new_latency (GST_OBJECT_CAST (decoder)));
3327 }
3328
3329 /**
3330  * gst_video_decoder_get_latency:
3331  * @decoder: a #GstVideoDecoder
3332  * @min_latency: (out) (allow-none): address of variable in which to store the
3333  *     configured minimum latency, or %NULL
3334  * @max_latency: (out) (allow-none): address of variable in which to store the
3335  *     configured mximum latency, or %NULL
3336  *
3337  * Query the configured decoder latency. Results will be returned via
3338  * @min_latency and @max_latency.
3339  */
3340 void
3341 gst_video_decoder_get_latency (GstVideoDecoder * decoder,
3342     GstClockTime * min_latency, GstClockTime * max_latency)
3343 {
3344   GST_OBJECT_LOCK (decoder);
3345   if (min_latency)
3346     *min_latency = decoder->priv->min_latency;
3347   if (max_latency)
3348     *max_latency = decoder->priv->max_latency;
3349   GST_OBJECT_UNLOCK (decoder);
3350 }
3351
3352 /**
3353  * gst_video_decoder_merge_tags:
3354  * @decoder: a #GstVideoDecoder
3355  * @tags: a #GstTagList to merge
3356  * @mode: the #GstTagMergeMode to use
3357  *
3358  * Adds tags to so-called pending tags, which will be processed
3359  * before pushing out data downstream.
3360  *
3361  * Note that this is provided for convenience, and the subclass is
3362  * not required to use this and can still do tag handling on its own.
3363  *
3364  * MT safe.
3365  */
3366 void
3367 gst_video_decoder_merge_tags (GstVideoDecoder * decoder,
3368     const GstTagList * tags, GstTagMergeMode mode)
3369 {
3370   GstTagList *otags;
3371
3372   g_return_if_fail (GST_IS_VIDEO_DECODER (decoder));
3373   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
3374
3375   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3376   if (tags)
3377     GST_DEBUG_OBJECT (decoder, "merging tags %" GST_PTR_FORMAT, tags);
3378   otags = decoder->priv->tags;
3379   decoder->priv->tags = gst_tag_list_merge (decoder->priv->tags, tags, mode);
3380   if (otags)
3381     gst_tag_list_unref (otags);
3382   decoder->priv->tags_changed = TRUE;
3383   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3384 }
3385
3386 /**
3387  * gst_video_decoder_get_buffer_pool:
3388  * @decoder: a #GstVideoDecoder
3389  *
3390  * Returns: (transfer full): the instance of the #GstBufferPool used
3391  * by the decoder; free it after use it
3392  */
3393 GstBufferPool *
3394 gst_video_decoder_get_buffer_pool (GstVideoDecoder * decoder)
3395 {
3396   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), NULL);
3397
3398   if (decoder->priv->pool)
3399     return gst_object_ref (decoder->priv->pool);
3400
3401   return NULL;
3402 }
3403
3404 /**
3405  * gst_video_decoder_get_allocator:
3406  * @decoder: a #GstVideoDecoder
3407  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
3408  * used
3409  * @params: (out) (allow-none) (transfer full): the
3410  * #GstAllocatorParams of @allocator
3411  *
3412  * Lets #GstVideoDecoder sub-classes to know the memory @allocator
3413  * used by the base class and its @params.
3414  *
3415  * Unref the @allocator after use it.
3416  */
3417 void
3418 gst_video_decoder_get_allocator (GstVideoDecoder * decoder,
3419     GstAllocator ** allocator, GstAllocationParams * params)
3420 {
3421   g_return_if_fail (GST_IS_VIDEO_DECODER (decoder));
3422
3423   if (allocator)
3424     *allocator = decoder->priv->allocator ?
3425         gst_object_ref (decoder->priv->allocator) : NULL;
3426
3427   if (params)
3428     *params = decoder->priv->params;
3429 }