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