9404508637a558ce60fb1dff82ddb6de1e7c3e50
[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., 59 Temple Place - Suite 330,
22  * Boston, MA 02111-1307, 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/gstvideopool.h>
300 #include <gst/video/gstvideometa.h>
301 #include <string.h>
302
303 GST_DEBUG_CATEGORY (videodecoder_debug);
304 #define GST_CAT_DEFAULT videodecoder_debug
305
306 #define GST_VIDEO_DECODER_GET_PRIVATE(obj)  \
307     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_VIDEO_DECODER, \
308         GstVideoDecoderPrivate))
309
310 struct _GstVideoDecoderPrivate
311 {
312   /* FIXME introduce a context ? */
313
314   GstBufferPool *pool;
315   GstAllocator *allocator;
316   GstAllocationParams params;
317
318   /* parse tracking */
319   /* input data */
320   GstAdapter *input_adapter;
321   /* assembles current frame */
322   GstAdapter *output_adapter;
323
324   /* Whether we attempt to convert newsegment from bytes to
325    * time using a bitrate estimation */
326   gboolean do_estimate_rate;
327
328   /* Whether input is considered packetized or not */
329   gboolean packetized;
330
331   /* Error handling */
332   gint max_errors;
333   gint error_count;
334
335   /* ... being tracked here;
336    * only available during parsing */
337   GstVideoCodecFrame *current_frame;
338   /* events that should apply to the current frame */
339   GList *current_frame_events;
340
341   /* relative offset of input data */
342   guint64 input_offset;
343   /* relative offset of frame */
344   guint64 frame_offset;
345   /* tracking ts and offsets */
346   GList *timestamps;
347
348   /* last outgoing ts */
349   GstClockTime last_timestamp_out;
350
351   /* reverse playback */
352   /* collect input */
353   GList *gather;
354   /* to-be-parsed */
355   GList *parse;
356   /* collected parsed frames */
357   GList *parse_gather;
358   /* frames to be handled == decoded */
359   GList *decode;
360   /* collected output - of buffer objects, not frames */
361   GList *output_queued;
362
363
364   /* base_picture_number is the picture number of the reference picture */
365   guint64 base_picture_number;
366   /* combine with base_picture_number, framerate and calcs to yield (presentation) ts */
367   GstClockTime base_timestamp;
368
369   /* FIXME : reorder_depth is never set */
370   int reorder_depth;
371   int distance_from_sync;
372
373   guint64 system_frame_number;
374   guint64 decode_frame_number;
375
376   GList *frames;                /* Protected with OBJECT_LOCK */
377   GstVideoCodecState *input_state;
378   GstVideoCodecState *output_state;
379   gboolean output_state_changed;
380
381   /* QoS properties */
382   gdouble proportion;
383   GstClockTime earliest_time;
384   gboolean discont;
385   /* qos messages: frames dropped/processed */
386   guint dropped;
387   guint processed;
388
389   /* Outgoing byte size ? */
390   gint64 bytes_out;
391   gint64 time;
392
393   gint64 min_latency;
394   gint64 max_latency;
395 };
396
397 static GstElementClass *parent_class = NULL;
398 static void gst_video_decoder_class_init (GstVideoDecoderClass * klass);
399 static void gst_video_decoder_init (GstVideoDecoder * dec,
400     GstVideoDecoderClass * klass);
401
402 static void gst_video_decoder_finalize (GObject * object);
403
404 static gboolean gst_video_decoder_setcaps (GstVideoDecoder * dec,
405     GstCaps * caps);
406 static gboolean gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
407     GstEvent * event);
408 static gboolean gst_video_decoder_src_event (GstPad * pad, GstObject * parent,
409     GstEvent * event);
410 static GstFlowReturn gst_video_decoder_chain (GstPad * pad, GstObject * parent,
411     GstBuffer * buf);
412 static gboolean gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
413     GstQuery * query);
414 static GstStateChangeReturn gst_video_decoder_change_state (GstElement *
415     element, GstStateChange transition);
416 static gboolean gst_video_decoder_src_query (GstPad * pad, GstObject * parent,
417     GstQuery * query);
418 static void gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full);
419
420 static GstFlowReturn gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
421     GstVideoCodecFrame * frame);
422
423 static void gst_video_decoder_release_frame (GstVideoDecoder * dec,
424     GstVideoCodecFrame * frame);
425 static GstClockTime gst_video_decoder_get_frame_duration (GstVideoDecoder *
426     decoder, GstVideoCodecFrame * frame);
427 static GstVideoCodecFrame *gst_video_decoder_new_frame (GstVideoDecoder *
428     decoder);
429 static GstFlowReturn gst_video_decoder_clip_and_push_buf (GstVideoDecoder *
430     decoder, GstBuffer * buf);
431 static GstFlowReturn gst_video_decoder_flush_parse (GstVideoDecoder * dec,
432     gboolean at_eos);
433
434 static void gst_video_decoder_clear_queues (GstVideoDecoder * dec);
435
436 static gboolean gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
437     GstEvent * event);
438 static gboolean gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
439     GstEvent * event);
440 static gboolean gst_video_decoder_decide_allocation_default (GstVideoDecoder *
441     decoder, GstQuery * query);
442 static gboolean gst_video_decoder_propose_allocation_default (GstVideoDecoder *
443     decoder, GstQuery * query);
444
445 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
446  * method to get to the padtemplates */
447 GType
448 gst_video_decoder_get_type (void)
449 {
450   static volatile gsize type = 0;
451
452   if (g_once_init_enter (&type)) {
453     GType _type;
454     static const GTypeInfo info = {
455       sizeof (GstVideoDecoderClass),
456       NULL,
457       NULL,
458       (GClassInitFunc) gst_video_decoder_class_init,
459       NULL,
460       NULL,
461       sizeof (GstVideoDecoder),
462       0,
463       (GInstanceInitFunc) gst_video_decoder_init,
464     };
465
466     _type = g_type_register_static (GST_TYPE_ELEMENT,
467         "GstVideoDecoder", &info, G_TYPE_FLAG_ABSTRACT);
468     g_once_init_leave (&type, _type);
469   }
470   return type;
471 }
472
473 static void
474 gst_video_decoder_class_init (GstVideoDecoderClass * klass)
475 {
476   GObjectClass *gobject_class;
477   GstElementClass *gstelement_class;
478
479   gobject_class = G_OBJECT_CLASS (klass);
480   gstelement_class = GST_ELEMENT_CLASS (klass);
481
482   GST_DEBUG_CATEGORY_INIT (videodecoder_debug, "videodecoder", 0,
483       "Base Video Decoder");
484
485   parent_class = g_type_class_peek_parent (klass);
486   g_type_class_add_private (klass, sizeof (GstVideoDecoderPrivate));
487
488   gobject_class->finalize = gst_video_decoder_finalize;
489
490   gstelement_class->change_state =
491       GST_DEBUG_FUNCPTR (gst_video_decoder_change_state);
492
493   klass->sink_event = gst_video_decoder_sink_event_default;
494   klass->src_event = gst_video_decoder_src_event_default;
495   klass->decide_allocation = gst_video_decoder_decide_allocation_default;
496   klass->propose_allocation = gst_video_decoder_propose_allocation_default;
497 }
498
499 static void
500 gst_video_decoder_init (GstVideoDecoder * decoder, GstVideoDecoderClass * klass)
501 {
502   GstPadTemplate *pad_template;
503   GstPad *pad;
504
505   GST_DEBUG_OBJECT (decoder, "gst_video_decoder_init");
506
507   decoder->priv = GST_VIDEO_DECODER_GET_PRIVATE (decoder);
508
509   pad_template =
510       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
511   g_return_if_fail (pad_template != NULL);
512
513   decoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
514
515   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_decoder_chain));
516   gst_pad_set_event_function (pad,
517       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_event));
518   gst_pad_set_query_function (pad,
519       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_query));
520   gst_element_add_pad (GST_ELEMENT (decoder), decoder->sinkpad);
521
522   pad_template =
523       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
524   g_return_if_fail (pad_template != NULL);
525
526   decoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
527
528   gst_pad_set_event_function (pad,
529       GST_DEBUG_FUNCPTR (gst_video_decoder_src_event));
530   gst_pad_set_query_function (pad,
531       GST_DEBUG_FUNCPTR (gst_video_decoder_src_query));
532   gst_pad_use_fixed_caps (pad);
533   gst_element_add_pad (GST_ELEMENT (decoder), decoder->srcpad);
534
535   gst_segment_init (&decoder->input_segment, GST_FORMAT_TIME);
536   gst_segment_init (&decoder->output_segment, GST_FORMAT_TIME);
537
538   g_rec_mutex_init (&decoder->stream_lock);
539
540   decoder->priv->input_adapter = gst_adapter_new ();
541   decoder->priv->output_adapter = gst_adapter_new ();
542   decoder->priv->packetized = TRUE;
543
544   gst_video_decoder_reset (decoder, TRUE);
545 }
546
547 static gboolean
548 gst_video_rawvideo_convert (GstVideoCodecState * state,
549     GstFormat src_format, gint64 src_value,
550     GstFormat * dest_format, gint64 * dest_value)
551 {
552   gboolean res = FALSE;
553   guint vidsize;
554   guint fps_n, fps_d;
555
556   g_return_val_if_fail (dest_format != NULL, FALSE);
557   g_return_val_if_fail (dest_value != NULL, FALSE);
558
559   if (src_format == *dest_format || src_value == 0 || src_value == -1) {
560     *dest_value = src_value;
561     return TRUE;
562   }
563
564   vidsize = GST_VIDEO_INFO_SIZE (&state->info);
565   fps_n = GST_VIDEO_INFO_FPS_N (&state->info);
566   fps_d = GST_VIDEO_INFO_FPS_D (&state->info);
567
568   if (src_format == GST_FORMAT_BYTES &&
569       *dest_format == GST_FORMAT_DEFAULT && vidsize) {
570     /* convert bytes to frames */
571     *dest_value = gst_util_uint64_scale_int (src_value, 1, vidsize);
572     res = TRUE;
573   } else if (src_format == GST_FORMAT_DEFAULT &&
574       *dest_format == GST_FORMAT_BYTES && vidsize) {
575     /* convert bytes to frames */
576     *dest_value = src_value * vidsize;
577     res = TRUE;
578   } else if (src_format == GST_FORMAT_DEFAULT &&
579       *dest_format == GST_FORMAT_TIME && fps_n) {
580     /* convert frames to time */
581     *dest_value = gst_util_uint64_scale (src_value, GST_SECOND * fps_d, fps_n);
582     res = TRUE;
583   } else if (src_format == GST_FORMAT_TIME &&
584       *dest_format == GST_FORMAT_DEFAULT && fps_d) {
585     /* convert time to frames */
586     *dest_value = gst_util_uint64_scale (src_value, fps_n, GST_SECOND * fps_d);
587     res = TRUE;
588   } else if (src_format == GST_FORMAT_TIME &&
589       *dest_format == GST_FORMAT_BYTES && fps_d && vidsize) {
590     /* convert time to frames */
591     *dest_value = gst_util_uint64_scale (src_value,
592         fps_n * vidsize, GST_SECOND * fps_d);
593     res = TRUE;
594   } else if (src_format == GST_FORMAT_BYTES &&
595       *dest_format == GST_FORMAT_TIME && fps_n && vidsize) {
596     /* convert frames to time */
597     *dest_value = gst_util_uint64_scale (src_value,
598         GST_SECOND * fps_d, fps_n * vidsize);
599     res = TRUE;
600   }
601
602   return res;
603 }
604
605 static gboolean
606 gst_video_encoded_video_convert (gint64 bytes, gint64 time,
607     GstFormat src_format, gint64 src_value, GstFormat * dest_format,
608     gint64 * dest_value)
609 {
610   gboolean res = FALSE;
611
612   g_return_val_if_fail (dest_format != NULL, FALSE);
613   g_return_val_if_fail (dest_value != NULL, FALSE);
614
615   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
616           src_value == -1)) {
617     if (dest_value)
618       *dest_value = src_value;
619     return TRUE;
620   }
621
622   if (bytes <= 0 || time <= 0) {
623     GST_DEBUG ("not enough metadata yet to convert");
624     goto exit;
625   }
626
627   switch (src_format) {
628     case GST_FORMAT_BYTES:
629       switch (*dest_format) {
630         case GST_FORMAT_TIME:
631           *dest_value = gst_util_uint64_scale (src_value, time, bytes);
632           res = TRUE;
633           break;
634         default:
635           res = FALSE;
636       }
637       break;
638     case GST_FORMAT_TIME:
639       switch (*dest_format) {
640         case GST_FORMAT_BYTES:
641           *dest_value = gst_util_uint64_scale (src_value, bytes, time);
642           res = TRUE;
643           break;
644         default:
645           res = FALSE;
646       }
647       break;
648     default:
649       GST_DEBUG ("unhandled conversion from %d to %d", src_format,
650           *dest_format);
651       res = FALSE;
652   }
653
654 exit:
655   return res;
656 }
657
658 static GstVideoCodecState *
659 _new_input_state (GstCaps * caps)
660 {
661   GstVideoCodecState *state;
662   GstStructure *structure;
663   const GValue *codec_data;
664
665   state = g_slice_new0 (GstVideoCodecState);
666   state->ref_count = 1;
667   gst_video_info_init (&state->info);
668   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
669     goto parse_fail;
670   state->caps = gst_caps_ref (caps);
671
672   structure = gst_caps_get_structure (caps, 0);
673
674   codec_data = gst_structure_get_value (structure, "codec_data");
675   if (codec_data && G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER)
676     state->codec_data = GST_BUFFER (g_value_dup_boxed (codec_data));
677
678   return state;
679
680 parse_fail:
681   {
682     g_slice_free (GstVideoCodecState, state);
683     return NULL;
684   }
685 }
686
687 static GstVideoCodecState *
688 _new_output_state (GstVideoFormat fmt, guint width, guint height,
689     GstVideoCodecState * reference)
690 {
691   GstVideoCodecState *state;
692
693   state = g_slice_new0 (GstVideoCodecState);
694   state->ref_count = 1;
695   gst_video_info_init (&state->info);
696   gst_video_info_set_format (&state->info, fmt, width, height);
697
698   if (reference) {
699     GstVideoInfo *tgt, *ref;
700
701     tgt = &state->info;
702     ref = &reference->info;
703
704     /* Copy over extra fields from reference state */
705     tgt->interlace_mode = ref->interlace_mode;
706     tgt->flags = ref->flags;
707     tgt->chroma_site = ref->chroma_site;
708     /* only copy values that are not unknown so that we don't override the
709      * defaults. subclasses should really fill these in when they know. */
710     if (ref->colorimetry.range)
711       tgt->colorimetry.range = ref->colorimetry.range;
712     if (ref->colorimetry.matrix)
713       tgt->colorimetry.matrix = ref->colorimetry.matrix;
714     if (ref->colorimetry.transfer)
715       tgt->colorimetry.transfer = ref->colorimetry.transfer;
716     if (ref->colorimetry.primaries)
717       tgt->colorimetry.primaries = ref->colorimetry.primaries;
718     GST_DEBUG ("reference par %d/%d fps %d/%d",
719         ref->par_n, ref->par_d, ref->fps_n, ref->fps_d);
720     tgt->par_n = ref->par_n;
721     tgt->par_d = ref->par_d;
722     tgt->fps_n = ref->fps_n;
723     tgt->fps_d = ref->fps_d;
724   }
725
726   GST_DEBUG ("reference par %d/%d fps %d/%d",
727       state->info.par_n, state->info.par_d,
728       state->info.fps_n, state->info.fps_d);
729
730   return state;
731 }
732
733 static gboolean
734 gst_video_decoder_setcaps (GstVideoDecoder * decoder, GstCaps * caps)
735 {
736   GstVideoDecoderClass *decoder_class;
737   GstVideoCodecState *state;
738   gboolean ret = TRUE;
739
740   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
741
742   GST_DEBUG_OBJECT (decoder, "setcaps %" GST_PTR_FORMAT, caps);
743
744   state = _new_input_state (caps);
745
746   if (G_UNLIKELY (state == NULL))
747     goto parse_fail;
748
749   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
750
751   if (decoder_class->set_format)
752     ret = decoder_class->set_format (decoder, state);
753
754   if (!ret)
755     goto refused_format;
756
757   if (decoder->priv->input_state)
758     gst_video_codec_state_unref (decoder->priv->input_state);
759   decoder->priv->input_state = state;
760
761   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
762
763   return ret;
764
765   /* ERRORS */
766
767 parse_fail:
768   {
769     GST_WARNING_OBJECT (decoder, "Failed to parse caps");
770     return FALSE;
771   }
772
773 refused_format:
774   {
775     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
776     GST_WARNING_OBJECT (decoder, "Subclass refused caps");
777     gst_video_codec_state_unref (state);
778     return FALSE;
779   }
780 }
781
782 static void
783 gst_video_decoder_finalize (GObject * object)
784 {
785   GstVideoDecoder *decoder;
786
787   decoder = GST_VIDEO_DECODER (object);
788
789   GST_DEBUG_OBJECT (object, "finalize");
790
791   g_rec_mutex_clear (&decoder->stream_lock);
792
793   if (decoder->priv->input_adapter) {
794     g_object_unref (decoder->priv->input_adapter);
795     decoder->priv->input_adapter = NULL;
796   }
797   if (decoder->priv->output_adapter) {
798     g_object_unref (decoder->priv->output_adapter);
799     decoder->priv->output_adapter = NULL;
800   }
801
802   if (decoder->priv->input_state)
803     gst_video_codec_state_unref (decoder->priv->input_state);
804   if (decoder->priv->output_state)
805     gst_video_codec_state_unref (decoder->priv->output_state);
806
807   if (decoder->priv->pool) {
808     gst_object_unref (decoder->priv->pool);
809     decoder->priv->pool = NULL;
810   }
811
812   if (decoder->priv->allocator) {
813     gst_object_unref (decoder->priv->allocator);
814     decoder->priv->allocator = NULL;
815   }
816
817   G_OBJECT_CLASS (parent_class)->finalize (object);
818 }
819
820 /* hard == FLUSH, otherwise discont */
821 static GstFlowReturn
822 gst_video_decoder_flush (GstVideoDecoder * dec, gboolean hard)
823 {
824   GstVideoDecoderClass *klass;
825   GstVideoDecoderPrivate *priv = dec->priv;
826   GstFlowReturn ret = GST_FLOW_OK;
827
828   klass = GST_VIDEO_DECODER_GET_CLASS (dec);
829
830   GST_LOG_OBJECT (dec, "flush hard %d", hard);
831
832   /* Inform subclass */
833   if (klass->reset)
834     klass->reset (dec, hard);
835
836   /* FIXME make some more distinction between hard and soft,
837    * but subclass may not be prepared for that */
838   /* FIXME perhaps also clear pending frames ?,
839    * but again, subclass may still come up with one of those */
840   if (!hard) {
841     /* TODO ? finish/drain some stuff */
842   } else {
843     gst_segment_init (&dec->input_segment, GST_FORMAT_UNDEFINED);
844     gst_segment_init (&dec->output_segment, GST_FORMAT_UNDEFINED);
845     gst_video_decoder_clear_queues (dec);
846     priv->error_count = 0;
847     g_list_free_full (priv->current_frame_events,
848         (GDestroyNotify) gst_event_unref);
849     priv->current_frame_events = NULL;
850   }
851   /* and get (re)set for the sequel */
852   gst_video_decoder_reset (dec, FALSE);
853
854   return ret;
855 }
856
857 static gboolean
858 gst_video_decoder_push_event (GstVideoDecoder * decoder, GstEvent * event)
859 {
860   switch (GST_EVENT_TYPE (event)) {
861     case GST_EVENT_SEGMENT:
862     {
863       GstSegment segment;
864
865       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
866
867       gst_event_copy_segment (event, &segment);
868
869       GST_DEBUG_OBJECT (decoder, "segment %" GST_SEGMENT_FORMAT, &segment);
870
871       if (segment.format != GST_FORMAT_TIME) {
872         GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
873         GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
874         break;
875       }
876
877       decoder->output_segment = segment;
878       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
879       break;
880     }
881     default:
882       break;
883   }
884
885   return gst_pad_push_event (decoder->srcpad, event);
886 }
887
888 static GstFlowReturn
889 gst_video_decoder_handle_eos (GstVideoDecoder * dec)
890 {
891   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_GET_CLASS (dec);
892   GstVideoDecoderPrivate *priv = dec->priv;
893   GstFlowReturn ret = GST_FLOW_OK;
894
895   GST_VIDEO_DECODER_STREAM_LOCK (dec);
896
897   if (dec->input_segment.rate > 0.0) {
898     /* Forward mode, if unpacketized, give the child class
899      * a final chance to flush out packets */
900     if (!priv->packetized) {
901       if (priv->current_frame == NULL)
902         priv->current_frame = gst_video_decoder_new_frame (dec);
903
904       while (ret == GST_FLOW_OK && gst_adapter_available (priv->input_adapter))
905         ret = decoder_class->parse (dec, priv->current_frame,
906             priv->input_adapter, TRUE);
907     }
908   } else {
909     /* Reverse playback mode */
910     ret = gst_video_decoder_flush_parse (dec, TRUE);
911   }
912
913   if (decoder_class->finish)
914     ret = decoder_class->finish (dec);
915
916   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
917
918   return ret;
919 }
920
921 static gboolean
922 gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
923     GstEvent * event)
924 {
925   GstVideoDecoderPrivate *priv;
926   gboolean ret = FALSE;
927
928   priv = decoder->priv;
929
930   switch (GST_EVENT_TYPE (event)) {
931     case GST_EVENT_CAPS:
932     {
933       GstCaps *caps;
934
935       gst_event_parse_caps (event, &caps);
936       ret = gst_video_decoder_setcaps (decoder, caps);
937       gst_event_unref (event);
938       event = NULL;
939       break;
940     }
941     case GST_EVENT_EOS:
942     {
943       GstFlowReturn flow_ret = GST_FLOW_OK;
944
945       flow_ret = gst_video_decoder_handle_eos (decoder);
946       ret = (flow_ret == GST_FLOW_OK);
947
948       break;
949     }
950     case GST_EVENT_SEGMENT:
951     {
952       GstSegment segment;
953
954       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
955
956       gst_event_copy_segment (event, &segment);
957
958       if (segment.format == GST_FORMAT_TIME) {
959         GST_DEBUG_OBJECT (decoder,
960             "received TIME SEGMENT %" GST_SEGMENT_FORMAT, &segment);
961       } else {
962         gint64 start;
963
964         GST_DEBUG_OBJECT (decoder,
965             "received SEGMENT %" GST_SEGMENT_FORMAT, &segment);
966
967         /* handle newsegment as a result from our legacy simple seeking */
968         /* note that initial 0 should convert to 0 in any case */
969         if (priv->do_estimate_rate &&
970             gst_pad_query_convert (decoder->sinkpad, GST_FORMAT_BYTES,
971                 segment.start, GST_FORMAT_TIME, &start)) {
972           /* best attempt convert */
973           /* as these are only estimates, stop is kept open-ended to avoid
974            * premature cutting */
975           GST_DEBUG_OBJECT (decoder,
976               "converted to TIME start %" GST_TIME_FORMAT,
977               GST_TIME_ARGS (start));
978           segment.start = start;
979           segment.stop = GST_CLOCK_TIME_NONE;
980           segment.time = start;
981           /* replace event */
982           gst_event_unref (event);
983           event = gst_event_new_segment (&segment);
984         } else {
985           GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
986           goto newseg_wrong_format;
987         }
988       }
989
990       gst_video_decoder_flush (decoder, FALSE);
991
992       priv->base_timestamp = GST_CLOCK_TIME_NONE;
993       priv->base_picture_number = 0;
994
995       decoder->input_segment = segment;
996
997       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
998       break;
999     }
1000     case GST_EVENT_FLUSH_STOP:
1001     {
1002       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1003       /* well, this is kind of worse than a DISCONT */
1004       gst_video_decoder_flush (decoder, TRUE);
1005       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1006     }
1007     default:
1008       break;
1009   }
1010
1011   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1012    * For EOS this is required because no buffer or serialized event
1013    * will come after EOS and nothing could trigger another
1014    * _finish_frame() call.   *
1015    * If the subclass handles sending of EOS manually it can return
1016    * _DROPPED from ::finish() and all other subclasses should have
1017    * decoded/flushed all remaining data before this
1018    *
1019    * For FLUSH_STOP this is required because it is expected
1020    * to be forwarded immediately and no buffers are queued anyway.
1021    */
1022   if (event) {
1023     if (!GST_EVENT_IS_SERIALIZED (event)
1024         || GST_EVENT_TYPE (event) == GST_EVENT_EOS
1025         || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
1026       ret = gst_video_decoder_push_event (decoder, event);
1027     } else {
1028       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1029       decoder->priv->current_frame_events =
1030           g_list_prepend (decoder->priv->current_frame_events, event);
1031       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1032       ret = TRUE;
1033     }
1034   }
1035
1036   return ret;
1037
1038 newseg_wrong_format:
1039   {
1040     GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
1041     gst_event_unref (event);
1042     /* SWALLOW EVENT */
1043     return TRUE;
1044   }
1045 }
1046
1047 static gboolean
1048 gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
1049     GstEvent * event)
1050 {
1051   GstVideoDecoder *decoder;
1052   GstVideoDecoderClass *decoder_class;
1053   gboolean ret = FALSE;
1054
1055   decoder = GST_VIDEO_DECODER (parent);
1056   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1057
1058   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1059       GST_EVENT_TYPE_NAME (event));
1060
1061   if (decoder_class->sink_event)
1062     ret = decoder_class->sink_event (decoder, event);
1063
1064   return ret;
1065 }
1066
1067 /* perform upstream byte <-> time conversion (duration, seeking)
1068  * if subclass allows and if enough data for moderately decent conversion */
1069 static inline gboolean
1070 gst_video_decoder_do_byte (GstVideoDecoder * dec)
1071 {
1072   return dec->priv->do_estimate_rate && (dec->priv->bytes_out > 0)
1073       && (dec->priv->time > GST_SECOND);
1074 }
1075
1076 static gboolean
1077 gst_video_decoder_do_seek (GstVideoDecoder * dec, GstEvent * event)
1078 {
1079   GstFormat format;
1080   GstSeekFlags flags;
1081   GstSeekType start_type, end_type;
1082   gdouble rate;
1083   gint64 start, start_time, end_time;
1084   GstSegment seek_segment;
1085   guint32 seqnum;
1086
1087   gst_event_parse_seek (event, &rate, &format, &flags, &start_type,
1088       &start_time, &end_type, &end_time);
1089
1090   /* we'll handle plain open-ended flushing seeks with the simple approach */
1091   if (rate != 1.0) {
1092     GST_DEBUG_OBJECT (dec, "unsupported seek: rate");
1093     return FALSE;
1094   }
1095
1096   if (start_type != GST_SEEK_TYPE_SET) {
1097     GST_DEBUG_OBJECT (dec, "unsupported seek: start time");
1098     return FALSE;
1099   }
1100
1101   if (end_type != GST_SEEK_TYPE_NONE ||
1102       (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) {
1103     GST_DEBUG_OBJECT (dec, "unsupported seek: end time");
1104     return FALSE;
1105   }
1106
1107   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
1108     GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing");
1109     return FALSE;
1110   }
1111
1112   memcpy (&seek_segment, &dec->output_segment, sizeof (seek_segment));
1113   gst_segment_do_seek (&seek_segment, rate, format, flags, start_type,
1114       start_time, end_type, end_time, NULL);
1115   start_time = seek_segment.position;
1116
1117   if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time,
1118           GST_FORMAT_BYTES, &start)) {
1119     GST_DEBUG_OBJECT (dec, "conversion failed");
1120     return FALSE;
1121   }
1122
1123   seqnum = gst_event_get_seqnum (event);
1124   event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags,
1125       GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1);
1126   gst_event_set_seqnum (event, seqnum);
1127
1128   GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %"
1129       G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start);
1130
1131   return gst_pad_push_event (dec->sinkpad, event);
1132 }
1133
1134 static gboolean
1135 gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
1136     GstEvent * event)
1137 {
1138   GstVideoDecoderPrivate *priv;
1139   gboolean res = FALSE;
1140
1141   priv = decoder->priv;
1142
1143   GST_DEBUG_OBJECT (decoder,
1144       "received event %d, %s", GST_EVENT_TYPE (event),
1145       GST_EVENT_TYPE_NAME (event));
1146
1147   switch (GST_EVENT_TYPE (event)) {
1148     case GST_EVENT_SEEK:
1149     {
1150       GstFormat format;
1151       gdouble rate;
1152       GstSeekFlags flags;
1153       GstSeekType cur_type, stop_type;
1154       gint64 cur, stop;
1155       gint64 tcur, tstop;
1156       guint32 seqnum;
1157
1158       gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
1159           &stop_type, &stop);
1160       seqnum = gst_event_get_seqnum (event);
1161
1162       /* upstream gets a chance first */
1163       if ((res = gst_pad_push_event (decoder->sinkpad, event)))
1164         break;
1165
1166       /* if upstream fails for a time seek, maybe we can help if allowed */
1167       if (format == GST_FORMAT_TIME) {
1168         if (gst_video_decoder_do_byte (decoder))
1169           res = gst_video_decoder_do_seek (decoder, event);
1170         break;
1171       }
1172
1173       /* ... though a non-time seek can be aided as well */
1174       /* First bring the requested format to time */
1175       if (!(res =
1176               gst_pad_query_convert (decoder->srcpad, format, cur,
1177                   GST_FORMAT_TIME, &tcur)))
1178         goto convert_error;
1179       if (!(res =
1180               gst_pad_query_convert (decoder->srcpad, format, stop,
1181                   GST_FORMAT_TIME, &tstop)))
1182         goto convert_error;
1183
1184       /* then seek with time on the peer */
1185       event = gst_event_new_seek (rate, GST_FORMAT_TIME,
1186           flags, cur_type, tcur, stop_type, tstop);
1187       gst_event_set_seqnum (event, seqnum);
1188
1189       res = gst_pad_push_event (decoder->sinkpad, event);
1190       break;
1191     }
1192     case GST_EVENT_QOS:
1193     {
1194       GstQOSType type;
1195       gdouble proportion;
1196       GstClockTimeDiff diff;
1197       GstClockTime timestamp;
1198       GstClockTime duration;
1199
1200       gst_event_parse_qos (event, &type, &proportion, &diff, &timestamp);
1201
1202       GST_OBJECT_LOCK (decoder);
1203       priv->proportion = proportion;
1204       if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (timestamp))) {
1205         if (G_UNLIKELY (diff > 0)) {
1206           if (priv->output_state->info.fps_n > 0)
1207             duration =
1208                 gst_util_uint64_scale (GST_SECOND,
1209                 priv->output_state->info.fps_d, priv->output_state->info.fps_n);
1210           else
1211             duration = 0;
1212           priv->earliest_time = timestamp + 2 * diff + duration;
1213         } else {
1214           priv->earliest_time = timestamp + diff;
1215         }
1216       } else {
1217         priv->earliest_time = GST_CLOCK_TIME_NONE;
1218       }
1219       GST_OBJECT_UNLOCK (decoder);
1220
1221       GST_DEBUG_OBJECT (decoder,
1222           "got QoS %" GST_TIME_FORMAT ", %" G_GINT64_FORMAT ", %g",
1223           GST_TIME_ARGS (timestamp), diff, proportion);
1224
1225       res = gst_pad_push_event (decoder->sinkpad, event);
1226       break;
1227     }
1228     default:
1229       res = gst_pad_push_event (decoder->sinkpad, event);
1230       break;
1231   }
1232 done:
1233   return res;
1234
1235 convert_error:
1236   GST_DEBUG_OBJECT (decoder, "could not convert format");
1237   goto done;
1238 }
1239
1240 static gboolean
1241 gst_video_decoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1242 {
1243   GstVideoDecoder *decoder;
1244   GstVideoDecoderClass *decoder_class;
1245   gboolean ret = FALSE;
1246
1247   decoder = GST_VIDEO_DECODER (parent);
1248   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1249
1250   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1251       GST_EVENT_TYPE_NAME (event));
1252
1253   if (decoder_class->src_event)
1254     ret = decoder_class->src_event (decoder, event);
1255
1256   return ret;
1257 }
1258
1259 static gboolean
1260 gst_video_decoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1261 {
1262   GstVideoDecoder *dec;
1263   gboolean res = TRUE;
1264
1265   dec = GST_VIDEO_DECODER (parent);
1266
1267   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
1268
1269   switch (GST_QUERY_TYPE (query)) {
1270     case GST_QUERY_POSITION:
1271     {
1272       GstFormat format;
1273       gint64 time, value;
1274
1275       /* upstream gets a chance first */
1276       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
1277         GST_LOG_OBJECT (dec, "returning peer response");
1278         break;
1279       }
1280
1281       /* we start from the last seen time */
1282       time = dec->priv->last_timestamp_out;
1283       /* correct for the segment values */
1284       time = gst_segment_to_stream_time (&dec->output_segment,
1285           GST_FORMAT_TIME, time);
1286
1287       GST_LOG_OBJECT (dec,
1288           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
1289
1290       /* and convert to the final format */
1291       gst_query_parse_position (query, &format, NULL);
1292       if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time,
1293                   format, &value)))
1294         break;
1295
1296       gst_query_set_position (query, format, value);
1297
1298       GST_LOG_OBJECT (dec,
1299           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
1300           format);
1301       break;
1302     }
1303     case GST_QUERY_DURATION:
1304     {
1305       GstFormat format;
1306
1307       /* upstream in any case */
1308       if ((res = gst_pad_query_default (pad, parent, query)))
1309         break;
1310
1311       gst_query_parse_duration (query, &format, NULL);
1312       /* try answering TIME by converting from BYTE if subclass allows  */
1313       if (format == GST_FORMAT_TIME && gst_video_decoder_do_byte (dec)) {
1314         gint64 value;
1315
1316         if (gst_pad_peer_query_duration (dec->sinkpad, GST_FORMAT_BYTES,
1317                 &value)) {
1318           GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value);
1319           if (gst_pad_query_convert (dec->sinkpad,
1320                   GST_FORMAT_BYTES, value, GST_FORMAT_TIME, &value)) {
1321             gst_query_set_duration (query, GST_FORMAT_TIME, value);
1322             res = TRUE;
1323           }
1324         }
1325       }
1326       break;
1327     }
1328     case GST_QUERY_CONVERT:
1329     {
1330       GstFormat src_fmt, dest_fmt;
1331       gint64 src_val, dest_val;
1332
1333       GST_DEBUG_OBJECT (dec, "convert query");
1334
1335       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1336       res = gst_video_rawvideo_convert (dec->priv->output_state,
1337           src_fmt, src_val, &dest_fmt, &dest_val);
1338       if (!res)
1339         goto error;
1340       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1341       break;
1342     }
1343     case GST_QUERY_LATENCY:
1344     {
1345       gboolean live;
1346       GstClockTime min_latency, max_latency;
1347
1348       res = gst_pad_peer_query (dec->sinkpad, query);
1349       if (res) {
1350         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1351         GST_DEBUG_OBJECT (dec, "Peer latency: live %d, min %"
1352             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1353             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1354
1355         GST_OBJECT_LOCK (dec);
1356         min_latency += dec->priv->min_latency;
1357         if (dec->priv->max_latency == GST_CLOCK_TIME_NONE) {
1358           max_latency = GST_CLOCK_TIME_NONE;
1359         } else if (max_latency != GST_CLOCK_TIME_NONE) {
1360           max_latency += dec->priv->max_latency;
1361         }
1362         GST_OBJECT_UNLOCK (dec);
1363
1364         gst_query_set_latency (query, live, min_latency, max_latency);
1365       }
1366     }
1367       break;
1368     default:
1369       res = gst_pad_query_default (pad, parent, query);
1370   }
1371   return res;
1372
1373 error:
1374   GST_ERROR_OBJECT (dec, "query failed");
1375   return res;
1376 }
1377
1378 static gboolean
1379 gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
1380     GstQuery * query)
1381 {
1382   GstVideoDecoder *decoder;
1383   GstVideoDecoderPrivate *priv;
1384   gboolean res = FALSE;
1385
1386   decoder = GST_VIDEO_DECODER (parent);
1387   priv = decoder->priv;
1388
1389   GST_LOG_OBJECT (decoder, "handling query: %" GST_PTR_FORMAT, query);
1390
1391   switch (GST_QUERY_TYPE (query)) {
1392     case GST_QUERY_CONVERT:
1393     {
1394       GstFormat src_fmt, dest_fmt;
1395       gint64 src_val, dest_val;
1396
1397       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1398       res =
1399           gst_video_encoded_video_convert (priv->bytes_out, priv->time, src_fmt,
1400           src_val, &dest_fmt, &dest_val);
1401       if (!res)
1402         goto error;
1403       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1404       break;
1405     }
1406     case GST_QUERY_ALLOCATION:{
1407       GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
1408
1409       if (klass->propose_allocation)
1410         res = klass->propose_allocation (decoder, query);
1411       break;
1412     }
1413     default:
1414       res = gst_pad_query_default (pad, parent, query);
1415       break;
1416   }
1417 done:
1418
1419   return res;
1420 error:
1421   GST_DEBUG_OBJECT (decoder, "query failed");
1422   goto done;
1423 }
1424
1425 typedef struct _Timestamp Timestamp;
1426 struct _Timestamp
1427 {
1428   guint64 offset;
1429   GstClockTime pts;
1430   GstClockTime dts;
1431   GstClockTime duration;
1432 };
1433
1434 static void
1435 timestamp_free (Timestamp * ts)
1436 {
1437   g_slice_free (Timestamp, ts);
1438 }
1439
1440 static void
1441 gst_video_decoder_add_timestamp (GstVideoDecoder * decoder, GstBuffer * buffer)
1442 {
1443   GstVideoDecoderPrivate *priv = decoder->priv;
1444   Timestamp *ts;
1445
1446   ts = g_slice_new (Timestamp);
1447
1448   GST_LOG_OBJECT (decoder,
1449       "adding PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT
1450       " (offset:%" G_GUINT64_FORMAT ")",
1451       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1452       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), priv->input_offset);
1453
1454   ts->offset = priv->input_offset;
1455   ts->pts = GST_BUFFER_PTS (buffer);
1456   ts->dts = GST_BUFFER_DTS (buffer);
1457   ts->duration = GST_BUFFER_DURATION (buffer);
1458
1459   priv->timestamps = g_list_append (priv->timestamps, ts);
1460 }
1461
1462 static void
1463 gst_video_decoder_get_timestamp_at_offset (GstVideoDecoder *
1464     decoder, guint64 offset, GstClockTime * pts, GstClockTime * dts,
1465     GstClockTime * duration)
1466 {
1467 #ifndef GST_DISABLE_GST_DEBUG
1468   guint64 got_offset = 0;
1469 #endif
1470   Timestamp *ts;
1471   GList *g;
1472
1473   *pts = GST_CLOCK_TIME_NONE;
1474   *dts = GST_CLOCK_TIME_NONE;
1475   *duration = GST_CLOCK_TIME_NONE;
1476
1477   g = decoder->priv->timestamps;
1478   while (g) {
1479     ts = g->data;
1480     if (ts->offset <= offset) {
1481 #ifndef GST_DISABLE_GST_DEBUG
1482       got_offset = ts->offset;
1483 #endif
1484       *pts = ts->pts;
1485       *dts = ts->dts;
1486       *duration = ts->duration;
1487       timestamp_free (ts);
1488       g = g->next;
1489       decoder->priv->timestamps = g_list_remove (decoder->priv->timestamps, ts);
1490     } else {
1491       break;
1492     }
1493   }
1494
1495   GST_LOG_OBJECT (decoder,
1496       "got PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT " @ offs %"
1497       G_GUINT64_FORMAT " (wanted offset:%" G_GUINT64_FORMAT ")",
1498       GST_TIME_ARGS (*pts), GST_TIME_ARGS (*dts), got_offset, offset);
1499 }
1500
1501 static void
1502 gst_video_decoder_clear_queues (GstVideoDecoder * dec)
1503 {
1504   GstVideoDecoderPrivate *priv = dec->priv;
1505
1506   g_list_free_full (priv->output_queued,
1507       (GDestroyNotify) gst_mini_object_unref);
1508   priv->output_queued = NULL;
1509
1510   g_list_free_full (priv->gather, (GDestroyNotify) gst_mini_object_unref);
1511   priv->gather = NULL;
1512   g_list_free_full (priv->decode, (GDestroyNotify) gst_video_codec_frame_unref);
1513   priv->decode = NULL;
1514   g_list_free_full (priv->parse, (GDestroyNotify) gst_mini_object_unref);
1515   priv->parse = NULL;
1516   g_list_free_full (priv->parse_gather,
1517       (GDestroyNotify) gst_video_codec_frame_unref);
1518   priv->parse_gather = NULL;
1519   g_list_free_full (priv->frames, (GDestroyNotify) gst_video_codec_frame_unref);
1520   priv->frames = NULL;
1521 }
1522
1523 static void
1524 gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full)
1525 {
1526   GstVideoDecoderPrivate *priv = decoder->priv;
1527
1528   GST_DEBUG_OBJECT (decoder, "reset full %d", full);
1529
1530   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1531
1532   if (full) {
1533     gst_segment_init (&decoder->input_segment, GST_FORMAT_UNDEFINED);
1534     gst_segment_init (&decoder->output_segment, GST_FORMAT_UNDEFINED);
1535     gst_video_decoder_clear_queues (decoder);
1536     priv->error_count = 0;
1537     priv->max_errors = GST_VIDEO_DECODER_MAX_ERRORS;
1538     if (priv->input_state)
1539       gst_video_codec_state_unref (priv->input_state);
1540     priv->input_state = NULL;
1541     if (priv->output_state)
1542       gst_video_codec_state_unref (priv->output_state);
1543     priv->output_state = NULL;
1544     priv->min_latency = 0;
1545     priv->max_latency = 0;
1546   }
1547
1548   priv->discont = TRUE;
1549
1550   priv->base_timestamp = GST_CLOCK_TIME_NONE;
1551   priv->last_timestamp_out = GST_CLOCK_TIME_NONE;
1552
1553   priv->input_offset = 0;
1554   priv->frame_offset = 0;
1555   gst_adapter_clear (priv->input_adapter);
1556   gst_adapter_clear (priv->output_adapter);
1557   g_list_free_full (priv->timestamps, (GDestroyNotify) timestamp_free);
1558   priv->timestamps = NULL;
1559
1560   if (priv->current_frame) {
1561     gst_video_codec_frame_unref (priv->current_frame);
1562     priv->current_frame = NULL;
1563   }
1564
1565   priv->dropped = 0;
1566   priv->processed = 0;
1567
1568   priv->decode_frame_number = 0;
1569   priv->base_picture_number = 0;
1570
1571   g_list_free_full (priv->frames, (GDestroyNotify) gst_video_codec_frame_unref);
1572   priv->frames = NULL;
1573
1574   priv->bytes_out = 0;
1575   priv->time = 0;
1576
1577   priv->earliest_time = GST_CLOCK_TIME_NONE;
1578   priv->proportion = 0.5;
1579
1580   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1581 }
1582
1583 static GstFlowReturn
1584 gst_video_decoder_chain_forward (GstVideoDecoder * decoder,
1585     GstBuffer * buf, gboolean at_eos)
1586 {
1587   GstVideoDecoderPrivate *priv;
1588   GstVideoDecoderClass *klass;
1589   GstFlowReturn ret = GST_FLOW_OK;
1590
1591   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
1592   priv = decoder->priv;
1593
1594   g_return_val_if_fail (priv->packetized || klass->parse, GST_FLOW_ERROR);
1595
1596   if (priv->current_frame == NULL)
1597     priv->current_frame = gst_video_decoder_new_frame (decoder);
1598
1599   if (GST_BUFFER_PTS_IS_VALID (buf)) {
1600     gst_video_decoder_add_timestamp (decoder, buf);
1601   }
1602   priv->input_offset += gst_buffer_get_size (buf);
1603
1604   if (priv->packetized) {
1605     if (!GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
1606       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (priv->current_frame);
1607     }
1608
1609     priv->current_frame->input_buffer = buf;
1610
1611     if (decoder->input_segment.rate < 0.0) {
1612       priv->parse_gather =
1613           g_list_prepend (priv->parse_gather, priv->current_frame);
1614     } else {
1615       ret = gst_video_decoder_decode_frame (decoder, priv->current_frame);
1616     }
1617     priv->current_frame = NULL;
1618   } else {
1619
1620     gst_adapter_push (priv->input_adapter, buf);
1621
1622     if (G_UNLIKELY (!gst_adapter_available (priv->input_adapter)))
1623       goto beach;
1624
1625     do {
1626       ret = klass->parse (decoder, priv->current_frame,
1627           priv->input_adapter, at_eos);
1628     } while (ret == GST_FLOW_OK && gst_adapter_available (priv->input_adapter));
1629   }
1630
1631 beach:
1632   if (ret == GST_VIDEO_DECODER_FLOW_NEED_DATA)
1633     return GST_FLOW_OK;
1634
1635   return ret;
1636 }
1637
1638 static GstFlowReturn
1639 gst_video_decoder_flush_decode (GstVideoDecoder * dec)
1640 {
1641   GstVideoDecoderPrivate *priv = dec->priv;
1642   GstFlowReturn res = GST_FLOW_OK;
1643   GList *walk;
1644
1645   GST_DEBUG_OBJECT (dec, "flushing buffers to decode");
1646
1647   /* clear buffer and decoder state */
1648   gst_video_decoder_flush (dec, FALSE);
1649
1650   walk = priv->decode;
1651   while (walk) {
1652     GList *next;
1653     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
1654     GstBuffer *buf = frame->input_buffer;
1655
1656     GST_DEBUG_OBJECT (dec, "decoding frame %p buffer %p, PTS %" GST_TIME_FORMAT
1657         ", DTS %" GST_TIME_FORMAT, frame, buf,
1658         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1659         GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
1660
1661     next = walk->next;
1662
1663     priv->decode = g_list_delete_link (priv->decode, walk);
1664
1665     /* decode buffer, resulting data prepended to queue */
1666     res = gst_video_decoder_decode_frame (dec, frame);
1667     if (res != GST_FLOW_OK)
1668       break;
1669
1670     walk = next;
1671   }
1672
1673   return res;
1674 }
1675
1676 /* gst_video_decoder_flush_parse is called from the
1677  * chain_reverse() function when a buffer containing
1678  * a DISCONT - indicating that reverse playback
1679  * looped back to the next data block, and therefore
1680  * all available data should be fed through the
1681  * decoder and frames gathered for reversed output
1682  */
1683 static GstFlowReturn
1684 gst_video_decoder_flush_parse (GstVideoDecoder * dec, gboolean at_eos)
1685 {
1686   GstVideoDecoderPrivate *priv = dec->priv;
1687   GstFlowReturn res = GST_FLOW_OK;
1688   GList *walk;
1689
1690   GST_DEBUG_OBJECT (dec, "flushing buffers to parsing");
1691
1692   /* Reverse the gather list, and prepend it to the parse list,
1693    * then flush to parse whatever we can */
1694   priv->gather = g_list_reverse (priv->gather);
1695   priv->parse = g_list_concat (priv->gather, priv->parse);
1696   priv->gather = NULL;
1697
1698   /* clear buffer and decoder state */
1699   gst_video_decoder_flush (dec, FALSE);
1700
1701   walk = priv->parse;
1702   while (walk) {
1703     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1704     GList *next = walk->next;
1705
1706     GST_DEBUG_OBJECT (dec, "parsing buffer %p, PTS %" GST_TIME_FORMAT
1707         ", DTS %" GST_TIME_FORMAT, buf, GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1708         GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
1709
1710     /* parse buffer, resulting frames prepended to parse_gather queue */
1711     gst_buffer_ref (buf);
1712     res = gst_video_decoder_chain_forward (dec, buf, at_eos);
1713
1714     /* if we generated output, we can discard the buffer, else we
1715      * keep it in the queue */
1716     if (priv->parse_gather) {
1717       GST_DEBUG_OBJECT (dec, "parsed buffer to %p", priv->parse_gather->data);
1718       priv->parse = g_list_delete_link (priv->parse, walk);
1719       gst_buffer_unref (buf);
1720     } else {
1721       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1722     }
1723     walk = next;
1724   }
1725
1726   /* now we can process frames. Start by moving each frame from the parse_gather
1727    * to the decode list, reverse the order as we go, and stopping when/if we
1728    * copy a keyframe. */
1729   GST_DEBUG_OBJECT (dec, "checking parsed frames for a keyframe to decode");
1730   walk = priv->parse_gather;
1731   while (walk) {
1732     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
1733
1734     /* remove from the gather list */
1735     priv->parse_gather = g_list_remove_link (priv->parse_gather, walk);
1736
1737     /* move it to the front of the decode queue */
1738     priv->decode = g_list_concat (walk, priv->decode);
1739
1740     /* if we copied a keyframe, flush and decode the decode queue */
1741     if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
1742       GST_DEBUG_OBJECT (dec, "found keyframe %p with PTS %" GST_TIME_FORMAT
1743           ", DTS %" GST_TIME_FORMAT, frame,
1744           GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)),
1745           GST_TIME_ARGS (GST_BUFFER_DTS (frame->input_buffer)));
1746       res = gst_video_decoder_flush_decode (dec);
1747       if (res != GST_FLOW_OK)
1748         goto done;
1749     }
1750
1751     walk = priv->parse_gather;
1752   }
1753
1754   /* now send queued data downstream */
1755   walk = priv->output_queued;
1756   while (walk) {
1757     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1758
1759     if (G_LIKELY (res == GST_FLOW_OK)) {
1760       /* avoid stray DISCONT from forward processing,
1761        * which have no meaning in reverse pushing */
1762       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
1763
1764       /* Last chance to calculate a timestamp as we loop backwards
1765        * through the list */
1766       if (GST_BUFFER_TIMESTAMP (buf) != GST_CLOCK_TIME_NONE)
1767         priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
1768       else if (priv->last_timestamp_out != GST_CLOCK_TIME_NONE &&
1769           GST_BUFFER_DURATION (buf) != GST_CLOCK_TIME_NONE) {
1770         GST_BUFFER_TIMESTAMP (buf) =
1771             priv->last_timestamp_out - GST_BUFFER_DURATION (buf);
1772         priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
1773         GST_LOG_OBJECT (dec,
1774             "Calculated TS %" GST_TIME_FORMAT " working backwards",
1775             GST_TIME_ARGS (priv->last_timestamp_out));
1776       }
1777
1778       res = gst_video_decoder_clip_and_push_buf (dec, buf);
1779     } else {
1780       gst_buffer_unref (buf);
1781     }
1782
1783     priv->output_queued =
1784         g_list_delete_link (priv->output_queued, priv->output_queued);
1785     walk = priv->output_queued;
1786   }
1787
1788 done:
1789   return res;
1790 }
1791
1792 static GstFlowReturn
1793 gst_video_decoder_chain_reverse (GstVideoDecoder * dec, GstBuffer * buf)
1794 {
1795   GstVideoDecoderPrivate *priv = dec->priv;
1796   GstFlowReturn result = GST_FLOW_OK;
1797
1798   /* if we have a discont, move buffers to the decode list */
1799   if (!buf || GST_BUFFER_IS_DISCONT (buf)) {
1800     GST_DEBUG_OBJECT (dec, "received discont");
1801
1802     /* parse and decode stuff in the gather and parse queues */
1803     gst_video_decoder_flush_parse (dec, FALSE);
1804   }
1805
1806   if (G_LIKELY (buf)) {
1807     GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %" G_GSIZE_FORMAT ", "
1808         "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
1809         GST_TIME_FORMAT, buf, gst_buffer_get_size (buf),
1810         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1811         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
1812         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1813
1814     /* add buffer to gather queue */
1815     priv->gather = g_list_prepend (priv->gather, buf);
1816   }
1817
1818   return result;
1819 }
1820
1821 static GstFlowReturn
1822 gst_video_decoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
1823 {
1824   GstVideoDecoder *decoder;
1825   GstFlowReturn ret = GST_FLOW_OK;
1826
1827   decoder = GST_VIDEO_DECODER (parent);
1828
1829   GST_LOG_OBJECT (decoder,
1830       "chain PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT " duration %"
1831       GST_TIME_FORMAT " size %" G_GSIZE_FORMAT,
1832       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1833       GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
1834       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), gst_buffer_get_size (buf));
1835
1836   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1837
1838   /* NOTE:
1839    * requiring the pad to be negotiated makes it impossible to use
1840    * oggdemux or filesrc ! decoder */
1841
1842   if (decoder->input_segment.format == GST_FORMAT_UNDEFINED) {
1843     GstEvent *event;
1844     GstSegment *segment = &decoder->input_segment;
1845
1846     GST_WARNING_OBJECT (decoder,
1847         "Received buffer without a new-segment. "
1848         "Assuming timestamps start from 0.");
1849
1850     gst_segment_init (segment, GST_FORMAT_TIME);
1851
1852     event = gst_event_new_segment (segment);
1853
1854     decoder->priv->current_frame_events =
1855         g_list_prepend (decoder->priv->current_frame_events, event);
1856   }
1857
1858   if (decoder->input_segment.rate > 0.0)
1859     ret = gst_video_decoder_chain_forward (decoder, buf, FALSE);
1860   else
1861     ret = gst_video_decoder_chain_reverse (decoder, buf);
1862
1863   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1864   return ret;
1865 }
1866
1867 static GstStateChangeReturn
1868 gst_video_decoder_change_state (GstElement * element, GstStateChange transition)
1869 {
1870   GstVideoDecoder *decoder;
1871   GstVideoDecoderClass *decoder_class;
1872   GstStateChangeReturn ret;
1873
1874   decoder = GST_VIDEO_DECODER (element);
1875   decoder_class = GST_VIDEO_DECODER_GET_CLASS (element);
1876
1877   switch (transition) {
1878     case GST_STATE_CHANGE_NULL_TO_READY:
1879       /* open device/library if needed */
1880       if (decoder_class->open && !decoder_class->open (decoder))
1881         goto open_failed;
1882       break;
1883     case GST_STATE_CHANGE_READY_TO_PAUSED:
1884       /* Initialize device/library if needed */
1885       if (decoder_class->start && !decoder_class->start (decoder))
1886         goto start_failed;
1887       break;
1888     default:
1889       break;
1890   }
1891
1892   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1893
1894   switch (transition) {
1895     case GST_STATE_CHANGE_PAUSED_TO_READY:
1896       if (decoder_class->stop && !decoder_class->stop (decoder))
1897         goto stop_failed;
1898
1899       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1900       gst_video_decoder_reset (decoder, TRUE);
1901       g_list_free_full (decoder->priv->current_frame_events,
1902           (GDestroyNotify) gst_event_unref);
1903       decoder->priv->current_frame_events = NULL;
1904       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1905       break;
1906     case GST_STATE_CHANGE_READY_TO_NULL:
1907       /* close device/library if needed */
1908       if (decoder_class->close && !decoder_class->close (decoder))
1909         goto close_failed;
1910       break;
1911     default:
1912       break;
1913   }
1914
1915   return ret;
1916
1917   /* Errors */
1918 open_failed:
1919   {
1920     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
1921         ("Failed to open decoder"));
1922     return GST_STATE_CHANGE_FAILURE;
1923   }
1924
1925 start_failed:
1926   {
1927     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
1928         ("Failed to start decoder"));
1929     return GST_STATE_CHANGE_FAILURE;
1930   }
1931
1932 stop_failed:
1933   {
1934     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
1935         ("Failed to stop decoder"));
1936     return GST_STATE_CHANGE_FAILURE;
1937   }
1938
1939 close_failed:
1940   {
1941     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
1942         ("Failed to close decoder"));
1943     return GST_STATE_CHANGE_FAILURE;
1944   }
1945 }
1946
1947 static GstVideoCodecFrame *
1948 gst_video_decoder_new_frame (GstVideoDecoder * decoder)
1949 {
1950   GstVideoDecoderPrivate *priv = decoder->priv;
1951   GstVideoCodecFrame *frame;
1952
1953   frame = g_slice_new0 (GstVideoCodecFrame);
1954
1955   frame->ref_count = 1;
1956
1957   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1958   frame->system_frame_number = priv->system_frame_number;
1959   priv->system_frame_number++;
1960   frame->decode_frame_number = priv->decode_frame_number;
1961   priv->decode_frame_number++;
1962
1963   frame->dts = GST_CLOCK_TIME_NONE;
1964   frame->pts = GST_CLOCK_TIME_NONE;
1965   frame->duration = GST_CLOCK_TIME_NONE;
1966   frame->events = priv->current_frame_events;
1967   priv->current_frame_events = NULL;
1968   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1969
1970   GST_LOG_OBJECT (decoder, "Created new frame %p (sfn:%d)",
1971       frame, frame->system_frame_number);
1972
1973   return frame;
1974 }
1975
1976 static void
1977 gst_video_decoder_prepare_finish_frame (GstVideoDecoder *
1978     decoder, GstVideoCodecFrame * frame, gboolean dropping)
1979 {
1980   GstVideoDecoderPrivate *priv = decoder->priv;
1981   GList *l, *events = NULL;
1982
1983 #ifndef GST_DISABLE_GST_DEBUG
1984   GST_LOG_OBJECT (decoder, "n %d in %" G_GSIZE_FORMAT " out %" G_GSIZE_FORMAT,
1985       g_list_length (priv->frames),
1986       gst_adapter_available (priv->input_adapter),
1987       gst_adapter_available (priv->output_adapter));
1988 #endif
1989
1990   GST_LOG_OBJECT (decoder,
1991       "finish frame %p (#%d) sync:%d PTS:%" GST_TIME_FORMAT " DTS:%"
1992       GST_TIME_FORMAT,
1993       frame, frame->system_frame_number,
1994       GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame), GST_TIME_ARGS (frame->pts),
1995       GST_TIME_ARGS (frame->dts));
1996
1997   /* Push all pending events that arrived before this frame */
1998   for (l = priv->frames; l; l = l->next) {
1999     GstVideoCodecFrame *tmp = l->data;
2000
2001     if (tmp->events) {
2002       events = g_list_concat (events, tmp->events);
2003       tmp->events = NULL;
2004     }
2005
2006     if (tmp == frame)
2007       break;
2008   }
2009
2010   for (l = g_list_last (events); l; l = g_list_previous (l)) {
2011     GST_LOG_OBJECT (decoder, "pushing %s event", GST_EVENT_TYPE_NAME (l->data));
2012     gst_video_decoder_push_event (decoder, l->data);
2013   }
2014   g_list_free (events);
2015
2016   /* Check if the data should not be displayed. For example altref/invisible
2017    * frame in vp8. In this case we should not update the timestamps. */
2018   if (GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame))
2019     return;
2020
2021   /* If the frame is meant to be output but we don't have an output_buffer
2022    * we have a problem :) */
2023   if (G_UNLIKELY ((frame->output_buffer == NULL) && !dropping))
2024     goto no_output_buffer;
2025
2026   if (GST_CLOCK_TIME_IS_VALID (frame->pts)) {
2027     if (frame->pts != priv->base_timestamp) {
2028       GST_DEBUG_OBJECT (decoder,
2029           "sync timestamp %" GST_TIME_FORMAT " diff %" GST_TIME_FORMAT,
2030           GST_TIME_ARGS (frame->pts),
2031           GST_TIME_ARGS (frame->pts - decoder->output_segment.start));
2032       priv->base_timestamp = frame->pts;
2033       priv->base_picture_number = frame->decode_frame_number;
2034     }
2035   }
2036
2037   if (frame->duration == GST_CLOCK_TIME_NONE) {
2038     frame->duration = gst_video_decoder_get_frame_duration (decoder, frame);
2039     GST_LOG_OBJECT (decoder,
2040         "Guessing duration %" GST_TIME_FORMAT " for frame...",
2041         GST_TIME_ARGS (frame->duration));
2042   }
2043
2044   if (frame->pts == GST_CLOCK_TIME_NONE) {
2045     /* Last ditch timestamp guess: Just add the duration to the previous
2046      * frame */
2047     if (priv->last_timestamp_out != GST_CLOCK_TIME_NONE &&
2048         frame->duration != GST_CLOCK_TIME_NONE) {
2049       frame->pts = priv->last_timestamp_out + frame->duration;
2050       GST_LOG_OBJECT (decoder,
2051           "Guessing timestamp %" GST_TIME_FORMAT " for frame...",
2052           GST_TIME_ARGS (frame->pts));
2053     }
2054   }
2055
2056   if (GST_CLOCK_TIME_IS_VALID (priv->last_timestamp_out)) {
2057     if (frame->pts < priv->last_timestamp_out) {
2058       GST_WARNING_OBJECT (decoder,
2059           "decreasing timestamp (%" GST_TIME_FORMAT " < %"
2060           GST_TIME_FORMAT ")",
2061           GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (priv->last_timestamp_out));
2062     }
2063   }
2064
2065   if (GST_CLOCK_TIME_IS_VALID (frame->pts))
2066     priv->last_timestamp_out = frame->pts;
2067
2068   return;
2069
2070   /* ERRORS */
2071 no_output_buffer:
2072   {
2073     GST_ERROR_OBJECT (decoder, "No buffer to output !");
2074   }
2075 }
2076
2077 static void
2078 gst_video_decoder_release_frame (GstVideoDecoder * dec,
2079     GstVideoCodecFrame * frame)
2080 {
2081   GList *link;
2082
2083   /* unref once from the list */
2084   link = g_list_find (dec->priv->frames, frame);
2085   if (link) {
2086     gst_video_codec_frame_unref (frame);
2087     dec->priv->frames = g_list_delete_link (dec->priv->frames, link);
2088   }
2089
2090   /* unref because this function takes ownership */
2091   gst_video_codec_frame_unref (frame);
2092 }
2093
2094 /**
2095  * gst_video_decoder_drop_frame:
2096  * @dec: a #GstVideoDecoder
2097  * @frame: (transfer full): the #GstVideoCodecFrame to drop
2098  *
2099  * Similar to gst_video_decoder_finish_frame(), but drops @frame in any
2100  * case and posts a QoS message with the frame's details on the bus.
2101  * In any case, the frame is considered finished and released.
2102  *
2103  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
2104  */
2105 GstFlowReturn
2106 gst_video_decoder_drop_frame (GstVideoDecoder * dec, GstVideoCodecFrame * frame)
2107 {
2108   GstClockTime stream_time, jitter, earliest_time, qostime, timestamp;
2109   GstSegment *segment;
2110   GstMessage *qos_msg;
2111   gdouble proportion;
2112
2113   GST_LOG_OBJECT (dec, "drop frame %p", frame);
2114
2115   GST_VIDEO_DECODER_STREAM_LOCK (dec);
2116
2117   gst_video_decoder_prepare_finish_frame (dec, frame, TRUE);
2118
2119   GST_DEBUG_OBJECT (dec, "dropping frame %" GST_TIME_FORMAT,
2120       GST_TIME_ARGS (frame->pts));
2121
2122   dec->priv->dropped++;
2123
2124   /* post QoS message */
2125   timestamp = frame->pts;
2126   proportion = dec->priv->proportion;
2127   segment = &dec->output_segment;
2128   stream_time =
2129       gst_segment_to_stream_time (segment, GST_FORMAT_TIME, timestamp);
2130   qostime = gst_segment_to_running_time (segment, GST_FORMAT_TIME, timestamp);
2131   earliest_time = dec->priv->earliest_time;
2132   jitter = GST_CLOCK_DIFF (qostime, earliest_time);
2133   qos_msg =
2134       gst_message_new_qos (GST_OBJECT_CAST (dec), FALSE, qostime, stream_time,
2135       timestamp, GST_CLOCK_TIME_NONE);
2136   gst_message_set_qos_values (qos_msg, jitter, proportion, 1000000);
2137   gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS,
2138       dec->priv->processed, dec->priv->dropped);
2139   gst_element_post_message (GST_ELEMENT_CAST (dec), qos_msg);
2140
2141   /* now free the frame */
2142   gst_video_decoder_release_frame (dec, frame);
2143
2144   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
2145
2146   return GST_FLOW_OK;
2147 }
2148
2149 /**
2150  * gst_video_decoder_finish_frame:
2151  * @decoder: a #GstVideoDecoder
2152  * @frame: (transfer full): a decoded #GstVideoCodecFrame
2153  *
2154  * @frame should have a valid decoded data buffer, whose metadata fields
2155  * are then appropriately set according to frame data and pushed downstream.
2156  * If no output data is provided, @frame is considered skipped.
2157  * In any case, the frame is considered finished and released.
2158  *
2159  * After calling this function the output buffer of the frame is to be
2160  * considered read-only. This function will also change the metadata
2161  * of the buffer.
2162  *
2163  * Returns: a #GstFlowReturn resulting from sending data downstream
2164  */
2165 GstFlowReturn
2166 gst_video_decoder_finish_frame (GstVideoDecoder * decoder,
2167     GstVideoCodecFrame * frame)
2168 {
2169   GstFlowReturn ret = GST_FLOW_OK;
2170   GstVideoDecoderPrivate *priv = decoder->priv;
2171   GstBuffer *output_buffer;
2172
2173   GST_LOG_OBJECT (decoder, "finish frame %p", frame);
2174
2175   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2176
2177   if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
2178               && gst_pad_check_reconfigure (decoder->srcpad))))
2179     gst_video_decoder_negotiate (decoder);
2180
2181   gst_video_decoder_prepare_finish_frame (decoder, frame, FALSE);
2182   priv->processed++;
2183
2184   /* no buffer data means this frame is skipped */
2185   if (!frame->output_buffer || GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame)) {
2186     GST_DEBUG_OBJECT (decoder, "skipping frame %" GST_TIME_FORMAT,
2187         GST_TIME_ARGS (frame->pts));
2188     goto done;
2189   }
2190
2191   output_buffer = frame->output_buffer;
2192
2193   GST_BUFFER_FLAG_UNSET (output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2194
2195   /* set PTS and DTS to both the PTS for decoded frames */
2196   GST_BUFFER_PTS (output_buffer) = frame->pts;
2197   GST_BUFFER_DTS (output_buffer) = frame->pts;
2198   GST_BUFFER_DURATION (output_buffer) = frame->duration;
2199
2200   GST_BUFFER_OFFSET (output_buffer) = GST_BUFFER_OFFSET_NONE;
2201   GST_BUFFER_OFFSET_END (output_buffer) = GST_BUFFER_OFFSET_NONE;
2202
2203   if (priv->discont) {
2204     GST_BUFFER_FLAG_SET (output_buffer, GST_BUFFER_FLAG_DISCONT);
2205     priv->discont = FALSE;
2206   }
2207
2208   /* Get an additional ref to the buffer, which is going to be pushed
2209    * downstream, the original ref is owned by the frame
2210    *
2211    * FIXME: clip_and_push_buf() changes buffer metadata but the buffer
2212    * might have a refcount > 1 */
2213   output_buffer = gst_buffer_ref (output_buffer);
2214   if (decoder->output_segment.rate < 0.0) {
2215     GST_LOG_OBJECT (decoder, "queued frame");
2216     priv->output_queued = g_list_prepend (priv->output_queued, output_buffer);
2217   } else {
2218     ret = gst_video_decoder_clip_and_push_buf (decoder, output_buffer);
2219   }
2220
2221 done:
2222   gst_video_decoder_release_frame (decoder, frame);
2223   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2224   return ret;
2225 }
2226
2227
2228 /* With stream lock, takes the frame reference */
2229 static GstFlowReturn
2230 gst_video_decoder_clip_and_push_buf (GstVideoDecoder * decoder, GstBuffer * buf)
2231 {
2232   GstFlowReturn ret = GST_FLOW_OK;
2233   GstVideoDecoderPrivate *priv = decoder->priv;
2234   guint64 start, stop;
2235   guint64 cstart, cstop;
2236   GstSegment *segment;
2237   GstClockTime duration;
2238
2239   /* Check for clipping */
2240   start = GST_BUFFER_PTS (buf);
2241   duration = GST_BUFFER_DURATION (buf);
2242
2243   stop = GST_CLOCK_TIME_NONE;
2244
2245   if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (duration)) {
2246     stop = start + duration;
2247   }
2248
2249   segment = &decoder->output_segment;
2250   if (gst_segment_clip (segment, GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
2251
2252     GST_BUFFER_PTS (buf) = cstart;
2253
2254     if (stop != GST_CLOCK_TIME_NONE)
2255       GST_BUFFER_DURATION (buf) = cstop - cstart;
2256
2257     GST_LOG_OBJECT (decoder,
2258         "accepting buffer inside segment: %" GST_TIME_FORMAT " %"
2259         GST_TIME_FORMAT " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
2260         " time %" GST_TIME_FORMAT,
2261         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2262         GST_TIME_ARGS (GST_BUFFER_PTS (buf) +
2263             GST_BUFFER_DURATION (buf)),
2264         GST_TIME_ARGS (segment->start), GST_TIME_ARGS (segment->stop),
2265         GST_TIME_ARGS (segment->time));
2266   } else {
2267     GST_LOG_OBJECT (decoder,
2268         "dropping buffer outside segment: %" GST_TIME_FORMAT
2269         " %" GST_TIME_FORMAT
2270         " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
2271         " time %" GST_TIME_FORMAT,
2272         GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
2273         GST_TIME_ARGS (segment->start),
2274         GST_TIME_ARGS (segment->stop), GST_TIME_ARGS (segment->time));
2275     gst_buffer_unref (buf);
2276     goto done;
2277   }
2278
2279   /* update rate estimate */
2280   priv->bytes_out += gst_buffer_get_size (buf);
2281   if (GST_CLOCK_TIME_IS_VALID (duration)) {
2282     priv->time += duration;
2283   } else {
2284     /* FIXME : Use difference between current and previous outgoing
2285      * timestamp, and relate to difference between current and previous
2286      * bytes */
2287     /* better none than nothing valid */
2288     priv->time = GST_CLOCK_TIME_NONE;
2289   }
2290
2291   GST_DEBUG_OBJECT (decoder, "pushing buffer %p of size %" G_GSIZE_FORMAT ", "
2292       "PTS %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
2293       gst_buffer_get_size (buf),
2294       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2295       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2296
2297   /* we got data, so note things are looking up again, reduce
2298    * the error count, if there is one */
2299   if (G_UNLIKELY (priv->error_count))
2300     priv->error_count--;
2301
2302   ret = gst_pad_push (decoder->srcpad, buf);
2303
2304 done:
2305   return ret;
2306 }
2307
2308 /**
2309  * gst_video_decoder_add_to_frame:
2310  * @decoder: a #GstVideoDecoder
2311  * @n_bytes: the number of bytes to add
2312  *
2313  * Removes next @n_bytes of input data and adds it to currently parsed frame.
2314  */
2315 void
2316 gst_video_decoder_add_to_frame (GstVideoDecoder * decoder, int n_bytes)
2317 {
2318   GstVideoDecoderPrivate *priv = decoder->priv;
2319   GstBuffer *buf;
2320
2321   GST_LOG_OBJECT (decoder, "add %d bytes to frame", n_bytes);
2322
2323   if (n_bytes == 0)
2324     return;
2325
2326   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2327   if (gst_adapter_available (priv->output_adapter) == 0) {
2328     priv->frame_offset =
2329         priv->input_offset - gst_adapter_available (priv->input_adapter);
2330   }
2331   buf = gst_adapter_take_buffer (priv->input_adapter, n_bytes);
2332
2333   gst_adapter_push (priv->output_adapter, buf);
2334   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2335 }
2336
2337 static guint64
2338 gst_video_decoder_get_frame_duration (GstVideoDecoder * decoder,
2339     GstVideoCodecFrame * frame)
2340 {
2341   GstVideoCodecState *state = decoder->priv->output_state;
2342
2343   /* it's possible that we don't have a state yet when we are dropping the
2344    * initial buffers */
2345   if (state == NULL)
2346     return GST_CLOCK_TIME_NONE;
2347
2348   if (state->info.fps_d == 0 || state->info.fps_n == 0) {
2349     return GST_CLOCK_TIME_NONE;
2350   }
2351
2352   /* FIXME: For interlaced frames this needs to take into account
2353    * the number of valid fields in the frame
2354    */
2355
2356   return gst_util_uint64_scale (GST_SECOND, state->info.fps_d,
2357       state->info.fps_n);
2358 }
2359
2360 /**
2361  * gst_video_decoder_have_frame:
2362  * @decoder: a #GstVideoDecoder
2363  *
2364  * Gathers all data collected for currently parsed frame, gathers corresponding
2365  * metadata and passes it along for further processing, i.e. @handle_frame.
2366  *
2367  * Returns: a #GstFlowReturn
2368  */
2369 GstFlowReturn
2370 gst_video_decoder_have_frame (GstVideoDecoder * decoder)
2371 {
2372   GstVideoDecoderPrivate *priv = decoder->priv;
2373   GstBuffer *buffer;
2374   int n_available;
2375   GstClockTime pts, dts, duration;
2376   GstFlowReturn ret = GST_FLOW_OK;
2377
2378   GST_LOG_OBJECT (decoder, "have_frame");
2379
2380   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2381
2382   n_available = gst_adapter_available (priv->output_adapter);
2383   if (n_available) {
2384     buffer = gst_adapter_take_buffer (priv->output_adapter, n_available);
2385   } else {
2386     buffer = gst_buffer_new_and_alloc (0);
2387   }
2388
2389   priv->current_frame->input_buffer = buffer;
2390
2391   gst_video_decoder_get_timestamp_at_offset (decoder,
2392       priv->frame_offset, &pts, &dts, &duration);
2393
2394   GST_BUFFER_PTS (buffer) = pts;
2395   GST_BUFFER_DTS (buffer) = dts;
2396   GST_BUFFER_DURATION (buffer) = duration;
2397
2398   GST_LOG_OBJECT (decoder, "collected frame size %d, "
2399       "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
2400       GST_TIME_FORMAT, n_available, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts),
2401       GST_TIME_ARGS (duration));
2402
2403   /* In reverse playback, just capture and queue frames for later processing */
2404   if (decoder->output_segment.rate < 0.0) {
2405     priv->parse_gather =
2406         g_list_prepend (priv->parse_gather, priv->current_frame);
2407   } else {
2408     /* Otherwise, decode the frame, which gives away our ref */
2409     ret = gst_video_decoder_decode_frame (decoder, priv->current_frame);
2410   }
2411   /* Current frame is gone now, either way */
2412   priv->current_frame = NULL;
2413
2414   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2415
2416   return ret;
2417 }
2418
2419 /* Pass the frame in priv->current_frame through the
2420  * handle_frame() callback for decoding and passing to gvd_finish_frame(), 
2421  * or dropping by passing to gvd_drop_frame() */
2422 static GstFlowReturn
2423 gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
2424     GstVideoCodecFrame * frame)
2425 {
2426   GstVideoDecoderPrivate *priv = decoder->priv;
2427   GstVideoDecoderClass *decoder_class;
2428   GstFlowReturn ret = GST_FLOW_OK;
2429
2430   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
2431
2432   /* FIXME : This should only have to be checked once (either the subclass has an 
2433    * implementation, or it doesn't) */
2434   g_return_val_if_fail (decoder_class->handle_frame != NULL, GST_FLOW_ERROR);
2435
2436   frame->distance_from_sync = priv->distance_from_sync;
2437   priv->distance_from_sync++;
2438   frame->pts = GST_BUFFER_PTS (frame->input_buffer);
2439   frame->dts = GST_BUFFER_DTS (frame->input_buffer);
2440   frame->duration = GST_BUFFER_DURATION (frame->input_buffer);
2441
2442   /* For keyframes, PTS = DTS */
2443   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
2444     if (!GST_CLOCK_TIME_IS_VALID (frame->pts))
2445       frame->pts = frame->dts;
2446   }
2447
2448   GST_LOG_OBJECT (decoder, "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT,
2449       GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->dts));
2450   GST_LOG_OBJECT (decoder, "dist %d", frame->distance_from_sync);
2451
2452   gst_video_codec_frame_ref (frame);
2453   priv->frames = g_list_append (priv->frames, frame);
2454   frame->deadline =
2455       gst_segment_to_running_time (&decoder->input_segment, GST_FORMAT_TIME,
2456       frame->pts);
2457
2458   /* do something with frame */
2459   ret = decoder_class->handle_frame (decoder, frame);
2460   if (ret != GST_FLOW_OK)
2461     GST_DEBUG_OBJECT (decoder, "flow error %s", gst_flow_get_name (ret));
2462
2463   /* the frame has either been added to parse_gather or sent to
2464      handle frame so there is no need to unref it */
2465   return ret;
2466 }
2467
2468
2469 /**
2470  * gst_video_decoder_get_output_state:
2471  * @decoder: a #GstVideoDecoder
2472  *
2473  * Get the #GstVideoCodecState currently describing the output stream.
2474  *
2475  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
2476  */
2477 GstVideoCodecState *
2478 gst_video_decoder_get_output_state (GstVideoDecoder * decoder)
2479 {
2480   GstVideoCodecState *state = NULL;
2481
2482   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2483   if (decoder->priv->output_state)
2484     state = gst_video_codec_state_ref (decoder->priv->output_state);
2485   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2486
2487   return state;
2488 }
2489
2490 /**
2491  * gst_video_decoder_set_output_state:
2492  * @decoder: a #GstVideoDecoder
2493  * @fmt: a #GstVideoFormat
2494  * @width: The width in pixels
2495  * @height: The height in pixels
2496  * @reference: (allow-none) (transfer none): An optional reference #GstVideoCodecState
2497  *
2498  * Creates a new #GstVideoCodecState with the specified @fmt, @width and @height
2499  * as the output state for the decoder.
2500  * Any previously set output state on @decoder will be replaced by the newly
2501  * created one.
2502  *
2503  * If the subclass wishes to copy over existing fields (like pixel aspec ratio,
2504  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
2505  * @reference.
2506  *
2507  * If the subclass wishes to override some fields from the output state (like
2508  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
2509  *
2510  * The new output state will only take effect (set on pads and buffers) starting
2511  * from the next call to #gst_video_decoder_finish_frame().
2512  *
2513  * Returns: (transfer full): the newly configured output state.
2514  */
2515 GstVideoCodecState *
2516 gst_video_decoder_set_output_state (GstVideoDecoder * decoder,
2517     GstVideoFormat fmt, guint width, guint height,
2518     GstVideoCodecState * reference)
2519 {
2520   GstVideoDecoderPrivate *priv = decoder->priv;
2521   GstVideoCodecState *state;
2522
2523   GST_DEBUG_OBJECT (decoder, "fmt:%d, width:%d, height:%d, reference:%p",
2524       fmt, width, height, reference);
2525
2526   /* Create the new output state */
2527   state = _new_output_state (fmt, width, height, reference);
2528
2529   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2530   /* Replace existing output state by new one */
2531   if (priv->output_state)
2532     gst_video_codec_state_unref (priv->output_state);
2533   priv->output_state = gst_video_codec_state_ref (state);
2534
2535   priv->output_state_changed = TRUE;
2536   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2537
2538   return state;
2539 }
2540
2541
2542 /**
2543  * gst_video_decoder_get_oldest_frame:
2544  * @decoder: a #GstVideoDecoder
2545  *
2546  * Get the oldest pending unfinished #GstVideoCodecFrame
2547  *
2548  * Returns: (transfer full): oldest pending unfinished #GstVideoCodecFrame.
2549  */
2550 GstVideoCodecFrame *
2551 gst_video_decoder_get_oldest_frame (GstVideoDecoder * decoder)
2552 {
2553   GstVideoCodecFrame *frame = NULL;
2554
2555   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2556   if (decoder->priv->frames)
2557     frame = gst_video_codec_frame_ref (decoder->priv->frames->data);
2558   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2559
2560   return (GstVideoCodecFrame *) frame;
2561 }
2562
2563 /**
2564  * gst_video_decoder_get_frame:
2565  * @decoder: a #GstVideoDecoder
2566  * @frame_number: system_frame_number of a frame
2567  *
2568  * Get a pending unfinished #GstVideoCodecFrame
2569  * 
2570  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
2571  */
2572 GstVideoCodecFrame *
2573 gst_video_decoder_get_frame (GstVideoDecoder * decoder, int frame_number)
2574 {
2575   GList *g;
2576   GstVideoCodecFrame *frame = NULL;
2577
2578   GST_DEBUG_OBJECT (decoder, "frame_number : %d", frame_number);
2579
2580   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2581   for (g = decoder->priv->frames; g; g = g->next) {
2582     GstVideoCodecFrame *tmp = g->data;
2583
2584     if (tmp->system_frame_number == frame_number) {
2585       frame = gst_video_codec_frame_ref (tmp);
2586       break;
2587     }
2588   }
2589   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2590
2591   return frame;
2592 }
2593
2594 static gboolean
2595 gst_video_decoder_decide_allocation_default (GstVideoDecoder * decoder,
2596     GstQuery * query)
2597 {
2598   GstCaps *outcaps;
2599   GstBufferPool *pool = NULL;
2600   guint size, min, max;
2601   GstAllocator *allocator = NULL;
2602   GstAllocationParams params;
2603   GstStructure *config;
2604   gboolean update_pool, update_allocator;
2605   GstVideoInfo vinfo;
2606
2607   gst_query_parse_allocation (query, &outcaps, NULL);
2608   gst_video_info_init (&vinfo);
2609   gst_video_info_from_caps (&vinfo, outcaps);
2610
2611   /* we got configuration from our peer or the decide_allocation method,
2612    * parse them */
2613   if (gst_query_get_n_allocation_params (query) > 0) {
2614     /* try the allocator */
2615     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2616     update_allocator = TRUE;
2617   } else {
2618     allocator = NULL;
2619     gst_allocation_params_init (&params);
2620     update_allocator = FALSE;
2621   }
2622
2623   if (gst_query_get_n_allocation_pools (query) > 0) {
2624     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
2625     size = MAX (size, vinfo.size);
2626     update_pool = TRUE;
2627   } else {
2628     pool = NULL;
2629     size = vinfo.size;
2630     min = max = 0;
2631
2632     update_pool = FALSE;
2633   }
2634
2635   if (pool == NULL) {
2636     /* no pool, we can make our own */
2637     GST_DEBUG_OBJECT (decoder, "no pool, making new pool");
2638     pool = gst_video_buffer_pool_new ();
2639   }
2640
2641   /* now configure */
2642   config = gst_buffer_pool_get_config (pool);
2643   gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
2644   gst_buffer_pool_config_set_allocator (config, allocator, &params);
2645   gst_buffer_pool_set_config (pool, config);
2646
2647   if (update_allocator)
2648     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
2649   else
2650     gst_query_add_allocation_param (query, allocator, &params);
2651   if (allocator)
2652     gst_object_unref (allocator);
2653
2654   if (update_pool)
2655     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
2656   else
2657     gst_query_add_allocation_pool (query, pool, size, min, max);
2658
2659   if (pool)
2660     gst_object_unref (pool);
2661
2662   return TRUE;
2663 }
2664
2665 static gboolean
2666 gst_video_decoder_propose_allocation_default (GstVideoDecoder * decoder,
2667     GstQuery * query)
2668 {
2669   return TRUE;
2670 }
2671
2672 /**
2673  * gst_video_decoder_negotiate:
2674  * @decoder: a #GstVideoDecoder
2675  *
2676  * Negotiate with downstreame elements to currently configured #GstVideoCodecState.
2677  *
2678  * Returns: #TRUE if the negotiation succeeded, else #FALSE.
2679  */
2680 gboolean
2681 gst_video_decoder_negotiate (GstVideoDecoder * decoder)
2682 {
2683   GstVideoCodecState *state = decoder->priv->output_state;
2684   GstVideoDecoderClass *klass;
2685   GstQuery *query = NULL;
2686   GstBufferPool *pool = NULL;
2687   GstAllocator *allocator;
2688   GstAllocationParams params;
2689   gboolean ret = TRUE;
2690
2691   g_return_val_if_fail (GST_VIDEO_INFO_WIDTH (&state->info) != 0, FALSE);
2692   g_return_val_if_fail (GST_VIDEO_INFO_HEIGHT (&state->info) != 0, FALSE);
2693
2694   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2695
2696   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
2697
2698   GST_DEBUG_OBJECT (decoder, "output_state par %d/%d fps %d/%d",
2699       state->info.par_n, state->info.par_d,
2700       state->info.fps_n, state->info.fps_d);
2701
2702   if (G_UNLIKELY (state->caps == NULL))
2703     state->caps = gst_video_info_to_caps (&state->info);
2704
2705   GST_DEBUG_OBJECT (decoder, "setting caps %" GST_PTR_FORMAT, state->caps);
2706
2707   ret = gst_pad_set_caps (decoder->srcpad, state->caps);
2708   if (!ret)
2709     goto done;
2710   decoder->priv->output_state_changed = FALSE;
2711
2712   /* Negotiate pool */
2713   query = gst_query_new_allocation (state->caps, TRUE);
2714
2715   if (!gst_pad_peer_query (decoder->srcpad, query)) {
2716     GST_DEBUG_OBJECT (decoder, "didn't get downstream ALLOCATION hints");
2717   }
2718
2719   g_assert (klass->decide_allocation != NULL);
2720   ret = klass->decide_allocation (decoder, query);
2721
2722   GST_DEBUG_OBJECT (decoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
2723       query);
2724
2725   if (!ret)
2726     goto no_decide_allocation;
2727
2728   /* we got configuration from our peer or the decide_allocation method,
2729    * parse them */
2730   if (gst_query_get_n_allocation_params (query) > 0) {
2731     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2732   } else {
2733     allocator = NULL;
2734     gst_allocation_params_init (&params);
2735   }
2736
2737   if (gst_query_get_n_allocation_pools (query) > 0)
2738     gst_query_parse_nth_allocation_pool (query, 0, &pool, NULL, NULL, NULL);
2739   if (!pool) {
2740     if (allocator)
2741       gst_object_unref (allocator);
2742     ret = FALSE;
2743     goto no_decide_allocation;
2744   }
2745
2746   if (decoder->priv->allocator)
2747     gst_object_unref (decoder->priv->allocator);
2748   decoder->priv->allocator = allocator;
2749   decoder->priv->params = params;
2750
2751   if (decoder->priv->pool) {
2752     gst_buffer_pool_set_active (decoder->priv->pool, FALSE);
2753     gst_object_unref (decoder->priv->pool);
2754   }
2755   decoder->priv->pool = pool;
2756
2757   /* and activate */
2758   gst_buffer_pool_set_active (pool, TRUE);
2759
2760 done:
2761   if (query)
2762     gst_query_unref (query);
2763
2764   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2765
2766   return ret;
2767
2768   /* Errors */
2769 no_decide_allocation:
2770   {
2771     GST_WARNING_OBJECT (decoder, "Subclass failed to decide allocation");
2772     goto done;
2773   }
2774 }
2775
2776 /**
2777  * gst_video_decoder_allocate_output_buffer:
2778  * @decoder: a #GstVideoDecoder
2779  *
2780  * Helper function that allocates a buffer to hold a video frame for @decoder's
2781  * current #GstVideoCodecState.
2782  *
2783  * Returns: (transfer full): allocated buffer
2784  */
2785 GstBuffer *
2786 gst_video_decoder_allocate_output_buffer (GstVideoDecoder * decoder)
2787 {
2788   GstBuffer *buffer;
2789
2790   GST_DEBUG ("alloc src buffer");
2791
2792   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2793   if (G_UNLIKELY (decoder->priv->output_state_changed
2794           || (decoder->priv->output_state
2795               && gst_pad_check_reconfigure (decoder->srcpad))))
2796     gst_video_decoder_negotiate (decoder);
2797
2798   gst_buffer_pool_acquire_buffer (decoder->priv->pool, &buffer, NULL);
2799
2800   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2801
2802   return buffer;
2803 }
2804
2805 /**
2806  * gst_video_decoder_allocate_output_frame:
2807  * @decoder: a #GstVideoDecoder
2808  * @frame: a #GstVideoCodecFrame
2809  *
2810  * Helper function that allocates a buffer to hold a video frame for @decoder's
2811  * current #GstVideoCodecState.  Subclass should already have configured video
2812  * state and set src pad caps.
2813  *
2814  * The buffer allocated here is owned by the frame and you should only
2815  * keep references to the frame, not the buffer.
2816  *
2817  * Returns: %GST_FLOW_OK if an output buffer could be allocated
2818  */
2819 GstFlowReturn
2820 gst_video_decoder_allocate_output_frame (GstVideoDecoder *
2821     decoder, GstVideoCodecFrame * frame)
2822 {
2823   GstFlowReturn flow_ret;
2824   GstVideoCodecState *state = decoder->priv->output_state;
2825   int num_bytes = GST_VIDEO_INFO_SIZE (&state->info);
2826
2827   g_return_val_if_fail (num_bytes != 0, GST_FLOW_ERROR);
2828   g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
2829
2830   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2831   if (G_UNLIKELY (decoder->priv->output_state_changed
2832           || (decoder->priv->output_state
2833               && gst_pad_check_reconfigure (decoder->srcpad))))
2834     gst_video_decoder_negotiate (decoder);
2835
2836   GST_LOG_OBJECT (decoder, "alloc buffer size %d", num_bytes);
2837
2838   flow_ret = gst_buffer_pool_acquire_buffer (decoder->priv->pool,
2839       &frame->output_buffer, NULL);
2840
2841   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2842
2843   return flow_ret;
2844 }
2845
2846 /**
2847  * gst_video_decoder_get_max_decode_time:
2848  * @decoder: a #GstVideoDecoder
2849  * @frame: a #GstVideoCodecFrame
2850  *
2851  * Determines maximum possible decoding time for @frame that will
2852  * allow it to decode and arrive in time (as determined by QoS events).
2853  * In particular, a negative result means decoding in time is no longer possible
2854  * and should therefore occur as soon/skippy as possible.
2855  *
2856  * Returns: max decoding time.
2857  */
2858 GstClockTimeDiff
2859 gst_video_decoder_get_max_decode_time (GstVideoDecoder *
2860     decoder, GstVideoCodecFrame * frame)
2861 {
2862   GstClockTimeDiff deadline;
2863   GstClockTime earliest_time;
2864
2865   GST_OBJECT_LOCK (decoder);
2866   earliest_time = decoder->priv->earliest_time;
2867   if (GST_CLOCK_TIME_IS_VALID (earliest_time)
2868       && GST_CLOCK_TIME_IS_VALID (frame->deadline))
2869     deadline = GST_CLOCK_DIFF (earliest_time, frame->deadline);
2870   else
2871     deadline = G_MAXINT64;
2872
2873   GST_LOG_OBJECT (decoder, "earliest %" GST_TIME_FORMAT
2874       ", frame deadline %" GST_TIME_FORMAT ", deadline %" GST_TIME_FORMAT,
2875       GST_TIME_ARGS (earliest_time), GST_TIME_ARGS (frame->deadline),
2876       GST_TIME_ARGS (deadline));
2877
2878   GST_OBJECT_UNLOCK (decoder);
2879
2880   return deadline;
2881 }
2882
2883 GstFlowReturn
2884 _gst_video_decoder_error (GstVideoDecoder * dec, gint weight,
2885     GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file,
2886     const gchar * function, gint line)
2887 {
2888   if (txt)
2889     GST_WARNING_OBJECT (dec, "error: %s", txt);
2890   if (dbg)
2891     GST_WARNING_OBJECT (dec, "error: %s", dbg);
2892   dec->priv->error_count += weight;
2893   dec->priv->discont = TRUE;
2894   if (dec->priv->max_errors < dec->priv->error_count) {
2895     gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR,
2896         domain, code, txt, dbg, file, function, line);
2897     return GST_FLOW_ERROR;
2898   } else {
2899     return GST_FLOW_OK;
2900   }
2901 }
2902
2903 /**
2904  * gst_video_decoder_set_max_errors:
2905  * @dec: a #GstVideoDecoder
2906  * @num: max tolerated errors
2907  *
2908  * Sets numbers of tolerated decoder errors, where a tolerated one is then only
2909  * warned about, but more than tolerated will lead to fatal error.  Default
2910  * is set to GST_VIDEO_DECODER_MAX_ERRORS.
2911  */
2912 void
2913 gst_video_decoder_set_max_errors (GstVideoDecoder * dec, gint num)
2914 {
2915   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
2916
2917   dec->priv->max_errors = num;
2918 }
2919
2920 /**
2921  * gst_video_decoder_get_max_errors:
2922  * @dec: a #GstVideoDecoder
2923  *
2924  * Returns: currently configured decoder tolerated error count.
2925  */
2926 gint
2927 gst_video_decoder_get_max_errors (GstVideoDecoder * dec)
2928 {
2929   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
2930
2931   return dec->priv->max_errors;
2932 }
2933
2934 /**
2935  * gst_video_decoder_set_packetized:
2936  * @decoder: a #GstVideoDecoder
2937  * @packetized: whether the input data should be considered as packetized.
2938  *
2939  * Allows baseclass to consider input data as packetized or not. If the
2940  * input is packetized, then the @parse method will not be called.
2941  */
2942 void
2943 gst_video_decoder_set_packetized (GstVideoDecoder * decoder,
2944     gboolean packetized)
2945 {
2946   decoder->priv->packetized = packetized;
2947 }
2948
2949 /**
2950  * gst_video_decoder_get_packetized:
2951  * @decoder: a #GstVideoDecoder
2952  *
2953  * Queries whether input data is considered packetized or not by the
2954  * base class.
2955  *
2956  * Returns: TRUE if input data is considered packetized.
2957  */
2958 gboolean
2959 gst_video_decoder_get_packetized (GstVideoDecoder * decoder)
2960 {
2961   return decoder->priv->packetized;
2962 }
2963
2964 /**
2965  * gst_video_decoder_set_estimate_rate:
2966  * @dec: a #GstVideoDecoder
2967  * @enabled: whether to enable byte to time conversion
2968  *
2969  * Allows baseclass to perform byte to time estimated conversion.
2970  */
2971 void
2972 gst_video_decoder_set_estimate_rate (GstVideoDecoder * dec, gboolean enabled)
2973 {
2974   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
2975
2976   dec->priv->do_estimate_rate = enabled;
2977 }
2978
2979 /**
2980  * gst_video_decoder_get_estimate_rate:
2981  * @dec: a #GstVideoDecoder
2982  *
2983  * Returns: currently configured byte to time conversion setting
2984  */
2985 gboolean
2986 gst_video_decoder_get_estimate_rate (GstVideoDecoder * dec)
2987 {
2988   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
2989
2990   return dec->priv->do_estimate_rate;
2991 }
2992
2993 /**
2994  * gst_video_decoder_set_latency:
2995  * @decoder: a #GstVideoDecoder
2996  * @min_latency: minimum latency
2997  * @max_latency: maximum latency
2998  *
2999  * Lets #GstVideoDecoder sub-classes tell the baseclass what the decoder
3000  * latency is. Will also post a LATENCY message on the bus so the pipeline
3001  * can reconfigure its global latency.
3002  */
3003 void
3004 gst_video_decoder_set_latency (GstVideoDecoder * decoder,
3005     GstClockTime min_latency, GstClockTime max_latency)
3006 {
3007   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
3008   g_return_if_fail (max_latency >= min_latency);
3009
3010   GST_OBJECT_LOCK (decoder);
3011   decoder->priv->min_latency = min_latency;
3012   decoder->priv->max_latency = max_latency;
3013   GST_OBJECT_UNLOCK (decoder);
3014
3015   gst_element_post_message (GST_ELEMENT_CAST (decoder),
3016       gst_message_new_latency (GST_OBJECT_CAST (decoder)));
3017 }
3018
3019 /**
3020  * gst_video_decoder_get_latency:
3021  * @decoder: a #GstVideoDecoder
3022  * @min_latency: (out) (allow-none): address of variable in which to store the
3023  *     configured minimum latency, or %NULL
3024  * @max_latency: (out) (allow-none): address of variable in which to store the
3025  *     configured mximum latency, or %NULL
3026  *
3027  * Query the configured decoder latency. Results will be returned via
3028  * @min_latency and @max_latency.
3029  */
3030 void
3031 gst_video_decoder_get_latency (GstVideoDecoder * decoder,
3032     GstClockTime * min_latency, GstClockTime * max_latency)
3033 {
3034   GST_OBJECT_LOCK (decoder);
3035   if (min_latency)
3036     *min_latency = decoder->priv->min_latency;
3037   if (max_latency)
3038     *max_latency = decoder->priv->max_latency;
3039   GST_OBJECT_UNLOCK (decoder);
3040 }