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