videodecoder: Add properties to automatically request sync points and vfunc to allow...
[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  * @title: GstVideoDecoder
28  * @short_description: Base class for video decoders
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
34  * follows:
35  *
36  * ## Configuration
37  *
38  *   * Initially, GstVideoDecoder calls @start when the decoder element
39  *     is activated, which allows the subclass to perform any global setup.
40  *
41  *   * GstVideoDecoder calls @set_format to inform the subclass of caps
42  *     describing input video data that it is about to receive, including
43  *     possibly configuration data.
44  *     While unlikely, it might be called more than once, if changing input
45  *     parameters require reconfiguration.
46  *
47  *   * Incoming data buffers are processed as needed, described in Data
48  *     Processing below.
49  *
50  *   * GstVideoDecoder calls @stop at end of all processing.
51  *
52  * ## Data processing
53  *
54  *   * The base class gathers input data, and optionally allows subclass
55  *     to parse this into subsequently manageable chunks, typically
56  *     corresponding to and referred to as 'frames'.
57  *
58  *   * Each input frame is provided in turn to the subclass' @handle_frame
59  *     callback.
60  *   * When the subclass enables the subframe mode with `gst_video_decoder_set_subframe_mode`,
61  *     the base class will provide to the subclass the same input frame with
62  *     different input buffers to the subclass @handle_frame
63  *     callback. During this call, the subclass needs to take
64  *     ownership of the input_buffer as @GstVideoCodecFrame.input_buffer
65  *     will have been changed before the next subframe buffer is received.
66  *     The subclass will call `gst_video_decoder_have_last_subframe`
67  *     when a new input frame can be created by the base class.
68  *     Every subframe will share the same @GstVideoCodecFrame.output_buffer
69  *     to write the decoding result. The subclass is responsible to protect
70  *     its access.
71  *
72  *   * If codec processing results in decoded data, the subclass should call
73  *     @gst_video_decoder_finish_frame to have decoded data pushed
74  *     downstream. In subframe mode
75  *     the subclass should call @gst_video_decoder_finish_subframe until the
76  *     last subframe where it should call @gst_video_decoder_finish_frame.
77  *     The subclass can detect the last subframe using GST_VIDEO_BUFFER_FLAG_MARKER
78  *     on buffers or using its own logic to collect the subframes.
79  *     In case of decoding failure, the subclass must call
80  *     @gst_video_decoder_drop_frame or @gst_video_decoder_drop_subframe,
81  *     to allow the base class to do timestamp and offset tracking, and possibly
82  *     to requeue the frame for a later attempt in the case of reverse playback.
83  *
84  * ## Shutdown phase
85  *
86  *   * The GstVideoDecoder class calls @stop to inform the subclass that data
87  *     parsing will be stopped.
88  *
89  * ## Additional Notes
90  *
91  *   * Seeking/Flushing
92  *
93  *     * When the pipeline is seeked or otherwise flushed, the subclass is
94  *       informed via a call to its @reset callback, with the hard parameter
95  *       set to true. This indicates the subclass should drop any internal data
96  *       queues and timestamps and prepare for a fresh set of buffers to arrive
97  *       for parsing and decoding.
98  *
99  *   * End Of Stream
100  *
101  *     * At end-of-stream, the subclass @parse function may be called some final
102  *       times with the at_eos parameter set to true, indicating that the element
103  *       should not expect any more data to be arriving, and it should parse and
104  *       remaining frames and call gst_video_decoder_have_frame() if possible.
105  *
106  * The subclass is responsible for providing pad template caps for
107  * source and sink pads. The pads need to be named "sink" and "src". It also
108  * needs to provide information about the output caps, when they are known.
109  * This may be when the base class calls the subclass' @set_format function,
110  * though it might be during decoding, before calling
111  * @gst_video_decoder_finish_frame. This is done via
112  * @gst_video_decoder_set_output_state
113  *
114  * The subclass is also responsible for providing (presentation) timestamps
115  * (likely based on corresponding input ones).  If that is not applicable
116  * or possible, the base class provides limited framerate based interpolation.
117  *
118  * Similarly, the base class provides some limited (legacy) seeking support
119  * if specifically requested by the subclass, as full-fledged support
120  * should rather be left to upstream demuxer, parser or alike.  This simple
121  * approach caters for seeking and duration reporting using estimated input
122  * bitrates. To enable it, a subclass should call
123  * @gst_video_decoder_set_estimate_rate to enable handling of incoming
124  * byte-streams.
125  *
126  * The base class provides some support for reverse playback, in particular
127  * in case incoming data is not packetized or upstream does not provide
128  * fragments on keyframe boundaries.  However, the subclass should then be
129  * prepared for the parsing and frame processing stage to occur separately
130  * (in normal forward processing, the latter immediately follows the former),
131  * The subclass also needs to ensure the parsing stage properly marks
132  * keyframes, unless it knows the upstream elements will do so properly for
133  * incoming data.
134  *
135  * The bare minimum that a functional subclass needs to implement is:
136  *
137  *   * Provide pad templates
138  *   * Inform the base class of output caps via
139  *      @gst_video_decoder_set_output_state
140  *
141  *   * Parse input data, if it is not considered packetized from upstream
142  *      Data will be provided to @parse which should invoke
143  *      @gst_video_decoder_add_to_frame and @gst_video_decoder_have_frame to
144  *      separate the data belonging to each video frame.
145  *
146  *   * Accept data in @handle_frame and provide decoded results to
147  *      @gst_video_decoder_finish_frame, or call @gst_video_decoder_drop_frame.
148  */
149
150 #ifdef HAVE_CONFIG_H
151 #include "config.h"
152 #endif
153
154 /* TODO
155  *
156  * * Add a flag/boolean for I-frame-only/image decoders so we can do extra
157  *   features, like applying QoS on input (as opposed to after the frame is
158  *   decoded).
159  * * Add a flag/boolean for decoders that require keyframes, so the base
160  *   class can automatically discard non-keyframes before one has arrived
161  * * Detect reordered frame/timestamps and fix the pts/dts
162  * * Support for GstIndex (or shall we not care ?)
163  * * Calculate actual latency based on input/output timestamp/frame_number
164  *   and if it exceeds the recorded one, save it and emit a GST_MESSAGE_LATENCY
165  * * Emit latency message when it changes
166  *
167  */
168
169 /* Implementation notes:
170  * The Video Decoder base class operates in 2 primary processing modes, depending
171  * on whether forward or reverse playback is requested.
172  *
173  * Forward playback:
174  *   * Incoming buffer -> @parse() -> add_to_frame()/have_frame() ->
175  *     handle_frame() -> push downstream
176  *
177  * Reverse playback is more complicated, since it involves gathering incoming
178  * data regions as we loop backwards through the upstream data. The processing
179  * concept (using incoming buffers as containing one frame each to simplify
180  * things) is:
181  *
182  * Upstream data we want to play:
183  *  Buffer encoded order:  1  2  3  4  5  6  7  8  9  EOS
184  *  Keyframe flag:            K        K
185  *  Groupings:             AAAAAAA  BBBBBBB  CCCCCCC
186  *
187  * Input:
188  *  Buffer reception order:  7  8  9  4  5  6  1  2  3  EOS
189  *  Keyframe flag:                       K        K
190  *  Discont flag:            D        D        D
191  *
192  * - Each Discont marks a discont in the decoding order.
193  * - The keyframes mark where we can start decoding.
194  *
195  * Initially, we prepend incoming buffers to the gather queue. Whenever the
196  * discont flag is set on an incoming buffer, the gather queue is flushed out
197  * before the new buffer is collected.
198  *
199  * The above data will be accumulated in the gather queue like this:
200  *
201  *   gather queue:  9  8  7
202  *                        D
203  *
204  * When buffer 4 is received (with a DISCONT), we flush the gather queue like
205  * this:
206  *
207  *   while (gather)
208  *     take head of queue and prepend to parse queue (this reverses the
209  *     sequence, so parse queue is 7 -> 8 -> 9)
210  *
211  *   Next, we process the parse queue, which now contains all un-parsed packets
212  *   (including any leftover ones from the previous decode section)
213  *
214  *   for each buffer now in the parse queue:
215  *     Call the subclass parse function, prepending each resulting frame to
216  *     the parse_gather queue. Buffers which precede the first one that
217  *     produces a parsed frame are retained in the parse queue for
218  *     re-processing on the next cycle of parsing.
219  *
220  *   The parse_gather queue now contains frame objects ready for decoding,
221  *   in reverse order.
222  *   parse_gather: 9 -> 8 -> 7
223  *
224  *   while (parse_gather)
225  *     Take the head of the queue and prepend it to the decode queue
226  *     If the frame was a keyframe, process the decode queue
227  *   decode is now 7-8-9
228  *
229  *  Processing the decode queue results in frames with attached output buffers
230  *  stored in the 'output_queue' ready for outputting in reverse order.
231  *
232  * After we flushed the gather queue and parsed it, we add 4 to the (now empty)
233  * gather queue. We get the following situation:
234  *
235  *  gather queue:    4
236  *  decode queue:    7  8  9
237  *
238  * After we received 5 (Keyframe) and 6:
239  *
240  *  gather queue:    6  5  4
241  *  decode queue:    7  8  9
242  *
243  * When we receive 1 (DISCONT) which triggers a flush of the gather queue:
244  *
245  *   Copy head of the gather queue (6) to decode queue:
246  *
247  *    gather queue:    5  4
248  *    decode queue:    6  7  8  9
249  *
250  *   Copy head of the gather queue (5) to decode queue. This is a keyframe so we
251  *   can start decoding.
252  *
253  *    gather queue:    4
254  *    decode queue:    5  6  7  8  9
255  *
256  *   Decode frames in decode queue, store raw decoded data in output queue, we
257  *   can take the head of the decode queue and prepend the decoded result in the
258  *   output queue:
259  *
260  *    gather queue:    4
261  *    decode queue:
262  *    output queue:    9  8  7  6  5
263  *
264  *   Now output all the frames in the output queue, picking a frame from the
265  *   head of the queue.
266  *
267  *   Copy head of the gather queue (4) to decode queue, we flushed the gather
268  *   queue and can now store input buffer in the gather queue:
269  *
270  *    gather queue:    1
271  *    decode queue:    4
272  *
273  *  When we receive EOS, the queue looks like:
274  *
275  *    gather queue:    3  2  1
276  *    decode queue:    4
277  *
278  *  Fill decode queue, first keyframe we copy is 2:
279  *
280  *    gather queue:    1
281  *    decode queue:    2  3  4
282  *
283  *  Decoded output:
284  *
285  *    gather queue:    1
286  *    decode queue:
287  *    output queue:    4  3  2
288  *
289  *  Leftover buffer 1 cannot be decoded and must be discarded.
290  */
291
292 #include "gstvideodecoder.h"
293 #include "gstvideoutils.h"
294 #include "gstvideoutilsprivate.h"
295
296 #include <gst/video/video.h>
297 #include <gst/video/video-event.h>
298 #include <gst/video/gstvideopool.h>
299 #include <gst/video/gstvideometa.h>
300 #include <string.h>
301
302 GST_DEBUG_CATEGORY (videodecoder_debug);
303 #define GST_CAT_DEFAULT videodecoder_debug
304
305 /* properties */
306 #define DEFAULT_QOS                 TRUE
307 #define DEFAULT_MAX_ERRORS          GST_VIDEO_DECODER_MAX_ERRORS
308 #define DEFAULT_MIN_FORCE_KEY_UNIT_INTERVAL 0
309 #define DEFAULT_DISCARD_CORRUPTED_FRAMES FALSE
310 #define DEFAULT_AUTOMATIC_REQUEST_SYNC_POINTS FALSE
311 #define DEFAULT_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS (GST_VIDEO_DECODER_REQUEST_SYNC_POINT_DISCARD_INPUT | GST_VIDEO_DECODER_REQUEST_SYNC_POINT_CORRUPT_OUTPUT)
312
313 /* Used for request_sync_point_frame_number. These are out of range for the
314  * frame numbers and can be given special meaning */
315 #define REQUEST_SYNC_POINT_PENDING G_MAXUINT + 1
316 #define REQUEST_SYNC_POINT_UNSET G_MAXUINT64
317
318 enum
319 {
320   PROP_0,
321   PROP_QOS,
322   PROP_MAX_ERRORS,
323   PROP_MIN_FORCE_KEY_UNIT_INTERVAL,
324   PROP_DISCARD_CORRUPTED_FRAMES,
325   PROP_AUTOMATIC_REQUEST_SYNC_POINTS,
326   PROP_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS,
327 };
328
329 struct _GstVideoDecoderPrivate
330 {
331   /* FIXME introduce a context ? */
332
333   GstBufferPool *pool;
334   GstAllocator *allocator;
335   GstAllocationParams params;
336
337   /* parse tracking */
338   /* input data */
339   GstAdapter *input_adapter;
340   /* assembles current frame */
341   GstAdapter *output_adapter;
342
343   /* Whether we attempt to convert newsegment from bytes to
344    * time using a bitrate estimation */
345   gboolean do_estimate_rate;
346
347   /* Whether input is considered packetized or not */
348   gboolean packetized;
349
350   /* whether input is considered as subframes */
351   gboolean subframe_mode;
352
353   /* Error handling */
354   gint max_errors;
355   gint error_count;
356   gboolean had_output_data;
357   gboolean had_input_data;
358
359   gboolean needs_format;
360   /* input_segment are output_segment identical */
361   gboolean in_out_segment_sync;
362
363   /* TRUE if we have an active set of instant rate flags */
364   gboolean decode_flags_override;
365   GstSegmentFlags decode_flags;
366
367   /* ... being tracked here;
368    * only available during parsing or when doing subframe decoding */
369   GstVideoCodecFrame *current_frame;
370   /* events that should apply to the current frame */
371   /* FIXME 2.0: Use a GQueue or similar, see GstVideoCodecFrame::events */
372   GList *current_frame_events;
373   /* events that should be pushed before the next frame */
374   /* FIXME 2.0: Use a GQueue or similar, see GstVideoCodecFrame::events */
375   GList *pending_events;
376
377   /* relative offset of input data */
378   guint64 input_offset;
379   /* relative offset of frame */
380   guint64 frame_offset;
381   /* tracking ts and offsets */
382   GQueue timestamps;
383
384   /* last outgoing ts */
385   GstClockTime last_timestamp_out;
386   /* incoming pts - dts */
387   GstClockTime pts_delta;
388   gboolean reordered_output;
389
390   /* FIXME: Consider using a GQueue or other better fitting data structure */
391   /* reverse playback */
392   /* collect input */
393   GList *gather;
394   /* to-be-parsed */
395   GList *parse;
396   /* collected parsed frames */
397   GList *parse_gather;
398   /* frames to be handled == decoded */
399   GList *decode;
400   /* collected output - of buffer objects, not frames */
401   GList *output_queued;
402
403
404   /* base_picture_number is the picture number of the reference picture */
405   guint64 base_picture_number;
406   /* combine with base_picture_number, framerate and calcs to yield (presentation) ts */
407   GstClockTime base_timestamp;
408
409   /* Properties */
410   GstClockTime min_force_key_unit_interval;
411   gboolean discard_corrupted_frames;
412
413   /* Key unit related state */
414   gboolean needs_sync_point;
415   GstVideoDecoderRequestSyncPointFlags request_sync_point_flags;
416   guint64 request_sync_point_frame_number;
417   GstClockTime last_force_key_unit_time;
418   /* -1 if we saw no sync point yet */
419   guint64 distance_from_sync;
420
421   gboolean automatic_request_sync_points;
422   GstVideoDecoderRequestSyncPointFlags automatic_request_sync_point_flags;
423
424   guint32 system_frame_number;
425   guint32 decode_frame_number;
426
427   GQueue frames;                /* Protected with OBJECT_LOCK */
428   GstVideoCodecState *input_state;
429   GstVideoCodecState *output_state;     /* OBJECT_LOCK and STREAM_LOCK */
430   gboolean output_state_changed;
431
432   /* QoS properties */
433   gboolean do_qos;
434   gdouble proportion;           /* OBJECT_LOCK */
435   GstClockTime earliest_time;   /* OBJECT_LOCK */
436   GstClockTime qos_frame_duration;      /* OBJECT_LOCK */
437   gboolean discont;
438   /* qos messages: frames dropped/processed */
439   guint dropped;
440   guint processed;
441
442   /* Outgoing byte size ? */
443   gint64 bytes_out;
444   gint64 time;
445
446   gint64 min_latency;
447   gint64 max_latency;
448
449   /* upstream stream tags (global tags are passed through as-is) */
450   GstTagList *upstream_tags;
451
452   /* subclass tags */
453   GstTagList *tags;
454   GstTagMergeMode tags_merge_mode;
455
456   gboolean tags_changed;
457
458   /* flags */
459   gboolean use_default_pad_acceptcaps;
460
461 #ifndef GST_DISABLE_DEBUG
462   /* Diagnostic time for reporting the time
463    * from flush to first output */
464   GstClockTime last_reset_time;
465 #endif
466 };
467
468 static GstElementClass *parent_class = NULL;
469 static gint private_offset = 0;
470
471 /* cached quark to avoid contention on the global quark table lock */
472 #define META_TAG_VIDEO meta_tag_video_quark
473 static GQuark meta_tag_video_quark;
474
475 static void gst_video_decoder_class_init (GstVideoDecoderClass * klass);
476 static void gst_video_decoder_init (GstVideoDecoder * dec,
477     GstVideoDecoderClass * klass);
478
479 static void gst_video_decoder_finalize (GObject * object);
480 static void gst_video_decoder_get_property (GObject * object, guint property_id,
481     GValue * value, GParamSpec * pspec);
482 static void gst_video_decoder_set_property (GObject * object, guint property_id,
483     const GValue * value, GParamSpec * pspec);
484
485 static gboolean gst_video_decoder_setcaps (GstVideoDecoder * dec,
486     GstCaps * caps);
487 static gboolean gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
488     GstEvent * event);
489 static gboolean gst_video_decoder_src_event (GstPad * pad, GstObject * parent,
490     GstEvent * event);
491 static GstFlowReturn gst_video_decoder_chain (GstPad * pad, GstObject * parent,
492     GstBuffer * buf);
493 static gboolean gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
494     GstQuery * query);
495 static GstStateChangeReturn gst_video_decoder_change_state (GstElement *
496     element, GstStateChange transition);
497 static gboolean gst_video_decoder_src_query (GstPad * pad, GstObject * parent,
498     GstQuery * query);
499 static void gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full,
500     gboolean flush_hard);
501
502 static GstFlowReturn gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
503     GstVideoCodecFrame * frame);
504
505 static void gst_video_decoder_push_event_list (GstVideoDecoder * decoder,
506     GList * events);
507 static GstClockTime gst_video_decoder_get_frame_duration (GstVideoDecoder *
508     decoder, GstVideoCodecFrame * frame);
509 static GstVideoCodecFrame *gst_video_decoder_new_frame (GstVideoDecoder *
510     decoder);
511 static GstFlowReturn gst_video_decoder_clip_and_push_buf (GstVideoDecoder *
512     decoder, GstBuffer * buf);
513 static GstFlowReturn gst_video_decoder_flush_parse (GstVideoDecoder * dec,
514     gboolean at_eos);
515
516 static void gst_video_decoder_clear_queues (GstVideoDecoder * dec);
517
518 static gboolean gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
519     GstEvent * event);
520 static gboolean gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
521     GstEvent * event);
522 static gboolean gst_video_decoder_decide_allocation_default (GstVideoDecoder *
523     decoder, GstQuery * query);
524 static gboolean gst_video_decoder_propose_allocation_default (GstVideoDecoder *
525     decoder, GstQuery * query);
526 static gboolean gst_video_decoder_negotiate_default (GstVideoDecoder * decoder);
527 static GstFlowReturn gst_video_decoder_parse_available (GstVideoDecoder * dec,
528     gboolean at_eos, gboolean new_buffer);
529 static gboolean gst_video_decoder_negotiate_unlocked (GstVideoDecoder *
530     decoder);
531 static gboolean gst_video_decoder_sink_query_default (GstVideoDecoder * decoder,
532     GstQuery * query);
533 static gboolean gst_video_decoder_src_query_default (GstVideoDecoder * decoder,
534     GstQuery * query);
535
536 static gboolean gst_video_decoder_transform_meta_default (GstVideoDecoder *
537     decoder, GstVideoCodecFrame * frame, GstMeta * meta);
538
539 static gboolean gst_video_decoder_handle_missing_data_default (GstVideoDecoder *
540     decoder, GstClockTime timestamp, GstClockTime duration);
541
542 static void gst_video_decoder_copy_metas (GstVideoDecoder * decoder,
543     GstVideoCodecFrame * frame, GstBuffer * src_buffer,
544     GstBuffer * dest_buffer);
545
546 static void gst_video_decoder_request_sync_point_internal (GstVideoDecoder *
547     dec, GstClockTime deadline, GstVideoDecoderRequestSyncPointFlags flags);
548
549 /* we can't use G_DEFINE_ABSTRACT_TYPE because we need the klass in the _init
550  * method to get to the padtemplates */
551 GType
552 gst_video_decoder_get_type (void)
553 {
554   static gsize type = 0;
555
556   if (g_once_init_enter (&type)) {
557     GType _type;
558     static const GTypeInfo info = {
559       sizeof (GstVideoDecoderClass),
560       NULL,
561       NULL,
562       (GClassInitFunc) gst_video_decoder_class_init,
563       NULL,
564       NULL,
565       sizeof (GstVideoDecoder),
566       0,
567       (GInstanceInitFunc) gst_video_decoder_init,
568     };
569
570     _type = g_type_register_static (GST_TYPE_ELEMENT,
571         "GstVideoDecoder", &info, G_TYPE_FLAG_ABSTRACT);
572
573     private_offset =
574         g_type_add_instance_private (_type, sizeof (GstVideoDecoderPrivate));
575
576     g_once_init_leave (&type, _type);
577   }
578   return type;
579 }
580
581 static inline GstVideoDecoderPrivate *
582 gst_video_decoder_get_instance_private (GstVideoDecoder * self)
583 {
584   return (G_STRUCT_MEMBER_P (self, private_offset));
585 }
586
587 static void
588 gst_video_decoder_class_init (GstVideoDecoderClass * klass)
589 {
590   GObjectClass *gobject_class;
591   GstElementClass *gstelement_class;
592
593   gobject_class = G_OBJECT_CLASS (klass);
594   gstelement_class = GST_ELEMENT_CLASS (klass);
595
596   GST_DEBUG_CATEGORY_INIT (videodecoder_debug, "videodecoder", 0,
597       "Base Video Decoder");
598
599   parent_class = g_type_class_peek_parent (klass);
600
601   if (private_offset != 0)
602     g_type_class_adjust_private_offset (klass, &private_offset);
603
604   gobject_class->finalize = gst_video_decoder_finalize;
605   gobject_class->get_property = gst_video_decoder_get_property;
606   gobject_class->set_property = gst_video_decoder_set_property;
607
608   gstelement_class->change_state =
609       GST_DEBUG_FUNCPTR (gst_video_decoder_change_state);
610
611   klass->sink_event = gst_video_decoder_sink_event_default;
612   klass->src_event = gst_video_decoder_src_event_default;
613   klass->decide_allocation = gst_video_decoder_decide_allocation_default;
614   klass->propose_allocation = gst_video_decoder_propose_allocation_default;
615   klass->negotiate = gst_video_decoder_negotiate_default;
616   klass->sink_query = gst_video_decoder_sink_query_default;
617   klass->src_query = gst_video_decoder_src_query_default;
618   klass->transform_meta = gst_video_decoder_transform_meta_default;
619   klass->handle_missing_data = gst_video_decoder_handle_missing_data_default;
620
621   /**
622    * GstVideoDecoder:qos:
623    *
624    * If set to %TRUE the decoder will handle QoS events received
625    * from downstream elements.
626    * This includes dropping output frames which are detected as late
627    * using the metrics reported by those events.
628    *
629    * Since: 1.18
630    */
631   g_object_class_install_property (gobject_class, PROP_QOS,
632       g_param_spec_boolean ("qos", "Quality of Service",
633           "Handle Quality-of-Service events from downstream",
634           DEFAULT_QOS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
635
636   /**
637    * GstVideoDecoder:max-errors:
638    *
639    * Maximum number of tolerated consecutive decode errors. See
640    * gst_video_decoder_set_max_errors() for more details.
641    *
642    * Since: 1.18
643    */
644   g_object_class_install_property (gobject_class, PROP_MAX_ERRORS,
645       g_param_spec_int ("max-errors", "Max errors",
646           "Max consecutive decoder errors before returning flow error",
647           -1, G_MAXINT, DEFAULT_MAX_ERRORS,
648           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
649
650   /**
651    * GstVideoDecoder:min-force-key-unit-interval:
652    *
653    * Minimum interval between force-key-unit events sent upstream by the
654    * decoder. Setting this to 0 will cause every event to be handled, setting
655    * this to %GST_CLOCK_TIME_NONE will cause every event to be ignored.
656    *
657    * See gst_video_event_new_upstream_force_key_unit() for more details about
658    * force-key-unit events.
659    *
660    * Since: 1.20
661    */
662   g_object_class_install_property (gobject_class,
663       PROP_MIN_FORCE_KEY_UNIT_INTERVAL,
664       g_param_spec_uint64 ("min-force-key-unit-interval",
665           "Minimum Force Keyunit Interval",
666           "Minimum interval between force-keyunit requests in nanoseconds", 0,
667           G_MAXUINT64, DEFAULT_MIN_FORCE_KEY_UNIT_INTERVAL,
668           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
669
670   /**
671    * GstVideoDecoder:discard-corrupted-frames:
672    *
673    * If set to %TRUE the decoder will discard frames that are marked as
674    * corrupted instead of outputting them.
675    *
676    * Since: 1.20
677    */
678   g_object_class_install_property (gobject_class, PROP_DISCARD_CORRUPTED_FRAMES,
679       g_param_spec_boolean ("discard-corrupted-frames",
680           "Discard Corrupted Frames",
681           "Discard frames marked as corrupted instead of outputting them",
682           DEFAULT_DISCARD_CORRUPTED_FRAMES,
683           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
684
685   /**
686    * GstVideoDecoder:automatic-request-sync-points:
687    *
688    * If set to %TRUE the decoder will automatically request sync points when
689    * it seems like a good idea, e.g. if the first frames are not key frames or
690    * if packet loss was reported by upstream.
691    *
692    * Since: 1.20
693    */
694   g_object_class_install_property (gobject_class,
695       PROP_AUTOMATIC_REQUEST_SYNC_POINTS,
696       g_param_spec_boolean ("automatic-request-sync-points",
697           "Discard Corrupted Frames",
698           "Discard frames marked as corrupted instead of outputting them",
699           DEFAULT_AUTOMATIC_REQUEST_SYNC_POINTS,
700           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
701
702   /**
703    * GstVideoDecoder:automatic-request-sync-point-flags:
704    *
705    * GstVideoDecoderRequestSyncPointFlags to use for the automatically
706    * requested sync points if `automatic-request-sync-points` is enabled.
707    *
708    * Since: 1.20
709    */
710   g_object_class_install_property (gobject_class,
711       PROP_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS,
712       g_param_spec_flags ("automatic-request-sync-point-flags",
713           "Discard Corrupted Frames",
714           "Discard frames marked as corrupted instead of outputting them",
715           GST_TYPE_VIDEO_DECODER_REQUEST_SYNC_POINT_FLAGS,
716           DEFAULT_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS,
717           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
718
719   meta_tag_video_quark = g_quark_from_static_string (GST_META_TAG_VIDEO_STR);
720 }
721
722 static void
723 gst_video_decoder_init (GstVideoDecoder * decoder, GstVideoDecoderClass * klass)
724 {
725   GstPadTemplate *pad_template;
726   GstPad *pad;
727
728   GST_DEBUG_OBJECT (decoder, "gst_video_decoder_init");
729
730   decoder->priv = gst_video_decoder_get_instance_private (decoder);
731
732   pad_template =
733       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
734   g_return_if_fail (pad_template != NULL);
735
736   decoder->sinkpad = pad = gst_pad_new_from_template (pad_template, "sink");
737
738   gst_pad_set_chain_function (pad, GST_DEBUG_FUNCPTR (gst_video_decoder_chain));
739   gst_pad_set_event_function (pad,
740       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_event));
741   gst_pad_set_query_function (pad,
742       GST_DEBUG_FUNCPTR (gst_video_decoder_sink_query));
743   gst_element_add_pad (GST_ELEMENT (decoder), decoder->sinkpad);
744
745   pad_template =
746       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
747   g_return_if_fail (pad_template != NULL);
748
749   decoder->srcpad = pad = gst_pad_new_from_template (pad_template, "src");
750
751   gst_pad_set_event_function (pad,
752       GST_DEBUG_FUNCPTR (gst_video_decoder_src_event));
753   gst_pad_set_query_function (pad,
754       GST_DEBUG_FUNCPTR (gst_video_decoder_src_query));
755   gst_element_add_pad (GST_ELEMENT (decoder), decoder->srcpad);
756
757   gst_segment_init (&decoder->input_segment, GST_FORMAT_TIME);
758   gst_segment_init (&decoder->output_segment, GST_FORMAT_TIME);
759
760   g_rec_mutex_init (&decoder->stream_lock);
761
762   decoder->priv->input_adapter = gst_adapter_new ();
763   decoder->priv->output_adapter = gst_adapter_new ();
764   decoder->priv->packetized = TRUE;
765   decoder->priv->needs_format = FALSE;
766
767   g_queue_init (&decoder->priv->frames);
768   g_queue_init (&decoder->priv->timestamps);
769
770   /* properties */
771   decoder->priv->do_qos = DEFAULT_QOS;
772   decoder->priv->max_errors = GST_VIDEO_DECODER_MAX_ERRORS;
773
774   decoder->priv->min_latency = 0;
775   decoder->priv->max_latency = 0;
776
777   decoder->priv->automatic_request_sync_points =
778       DEFAULT_AUTOMATIC_REQUEST_SYNC_POINTS;
779   decoder->priv->automatic_request_sync_point_flags =
780       DEFAULT_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS;
781
782   gst_video_decoder_reset (decoder, TRUE, TRUE);
783 }
784
785 static GstVideoCodecState *
786 _new_input_state (GstCaps * caps)
787 {
788   GstVideoCodecState *state;
789   GstStructure *structure;
790   const GValue *codec_data;
791
792   state = g_slice_new0 (GstVideoCodecState);
793   state->ref_count = 1;
794   gst_video_info_init (&state->info);
795   if (G_UNLIKELY (!gst_video_info_from_caps (&state->info, caps)))
796     goto parse_fail;
797   state->caps = gst_caps_ref (caps);
798
799   structure = gst_caps_get_structure (caps, 0);
800
801   codec_data = gst_structure_get_value (structure, "codec_data");
802   if (codec_data && G_VALUE_TYPE (codec_data) == GST_TYPE_BUFFER)
803     state->codec_data = GST_BUFFER (g_value_dup_boxed (codec_data));
804
805   return state;
806
807 parse_fail:
808   {
809     g_slice_free (GstVideoCodecState, state);
810     return NULL;
811   }
812 }
813
814 static GstVideoCodecState *
815 _new_output_state (GstVideoFormat fmt, GstVideoInterlaceMode interlace_mode,
816     guint width, guint height, GstVideoCodecState * reference,
817     gboolean copy_interlace_mode)
818 {
819   GstVideoCodecState *state;
820
821   state = g_slice_new0 (GstVideoCodecState);
822   state->ref_count = 1;
823   gst_video_info_init (&state->info);
824   if (!gst_video_info_set_interlaced_format (&state->info, fmt, interlace_mode,
825           width, height)) {
826     g_slice_free (GstVideoCodecState, state);
827     return NULL;
828   }
829
830   if (reference) {
831     GstVideoInfo *tgt, *ref;
832
833     tgt = &state->info;
834     ref = &reference->info;
835
836     /* Copy over extra fields from reference state */
837     if (copy_interlace_mode)
838       tgt->interlace_mode = ref->interlace_mode;
839     tgt->flags = ref->flags;
840     tgt->chroma_site = ref->chroma_site;
841     tgt->colorimetry = ref->colorimetry;
842     GST_DEBUG ("reference par %d/%d fps %d/%d",
843         ref->par_n, ref->par_d, ref->fps_n, ref->fps_d);
844     tgt->par_n = ref->par_n;
845     tgt->par_d = ref->par_d;
846     tgt->fps_n = ref->fps_n;
847     tgt->fps_d = ref->fps_d;
848     tgt->views = ref->views;
849
850     GST_VIDEO_INFO_FIELD_ORDER (tgt) = GST_VIDEO_INFO_FIELD_ORDER (ref);
851
852     if (GST_VIDEO_INFO_MULTIVIEW_MODE (ref) != GST_VIDEO_MULTIVIEW_MODE_NONE) {
853       GST_VIDEO_INFO_MULTIVIEW_MODE (tgt) = GST_VIDEO_INFO_MULTIVIEW_MODE (ref);
854       GST_VIDEO_INFO_MULTIVIEW_FLAGS (tgt) =
855           GST_VIDEO_INFO_MULTIVIEW_FLAGS (ref);
856     } else {
857       /* Default to MONO, overridden as needed by sub-classes */
858       GST_VIDEO_INFO_MULTIVIEW_MODE (tgt) = GST_VIDEO_MULTIVIEW_MODE_MONO;
859       GST_VIDEO_INFO_MULTIVIEW_FLAGS (tgt) = GST_VIDEO_MULTIVIEW_FLAGS_NONE;
860     }
861   }
862
863   GST_DEBUG ("reference par %d/%d fps %d/%d",
864       state->info.par_n, state->info.par_d,
865       state->info.fps_n, state->info.fps_d);
866
867   return state;
868 }
869
870 static gboolean
871 gst_video_decoder_setcaps (GstVideoDecoder * decoder, GstCaps * caps)
872 {
873   GstVideoDecoderClass *decoder_class;
874   GstVideoCodecState *state;
875   gboolean ret = TRUE;
876
877   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
878
879   GST_DEBUG_OBJECT (decoder, "setcaps %" GST_PTR_FORMAT, caps);
880
881   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
882
883   if (decoder->priv->input_state) {
884     GST_DEBUG_OBJECT (decoder,
885         "Checking if caps changed old %" GST_PTR_FORMAT " new %" GST_PTR_FORMAT,
886         decoder->priv->input_state->caps, caps);
887     if (gst_caps_is_equal (decoder->priv->input_state->caps, caps))
888       goto caps_not_changed;
889   }
890
891   state = _new_input_state (caps);
892
893   if (G_UNLIKELY (state == NULL))
894     goto parse_fail;
895
896   if (decoder_class->set_format)
897     ret = decoder_class->set_format (decoder, state);
898
899   if (!ret)
900     goto refused_format;
901
902   if (decoder->priv->input_state)
903     gst_video_codec_state_unref (decoder->priv->input_state);
904   decoder->priv->input_state = state;
905
906   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
907
908   return ret;
909
910 caps_not_changed:
911   {
912     GST_DEBUG_OBJECT (decoder, "Caps did not change - ignore");
913     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
914     return TRUE;
915   }
916
917   /* ERRORS */
918 parse_fail:
919   {
920     GST_WARNING_OBJECT (decoder, "Failed to parse caps");
921     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
922     return FALSE;
923   }
924
925 refused_format:
926   {
927     GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
928     GST_WARNING_OBJECT (decoder, "Subclass refused caps");
929     gst_video_codec_state_unref (state);
930     return FALSE;
931   }
932 }
933
934 static void
935 gst_video_decoder_finalize (GObject * object)
936 {
937   GstVideoDecoder *decoder;
938
939   decoder = GST_VIDEO_DECODER (object);
940
941   GST_DEBUG_OBJECT (object, "finalize");
942
943   g_rec_mutex_clear (&decoder->stream_lock);
944
945   if (decoder->priv->input_adapter) {
946     g_object_unref (decoder->priv->input_adapter);
947     decoder->priv->input_adapter = NULL;
948   }
949   if (decoder->priv->output_adapter) {
950     g_object_unref (decoder->priv->output_adapter);
951     decoder->priv->output_adapter = NULL;
952   }
953
954   if (decoder->priv->input_state)
955     gst_video_codec_state_unref (decoder->priv->input_state);
956   if (decoder->priv->output_state)
957     gst_video_codec_state_unref (decoder->priv->output_state);
958
959   if (decoder->priv->pool) {
960     gst_object_unref (decoder->priv->pool);
961     decoder->priv->pool = NULL;
962   }
963
964   if (decoder->priv->allocator) {
965     gst_object_unref (decoder->priv->allocator);
966     decoder->priv->allocator = NULL;
967   }
968
969   G_OBJECT_CLASS (parent_class)->finalize (object);
970 }
971
972 static void
973 gst_video_decoder_get_property (GObject * object, guint property_id,
974     GValue * value, GParamSpec * pspec)
975 {
976   GstVideoDecoder *dec = GST_VIDEO_DECODER (object);
977   GstVideoDecoderPrivate *priv = dec->priv;
978
979   switch (property_id) {
980     case PROP_QOS:
981       g_value_set_boolean (value, priv->do_qos);
982       break;
983     case PROP_MAX_ERRORS:
984       g_value_set_int (value, gst_video_decoder_get_max_errors (dec));
985       break;
986     case PROP_MIN_FORCE_KEY_UNIT_INTERVAL:
987       g_value_set_uint64 (value, priv->min_force_key_unit_interval);
988       break;
989     case PROP_DISCARD_CORRUPTED_FRAMES:
990       g_value_set_boolean (value, priv->discard_corrupted_frames);
991       break;
992     case PROP_AUTOMATIC_REQUEST_SYNC_POINTS:
993       g_value_set_boolean (value, priv->automatic_request_sync_points);
994       break;
995     case PROP_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS:
996       g_value_set_flags (value, priv->automatic_request_sync_point_flags);
997       break;
998     default:
999       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1000       break;
1001   }
1002 }
1003
1004 static void
1005 gst_video_decoder_set_property (GObject * object, guint property_id,
1006     const GValue * value, GParamSpec * pspec)
1007 {
1008   GstVideoDecoder *dec = GST_VIDEO_DECODER (object);
1009   GstVideoDecoderPrivate *priv = dec->priv;
1010
1011   switch (property_id) {
1012     case PROP_QOS:
1013       priv->do_qos = g_value_get_boolean (value);
1014       break;
1015     case PROP_MAX_ERRORS:
1016       gst_video_decoder_set_max_errors (dec, g_value_get_int (value));
1017       break;
1018     case PROP_MIN_FORCE_KEY_UNIT_INTERVAL:
1019       priv->min_force_key_unit_interval = g_value_get_uint64 (value);
1020       break;
1021     case PROP_DISCARD_CORRUPTED_FRAMES:
1022       priv->discard_corrupted_frames = g_value_get_boolean (value);
1023       break;
1024     case PROP_AUTOMATIC_REQUEST_SYNC_POINTS:
1025       priv->automatic_request_sync_points = g_value_get_boolean (value);
1026       break;
1027     case PROP_AUTOMATIC_REQUEST_SYNC_POINT_FLAGS:
1028       priv->automatic_request_sync_point_flags = g_value_get_flags (value);
1029       break;
1030     default:
1031       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
1032       break;
1033   }
1034 }
1035
1036 /* hard == FLUSH, otherwise discont */
1037 static GstFlowReturn
1038 gst_video_decoder_flush (GstVideoDecoder * dec, gboolean hard)
1039 {
1040   GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (dec);
1041   GstFlowReturn ret = GST_FLOW_OK;
1042
1043   GST_LOG_OBJECT (dec, "flush hard %d", hard);
1044
1045   /* Inform subclass */
1046   if (klass->reset) {
1047     GST_FIXME_OBJECT (dec, "GstVideoDecoder::reset() is deprecated");
1048     klass->reset (dec, hard);
1049   }
1050
1051   if (klass->flush)
1052     klass->flush (dec);
1053
1054   /* and get (re)set for the sequel */
1055   gst_video_decoder_reset (dec, FALSE, hard);
1056
1057   return ret;
1058 }
1059
1060 static GstEvent *
1061 gst_video_decoder_create_merged_tags_event (GstVideoDecoder * dec)
1062 {
1063   GstTagList *merged_tags;
1064
1065   GST_LOG_OBJECT (dec, "upstream : %" GST_PTR_FORMAT, dec->priv->upstream_tags);
1066   GST_LOG_OBJECT (dec, "decoder  : %" GST_PTR_FORMAT, dec->priv->tags);
1067   GST_LOG_OBJECT (dec, "mode     : %d", dec->priv->tags_merge_mode);
1068
1069   merged_tags =
1070       gst_tag_list_merge (dec->priv->upstream_tags, dec->priv->tags,
1071       dec->priv->tags_merge_mode);
1072
1073   GST_DEBUG_OBJECT (dec, "merged   : %" GST_PTR_FORMAT, merged_tags);
1074
1075   if (merged_tags == NULL)
1076     return NULL;
1077
1078   if (gst_tag_list_is_empty (merged_tags)) {
1079     gst_tag_list_unref (merged_tags);
1080     return NULL;
1081   }
1082
1083   return gst_event_new_tag (merged_tags);
1084 }
1085
1086 static gboolean
1087 gst_video_decoder_push_event (GstVideoDecoder * decoder, GstEvent * event)
1088 {
1089   switch (GST_EVENT_TYPE (event)) {
1090     case GST_EVENT_SEGMENT:
1091     {
1092       GstSegment segment;
1093
1094       gst_event_copy_segment (event, &segment);
1095
1096       GST_DEBUG_OBJECT (decoder, "segment %" GST_SEGMENT_FORMAT, &segment);
1097
1098       if (segment.format != GST_FORMAT_TIME) {
1099         GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
1100         break;
1101       }
1102
1103       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1104       decoder->output_segment = segment;
1105       decoder->priv->in_out_segment_sync =
1106           gst_segment_is_equal (&decoder->input_segment, &segment);
1107       decoder->priv->last_timestamp_out = GST_CLOCK_TIME_NONE;
1108       decoder->priv->earliest_time = GST_CLOCK_TIME_NONE;
1109       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1110       break;
1111     }
1112     default:
1113       break;
1114   }
1115
1116   GST_DEBUG_OBJECT (decoder, "pushing event %s",
1117       gst_event_type_get_name (GST_EVENT_TYPE (event)));
1118
1119   return gst_pad_push_event (decoder->srcpad, event);
1120 }
1121
1122 static GstFlowReturn
1123 gst_video_decoder_parse_available (GstVideoDecoder * dec, gboolean at_eos,
1124     gboolean new_buffer)
1125 {
1126   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_GET_CLASS (dec);
1127   GstVideoDecoderPrivate *priv = dec->priv;
1128   GstFlowReturn ret = GST_FLOW_OK;
1129   gsize was_available, available;
1130   guint inactive = 0;
1131
1132   available = gst_adapter_available (priv->input_adapter);
1133
1134   while (available || new_buffer) {
1135     new_buffer = FALSE;
1136     /* current frame may have been parsed and handled,
1137      * so we need to set up a new one when asking subclass to parse */
1138     if (priv->current_frame == NULL)
1139       priv->current_frame = gst_video_decoder_new_frame (dec);
1140
1141     was_available = available;
1142     ret = decoder_class->parse (dec, priv->current_frame,
1143         priv->input_adapter, at_eos);
1144     if (ret != GST_FLOW_OK)
1145       break;
1146
1147     /* if the subclass returned success (GST_FLOW_OK), it is expected
1148      * to have collected and submitted a frame, i.e. it should have
1149      * called gst_video_decoder_have_frame(), or at least consumed a
1150      * few bytes through gst_video_decoder_add_to_frame().
1151      *
1152      * Otherwise, this is an implementation bug, and we error out
1153      * after 2 failed attempts */
1154     available = gst_adapter_available (priv->input_adapter);
1155     if (!priv->current_frame || available != was_available)
1156       inactive = 0;
1157     else if (++inactive == 2)
1158       goto error_inactive;
1159   }
1160
1161   return ret;
1162
1163   /* ERRORS */
1164 error_inactive:
1165   {
1166     GST_ERROR_OBJECT (dec, "Failed to consume data. Error in subclass?");
1167     return GST_FLOW_ERROR;
1168   }
1169 }
1170
1171 /* This function has to be called with the stream lock taken. */
1172 static GstFlowReturn
1173 gst_video_decoder_drain_out (GstVideoDecoder * dec, gboolean at_eos)
1174 {
1175   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_GET_CLASS (dec);
1176   GstVideoDecoderPrivate *priv = dec->priv;
1177   GstFlowReturn ret = GST_FLOW_OK;
1178
1179   if (dec->input_segment.rate > 0.0) {
1180     /* Forward mode, if unpacketized, give the child class
1181      * a final chance to flush out packets */
1182     if (!priv->packetized) {
1183       ret = gst_video_decoder_parse_available (dec, TRUE, FALSE);
1184     }
1185
1186     if (at_eos) {
1187       if (decoder_class->finish)
1188         ret = decoder_class->finish (dec);
1189     } else {
1190       if (decoder_class->drain) {
1191         ret = decoder_class->drain (dec);
1192       } else {
1193         GST_FIXME_OBJECT (dec, "Sub-class should implement drain()");
1194       }
1195     }
1196   } else {
1197     /* Reverse playback mode */
1198     ret = gst_video_decoder_flush_parse (dec, TRUE);
1199   }
1200
1201   return ret;
1202 }
1203
1204 static GList *
1205 _flush_events (GstPad * pad, GList * events)
1206 {
1207   GList *tmp;
1208
1209   for (tmp = events; tmp; tmp = tmp->next) {
1210     if (GST_EVENT_TYPE (tmp->data) != GST_EVENT_EOS &&
1211         GST_EVENT_TYPE (tmp->data) != GST_EVENT_SEGMENT &&
1212         GST_EVENT_IS_STICKY (tmp->data)) {
1213       gst_pad_store_sticky_event (pad, GST_EVENT_CAST (tmp->data));
1214     }
1215     gst_event_unref (tmp->data);
1216   }
1217   g_list_free (events);
1218
1219   return NULL;
1220 }
1221
1222 /* Must be called holding the GST_VIDEO_DECODER_STREAM_LOCK */
1223 static gboolean
1224 gst_video_decoder_negotiate_default_caps (GstVideoDecoder * decoder)
1225 {
1226   GstCaps *caps, *templcaps;
1227   GstVideoCodecState *state;
1228   GstVideoInfo info;
1229   gint i;
1230   gint caps_size;
1231   GstStructure *structure;
1232
1233   templcaps = gst_pad_get_pad_template_caps (decoder->srcpad);
1234   caps = gst_pad_peer_query_caps (decoder->srcpad, templcaps);
1235   if (caps)
1236     gst_caps_unref (templcaps);
1237   else
1238     caps = templcaps;
1239   templcaps = NULL;
1240
1241   if (!caps || gst_caps_is_empty (caps) || gst_caps_is_any (caps))
1242     goto caps_error;
1243
1244   GST_LOG_OBJECT (decoder, "peer caps %" GST_PTR_FORMAT, caps);
1245
1246   /* before fixating, try to use whatever upstream provided */
1247   caps = gst_caps_make_writable (caps);
1248   caps_size = gst_caps_get_size (caps);
1249   if (decoder->priv->input_state && decoder->priv->input_state->caps) {
1250     GstCaps *sinkcaps = decoder->priv->input_state->caps;
1251     GstStructure *structure = gst_caps_get_structure (sinkcaps, 0);
1252     gint width, height;
1253
1254     if (gst_structure_get_int (structure, "width", &width)) {
1255       for (i = 0; i < caps_size; i++) {
1256         gst_structure_set (gst_caps_get_structure (caps, i), "width",
1257             G_TYPE_INT, width, NULL);
1258       }
1259     }
1260
1261     if (gst_structure_get_int (structure, "height", &height)) {
1262       for (i = 0; i < caps_size; i++) {
1263         gst_structure_set (gst_caps_get_structure (caps, i), "height",
1264             G_TYPE_INT, height, NULL);
1265       }
1266     }
1267   }
1268
1269   for (i = 0; i < caps_size; i++) {
1270     structure = gst_caps_get_structure (caps, i);
1271     /* Random I420 1280x720 for fixation */
1272     if (gst_structure_has_field (structure, "format"))
1273       gst_structure_fixate_field_string (structure, "format", "I420");
1274     else
1275       gst_structure_set (structure, "format", G_TYPE_STRING, "I420", NULL);
1276
1277     if (gst_structure_has_field (structure, "width"))
1278       gst_structure_fixate_field_nearest_int (structure, "width", 1280);
1279     else
1280       gst_structure_set (structure, "width", G_TYPE_INT, 1280, NULL);
1281
1282     if (gst_structure_has_field (structure, "height"))
1283       gst_structure_fixate_field_nearest_int (structure, "height", 720);
1284     else
1285       gst_structure_set (structure, "height", G_TYPE_INT, 720, NULL);
1286   }
1287   caps = gst_caps_fixate (caps);
1288
1289   if (!caps || !gst_video_info_from_caps (&info, caps))
1290     goto caps_error;
1291
1292   GST_INFO_OBJECT (decoder,
1293       "Chose default caps %" GST_PTR_FORMAT " for initial gap", caps);
1294   state =
1295       gst_video_decoder_set_output_state (decoder, info.finfo->format,
1296       info.width, info.height, decoder->priv->input_state);
1297   gst_video_codec_state_unref (state);
1298   gst_caps_unref (caps);
1299
1300   return TRUE;
1301
1302 caps_error:
1303   {
1304     if (caps)
1305       gst_caps_unref (caps);
1306     return FALSE;
1307   }
1308 }
1309
1310 static gboolean
1311 gst_video_decoder_handle_missing_data_default (GstVideoDecoder *
1312     decoder, GstClockTime timestamp, GstClockTime duration)
1313 {
1314   GstVideoDecoderPrivate *priv;
1315
1316   priv = decoder->priv;
1317
1318   if (priv->automatic_request_sync_points) {
1319     GstClockTime deadline =
1320         gst_segment_to_running_time (&decoder->input_segment, GST_FORMAT_TIME,
1321         timestamp);
1322
1323     GST_DEBUG_OBJECT (decoder,
1324         "Requesting sync point for missing data at running time %"
1325         GST_TIME_FORMAT " timestamp %" GST_TIME_FORMAT " with duration %"
1326         GST_TIME_FORMAT, GST_TIME_ARGS (deadline), GST_TIME_ARGS (timestamp),
1327         GST_TIME_ARGS (duration));
1328
1329     gst_video_decoder_request_sync_point_internal (decoder, deadline,
1330         priv->automatic_request_sync_point_flags);
1331   }
1332
1333   return TRUE;
1334 }
1335
1336 static gboolean
1337 gst_video_decoder_sink_event_default (GstVideoDecoder * decoder,
1338     GstEvent * event)
1339 {
1340   GstVideoDecoderClass *decoder_class;
1341   GstVideoDecoderPrivate *priv;
1342   gboolean ret = FALSE;
1343   gboolean forward_immediate = FALSE;
1344
1345   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1346
1347   priv = decoder->priv;
1348
1349   switch (GST_EVENT_TYPE (event)) {
1350     case GST_EVENT_STREAM_START:
1351     {
1352       GstFlowReturn flow_ret = GST_FLOW_OK;
1353
1354       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1355       flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
1356       ret = (flow_ret == GST_FLOW_OK);
1357
1358       GST_DEBUG_OBJECT (decoder, "received STREAM_START. Clearing taglist");
1359       /* Flush upstream tags after a STREAM_START */
1360       if (priv->upstream_tags) {
1361         gst_tag_list_unref (priv->upstream_tags);
1362         priv->upstream_tags = NULL;
1363         priv->tags_changed = TRUE;
1364       }
1365       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1366
1367       /* Forward STREAM_START immediately. Everything is drained after
1368        * the STREAM_START event and we can forward this event immediately
1369        * now without having buffers out of order.
1370        */
1371       forward_immediate = TRUE;
1372       break;
1373     }
1374     case GST_EVENT_CAPS:
1375     {
1376       GstCaps *caps;
1377
1378       gst_event_parse_caps (event, &caps);
1379       ret = gst_video_decoder_setcaps (decoder, caps);
1380       gst_event_unref (event);
1381       event = NULL;
1382       break;
1383     }
1384     case GST_EVENT_SEGMENT_DONE:
1385     {
1386       GstFlowReturn flow_ret = GST_FLOW_OK;
1387
1388       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1389       flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
1390       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1391       ret = (flow_ret == GST_FLOW_OK);
1392
1393       /* Forward SEGMENT_DONE immediately. This is required
1394        * because no buffer or serialized event might come
1395        * after SEGMENT_DONE and nothing could trigger another
1396        * _finish_frame() call.
1397        *
1398        * The subclass can override this behaviour by overriding
1399        * the ::sink_event() vfunc and not chaining up to the
1400        * parent class' ::sink_event() until a later time.
1401        */
1402       forward_immediate = TRUE;
1403       break;
1404     }
1405     case GST_EVENT_EOS:
1406     {
1407       GstFlowReturn flow_ret = GST_FLOW_OK;
1408
1409       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1410       flow_ret = gst_video_decoder_drain_out (decoder, TRUE);
1411       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1412       ret = (flow_ret == GST_FLOW_OK);
1413
1414       /* Error out even if EOS was ok when we had input, but no output */
1415       if (ret && priv->had_input_data && !priv->had_output_data) {
1416         GST_ELEMENT_ERROR (decoder, STREAM, DECODE,
1417             ("No valid frames decoded before end of stream"),
1418             ("no valid frames found"));
1419       }
1420
1421       /* Forward EOS immediately. This is required because no
1422        * buffer or serialized event will come after EOS and
1423        * nothing could trigger another _finish_frame() call.
1424        *
1425        * The subclass can override this behaviour by overriding
1426        * the ::sink_event() vfunc and not chaining up to the
1427        * parent class' ::sink_event() until a later time.
1428        */
1429       forward_immediate = TRUE;
1430       break;
1431     }
1432     case GST_EVENT_GAP:
1433     {
1434       GstClockTime timestamp, duration;
1435       GstGapFlags gap_flags = 0;
1436       GstFlowReturn flow_ret = GST_FLOW_OK;
1437       gboolean needs_reconfigure = FALSE;
1438       GList *events;
1439       GList *frame_events;
1440
1441       gst_event_parse_gap (event, &timestamp, &duration);
1442       gst_event_parse_gap_flags (event, &gap_flags);
1443
1444       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1445       /* If this is not missing data, or the subclass does not handle it
1446        * specifically, then drain out the decoder and forward the event
1447        * directly. */
1448       if ((gap_flags & GST_GAP_FLAG_MISSING_DATA) == 0
1449           || !decoder_class->handle_missing_data
1450           || decoder_class->handle_missing_data (decoder, timestamp,
1451               duration)) {
1452         if (decoder->input_segment.flags & GST_SEEK_FLAG_TRICKMODE_KEY_UNITS)
1453           flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
1454         ret = (flow_ret == GST_FLOW_OK);
1455
1456         /* Ensure we have caps before forwarding the event */
1457         if (!decoder->priv->output_state) {
1458           if (!gst_video_decoder_negotiate_default_caps (decoder)) {
1459             GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1460             GST_ELEMENT_ERROR (decoder, STREAM, FORMAT, (NULL),
1461                 ("Decoder output not negotiated before GAP event."));
1462             forward_immediate = TRUE;
1463             break;
1464           }
1465           needs_reconfigure = TRUE;
1466         }
1467
1468         needs_reconfigure = gst_pad_check_reconfigure (decoder->srcpad)
1469             || needs_reconfigure;
1470         if (decoder->priv->output_state_changed || needs_reconfigure) {
1471           if (!gst_video_decoder_negotiate_unlocked (decoder)) {
1472             GST_WARNING_OBJECT (decoder, "Failed to negotiate with downstream");
1473             gst_pad_mark_reconfigure (decoder->srcpad);
1474           }
1475         }
1476
1477         GST_DEBUG_OBJECT (decoder, "Pushing all pending serialized events"
1478             " before the gap");
1479         events = decoder->priv->pending_events;
1480         frame_events = decoder->priv->current_frame_events;
1481         decoder->priv->pending_events = NULL;
1482         decoder->priv->current_frame_events = NULL;
1483
1484         GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1485
1486         gst_video_decoder_push_event_list (decoder, events);
1487         gst_video_decoder_push_event_list (decoder, frame_events);
1488
1489         /* Forward GAP immediately. Everything is drained after
1490          * the GAP event and we can forward this event immediately
1491          * now without having buffers out of order.
1492          */
1493         forward_immediate = TRUE;
1494       } else {
1495         gst_clear_event (&event);
1496       }
1497       break;
1498     }
1499     case GST_EVENT_CUSTOM_DOWNSTREAM:
1500     {
1501       gboolean in_still;
1502       GstFlowReturn flow_ret = GST_FLOW_OK;
1503
1504       if (gst_video_event_parse_still_frame (event, &in_still)) {
1505         if (in_still) {
1506           GST_DEBUG_OBJECT (decoder, "draining current data for still-frame");
1507           GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1508           flow_ret = gst_video_decoder_drain_out (decoder, FALSE);
1509           GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1510           ret = (flow_ret == GST_FLOW_OK);
1511         }
1512         /* Forward STILL_FRAME immediately. Everything is drained after
1513          * the STILL_FRAME event and we can forward this event immediately
1514          * now without having buffers out of order.
1515          */
1516         forward_immediate = TRUE;
1517       }
1518       break;
1519     }
1520     case GST_EVENT_SEGMENT:
1521     {
1522       GstSegment segment;
1523
1524       gst_event_copy_segment (event, &segment);
1525
1526       if (segment.format == GST_FORMAT_TIME) {
1527         GST_DEBUG_OBJECT (decoder,
1528             "received TIME SEGMENT %" GST_SEGMENT_FORMAT, &segment);
1529       } else {
1530         gint64 start;
1531
1532         GST_DEBUG_OBJECT (decoder,
1533             "received SEGMENT %" GST_SEGMENT_FORMAT, &segment);
1534
1535         /* handle newsegment as a result from our legacy simple seeking */
1536         /* note that initial 0 should convert to 0 in any case */
1537         if (priv->do_estimate_rate &&
1538             gst_pad_query_convert (decoder->sinkpad, GST_FORMAT_BYTES,
1539                 segment.start, GST_FORMAT_TIME, &start)) {
1540           /* best attempt convert */
1541           /* as these are only estimates, stop is kept open-ended to avoid
1542            * premature cutting */
1543           GST_DEBUG_OBJECT (decoder,
1544               "converted to TIME start %" GST_TIME_FORMAT,
1545               GST_TIME_ARGS (start));
1546           segment.start = start;
1547           segment.stop = GST_CLOCK_TIME_NONE;
1548           segment.time = start;
1549           /* replace event */
1550           gst_event_unref (event);
1551           event = gst_event_new_segment (&segment);
1552         } else {
1553           goto newseg_wrong_format;
1554         }
1555       }
1556
1557       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1558
1559       /* Update the decode flags in the segment if we have an instant-rate
1560        * override active */
1561       GST_OBJECT_LOCK (decoder);
1562       if (!priv->decode_flags_override)
1563         priv->decode_flags = segment.flags;
1564       else {
1565         segment.flags &= ~GST_SEGMENT_INSTANT_FLAGS;
1566         segment.flags |= priv->decode_flags & GST_SEGMENT_INSTANT_FLAGS;
1567       }
1568
1569       priv->base_timestamp = GST_CLOCK_TIME_NONE;
1570       priv->base_picture_number = 0;
1571
1572       decoder->input_segment = segment;
1573       decoder->priv->in_out_segment_sync = FALSE;
1574
1575       GST_OBJECT_UNLOCK (decoder);
1576       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1577
1578       break;
1579     }
1580     case GST_EVENT_INSTANT_RATE_CHANGE:
1581     {
1582       GstSegmentFlags flags;
1583       GstSegment *seg;
1584
1585       gst_event_parse_instant_rate_change (event, NULL, &flags);
1586
1587       GST_OBJECT_LOCK (decoder);
1588       priv->decode_flags_override = TRUE;
1589       priv->decode_flags = flags;
1590
1591       /* Update the input segment flags */
1592       seg = &decoder->input_segment;
1593       seg->flags &= ~GST_SEGMENT_INSTANT_FLAGS;
1594       seg->flags |= priv->decode_flags & GST_SEGMENT_INSTANT_FLAGS;
1595       GST_OBJECT_UNLOCK (decoder);
1596       break;
1597     }
1598     case GST_EVENT_FLUSH_STOP:
1599     {
1600       GList *l;
1601
1602       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1603       for (l = priv->frames.head; l; l = l->next) {
1604         GstVideoCodecFrame *frame = l->data;
1605
1606         frame->events = _flush_events (decoder->srcpad, frame->events);
1607       }
1608       priv->current_frame_events = _flush_events (decoder->srcpad,
1609           decoder->priv->current_frame_events);
1610
1611       /* well, this is kind of worse than a DISCONT */
1612       gst_video_decoder_flush (decoder, TRUE);
1613       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1614       /* Forward FLUSH_STOP immediately. This is required because it is
1615        * expected to be forwarded immediately and no buffers are queued
1616        * anyway.
1617        */
1618       forward_immediate = TRUE;
1619       break;
1620     }
1621     case GST_EVENT_TAG:
1622     {
1623       GstTagList *tags;
1624
1625       gst_event_parse_tag (event, &tags);
1626
1627       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1628         GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1629         if (priv->upstream_tags != tags) {
1630           if (priv->upstream_tags)
1631             gst_tag_list_unref (priv->upstream_tags);
1632           priv->upstream_tags = gst_tag_list_ref (tags);
1633           GST_INFO_OBJECT (decoder, "upstream tags: %" GST_PTR_FORMAT, tags);
1634         }
1635         gst_event_unref (event);
1636         event = gst_video_decoder_create_merged_tags_event (decoder);
1637         GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1638         if (!event)
1639           ret = TRUE;
1640       }
1641       break;
1642     }
1643     default:
1644       break;
1645   }
1646
1647   /* Forward non-serialized events immediately, and all other
1648    * events which can be forwarded immediately without potentially
1649    * causing the event to go out of order with other events and
1650    * buffers as decided above.
1651    */
1652   if (event) {
1653     if (!GST_EVENT_IS_SERIALIZED (event) || forward_immediate) {
1654       ret = gst_video_decoder_push_event (decoder, event);
1655     } else {
1656       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1657       decoder->priv->current_frame_events =
1658           g_list_prepend (decoder->priv->current_frame_events, event);
1659       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1660       ret = TRUE;
1661     }
1662   }
1663
1664   return ret;
1665
1666 newseg_wrong_format:
1667   {
1668     GST_DEBUG_OBJECT (decoder, "received non TIME newsegment");
1669     gst_event_unref (event);
1670     /* SWALLOW EVENT */
1671     return TRUE;
1672   }
1673 }
1674
1675 static gboolean
1676 gst_video_decoder_sink_event (GstPad * pad, GstObject * parent,
1677     GstEvent * event)
1678 {
1679   GstVideoDecoder *decoder;
1680   GstVideoDecoderClass *decoder_class;
1681   gboolean ret = FALSE;
1682
1683   decoder = GST_VIDEO_DECODER (parent);
1684   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1685
1686   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1687       GST_EVENT_TYPE_NAME (event));
1688
1689   if (decoder_class->sink_event)
1690     ret = decoder_class->sink_event (decoder, event);
1691
1692   return ret;
1693 }
1694
1695 /* perform upstream byte <-> time conversion (duration, seeking)
1696  * if subclass allows and if enough data for moderately decent conversion */
1697 static inline gboolean
1698 gst_video_decoder_do_byte (GstVideoDecoder * dec)
1699 {
1700   gboolean ret;
1701
1702   GST_OBJECT_LOCK (dec);
1703   ret = dec->priv->do_estimate_rate && (dec->priv->bytes_out > 0)
1704       && (dec->priv->time > GST_SECOND);
1705   GST_OBJECT_UNLOCK (dec);
1706
1707   return ret;
1708 }
1709
1710 static gboolean
1711 gst_video_decoder_do_seek (GstVideoDecoder * dec, GstEvent * event)
1712 {
1713   GstFormat format;
1714   GstSeekFlags flags;
1715   GstSeekType start_type, end_type;
1716   gdouble rate;
1717   gint64 start, start_time, end_time;
1718   GstSegment seek_segment;
1719   guint32 seqnum;
1720
1721   gst_event_parse_seek (event, &rate, &format, &flags, &start_type,
1722       &start_time, &end_type, &end_time);
1723
1724   /* we'll handle plain open-ended flushing seeks with the simple approach */
1725   if (rate != 1.0) {
1726     GST_DEBUG_OBJECT (dec, "unsupported seek: rate");
1727     return FALSE;
1728   }
1729
1730   if (start_type != GST_SEEK_TYPE_SET) {
1731     GST_DEBUG_OBJECT (dec, "unsupported seek: start time");
1732     return FALSE;
1733   }
1734
1735   if ((end_type != GST_SEEK_TYPE_SET && end_type != GST_SEEK_TYPE_NONE) ||
1736       (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) {
1737     GST_DEBUG_OBJECT (dec, "unsupported seek: end time");
1738     return FALSE;
1739   }
1740
1741   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
1742     GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing");
1743     return FALSE;
1744   }
1745
1746   memcpy (&seek_segment, &dec->output_segment, sizeof (seek_segment));
1747   gst_segment_do_seek (&seek_segment, rate, format, flags, start_type,
1748       start_time, end_type, end_time, NULL);
1749   start_time = seek_segment.position;
1750
1751   if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time,
1752           GST_FORMAT_BYTES, &start)) {
1753     GST_DEBUG_OBJECT (dec, "conversion failed");
1754     return FALSE;
1755   }
1756
1757   seqnum = gst_event_get_seqnum (event);
1758   event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags,
1759       GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1);
1760   gst_event_set_seqnum (event, seqnum);
1761
1762   GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %"
1763       G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start);
1764
1765   return gst_pad_push_event (dec->sinkpad, event);
1766 }
1767
1768 static gboolean
1769 gst_video_decoder_src_event_default (GstVideoDecoder * decoder,
1770     GstEvent * event)
1771 {
1772   GstVideoDecoderPrivate *priv;
1773   gboolean res = FALSE;
1774
1775   priv = decoder->priv;
1776
1777   GST_DEBUG_OBJECT (decoder,
1778       "received event %d, %s", GST_EVENT_TYPE (event),
1779       GST_EVENT_TYPE_NAME (event));
1780
1781   switch (GST_EVENT_TYPE (event)) {
1782     case GST_EVENT_SEEK:
1783     {
1784       GstFormat format;
1785       gdouble rate;
1786       GstSeekFlags flags;
1787       GstSeekType start_type, stop_type;
1788       gint64 start, stop;
1789       gint64 tstart, tstop;
1790       guint32 seqnum;
1791
1792       gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
1793           &stop_type, &stop);
1794       seqnum = gst_event_get_seqnum (event);
1795
1796       /* upstream gets a chance first */
1797       if ((res = gst_pad_push_event (decoder->sinkpad, event)))
1798         break;
1799
1800       /* if upstream fails for a time seek, maybe we can help if allowed */
1801       if (format == GST_FORMAT_TIME) {
1802         if (gst_video_decoder_do_byte (decoder))
1803           res = gst_video_decoder_do_seek (decoder, event);
1804         break;
1805       }
1806
1807       /* ... though a non-time seek can be aided as well */
1808       /* First bring the requested format to time */
1809       if (!(res =
1810               gst_pad_query_convert (decoder->srcpad, format, start,
1811                   GST_FORMAT_TIME, &tstart)))
1812         goto convert_error;
1813       if (!(res =
1814               gst_pad_query_convert (decoder->srcpad, format, stop,
1815                   GST_FORMAT_TIME, &tstop)))
1816         goto convert_error;
1817
1818       /* then seek with time on the peer */
1819       event = gst_event_new_seek (rate, GST_FORMAT_TIME,
1820           flags, start_type, tstart, stop_type, tstop);
1821       gst_event_set_seqnum (event, seqnum);
1822
1823       res = gst_pad_push_event (decoder->sinkpad, event);
1824       break;
1825     }
1826     case GST_EVENT_QOS:
1827     {
1828       GstQOSType type;
1829       gdouble proportion;
1830       GstClockTimeDiff diff;
1831       GstClockTime timestamp;
1832
1833       gst_event_parse_qos (event, &type, &proportion, &diff, &timestamp);
1834
1835       GST_OBJECT_LOCK (decoder);
1836       priv->proportion = proportion;
1837       if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (timestamp))) {
1838         if (G_UNLIKELY (diff > 0)) {
1839           priv->earliest_time = timestamp + 2 * diff + priv->qos_frame_duration;
1840         } else {
1841           priv->earliest_time = timestamp + diff;
1842         }
1843       } else {
1844         priv->earliest_time = GST_CLOCK_TIME_NONE;
1845       }
1846       GST_OBJECT_UNLOCK (decoder);
1847
1848       GST_DEBUG_OBJECT (decoder,
1849           "got QoS %" GST_TIME_FORMAT ", %" GST_STIME_FORMAT ", %g",
1850           GST_TIME_ARGS (timestamp), GST_STIME_ARGS (diff), proportion);
1851
1852       res = gst_pad_push_event (decoder->sinkpad, event);
1853       break;
1854     }
1855     default:
1856       res = gst_pad_push_event (decoder->sinkpad, event);
1857       break;
1858   }
1859 done:
1860   return res;
1861
1862 convert_error:
1863   GST_DEBUG_OBJECT (decoder, "could not convert format");
1864   goto done;
1865 }
1866
1867 static gboolean
1868 gst_video_decoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1869 {
1870   GstVideoDecoder *decoder;
1871   GstVideoDecoderClass *decoder_class;
1872   gboolean ret = FALSE;
1873
1874   decoder = GST_VIDEO_DECODER (parent);
1875   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
1876
1877   GST_DEBUG_OBJECT (decoder, "received event %d, %s", GST_EVENT_TYPE (event),
1878       GST_EVENT_TYPE_NAME (event));
1879
1880   if (decoder_class->src_event)
1881     ret = decoder_class->src_event (decoder, event);
1882
1883   return ret;
1884 }
1885
1886 static gboolean
1887 gst_video_decoder_src_query_default (GstVideoDecoder * dec, GstQuery * query)
1888 {
1889   GstPad *pad = GST_VIDEO_DECODER_SRC_PAD (dec);
1890   gboolean res = TRUE;
1891
1892   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
1893
1894   switch (GST_QUERY_TYPE (query)) {
1895     case GST_QUERY_POSITION:
1896     {
1897       GstFormat format;
1898       gint64 time, value;
1899
1900       /* upstream gets a chance first */
1901       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
1902         GST_LOG_OBJECT (dec, "returning peer response");
1903         break;
1904       }
1905
1906       /* Refuse BYTES format queries. If it made sense to
1907        * answer them, upstream would have already */
1908       gst_query_parse_position (query, &format, NULL);
1909
1910       if (format == GST_FORMAT_BYTES) {
1911         GST_LOG_OBJECT (dec, "Ignoring BYTES position query");
1912         break;
1913       }
1914
1915       /* we start from the last seen time */
1916       time = dec->priv->last_timestamp_out;
1917       /* correct for the segment values */
1918       time = gst_segment_to_stream_time (&dec->output_segment,
1919           GST_FORMAT_TIME, time);
1920
1921       GST_LOG_OBJECT (dec,
1922           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
1923
1924       /* and convert to the final format */
1925       if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time,
1926                   format, &value)))
1927         break;
1928
1929       gst_query_set_position (query, format, value);
1930
1931       GST_LOG_OBJECT (dec,
1932           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
1933           format);
1934       break;
1935     }
1936     case GST_QUERY_DURATION:
1937     {
1938       GstFormat format;
1939
1940       /* upstream in any case */
1941       if ((res = gst_pad_query_default (pad, GST_OBJECT (dec), query)))
1942         break;
1943
1944       gst_query_parse_duration (query, &format, NULL);
1945       /* try answering TIME by converting from BYTE if subclass allows  */
1946       if (format == GST_FORMAT_TIME && gst_video_decoder_do_byte (dec)) {
1947         gint64 value;
1948
1949         if (gst_pad_peer_query_duration (dec->sinkpad, GST_FORMAT_BYTES,
1950                 &value)) {
1951           GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value);
1952           if (gst_pad_query_convert (dec->sinkpad,
1953                   GST_FORMAT_BYTES, value, GST_FORMAT_TIME, &value)) {
1954             gst_query_set_duration (query, GST_FORMAT_TIME, value);
1955             res = TRUE;
1956           }
1957         }
1958       }
1959       break;
1960     }
1961     case GST_QUERY_CONVERT:
1962     {
1963       GstFormat src_fmt, dest_fmt;
1964       gint64 src_val, dest_val;
1965
1966       GST_DEBUG_OBJECT (dec, "convert query");
1967
1968       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1969       GST_OBJECT_LOCK (dec);
1970       if (dec->priv->output_state != NULL)
1971         res = __gst_video_rawvideo_convert (dec->priv->output_state,
1972             src_fmt, src_val, &dest_fmt, &dest_val);
1973       else
1974         res = FALSE;
1975       GST_OBJECT_UNLOCK (dec);
1976       if (!res)
1977         goto error;
1978       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1979       break;
1980     }
1981     case GST_QUERY_LATENCY:
1982     {
1983       gboolean live;
1984       GstClockTime min_latency, max_latency;
1985
1986       res = gst_pad_peer_query (dec->sinkpad, query);
1987       if (res) {
1988         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1989         GST_DEBUG_OBJECT (dec, "Peer qlatency: live %d, min %"
1990             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1991             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1992
1993         GST_OBJECT_LOCK (dec);
1994         min_latency += dec->priv->min_latency;
1995         if (max_latency == GST_CLOCK_TIME_NONE
1996             || dec->priv->max_latency == GST_CLOCK_TIME_NONE)
1997           max_latency = GST_CLOCK_TIME_NONE;
1998         else
1999           max_latency += dec->priv->max_latency;
2000         GST_OBJECT_UNLOCK (dec);
2001
2002         gst_query_set_latency (query, live, min_latency, max_latency);
2003       }
2004     }
2005       break;
2006     default:
2007       res = gst_pad_query_default (pad, GST_OBJECT (dec), query);
2008   }
2009   return res;
2010
2011 error:
2012   GST_ERROR_OBJECT (dec, "query failed");
2013   return res;
2014 }
2015
2016 static gboolean
2017 gst_video_decoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2018 {
2019   GstVideoDecoder *decoder;
2020   GstVideoDecoderClass *decoder_class;
2021   gboolean ret = FALSE;
2022
2023   decoder = GST_VIDEO_DECODER (parent);
2024   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
2025
2026   GST_DEBUG_OBJECT (decoder, "received query %d, %s", GST_QUERY_TYPE (query),
2027       GST_QUERY_TYPE_NAME (query));
2028
2029   if (decoder_class->src_query)
2030     ret = decoder_class->src_query (decoder, query);
2031
2032   return ret;
2033 }
2034
2035 /**
2036  * gst_video_decoder_proxy_getcaps:
2037  * @decoder: a #GstVideoDecoder
2038  * @caps: (allow-none): initial caps
2039  * @filter: (allow-none): filter caps
2040  *
2041  * Returns caps that express @caps (or sink template caps if @caps == NULL)
2042  * restricted to resolution/format/... combinations supported by downstream
2043  * elements.
2044  *
2045  * Returns: (transfer full): a #GstCaps owned by caller
2046  *
2047  * Since: 1.6
2048  */
2049 GstCaps *
2050 gst_video_decoder_proxy_getcaps (GstVideoDecoder * decoder, GstCaps * caps,
2051     GstCaps * filter)
2052 {
2053   return __gst_video_element_proxy_getcaps (GST_ELEMENT_CAST (decoder),
2054       GST_VIDEO_DECODER_SINK_PAD (decoder),
2055       GST_VIDEO_DECODER_SRC_PAD (decoder), caps, filter);
2056 }
2057
2058 static GstCaps *
2059 gst_video_decoder_sink_getcaps (GstVideoDecoder * decoder, GstCaps * filter)
2060 {
2061   GstVideoDecoderClass *klass;
2062   GstCaps *caps;
2063
2064   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
2065
2066   if (klass->getcaps)
2067     caps = klass->getcaps (decoder, filter);
2068   else
2069     caps = gst_video_decoder_proxy_getcaps (decoder, NULL, filter);
2070
2071   GST_LOG_OBJECT (decoder, "Returning caps %" GST_PTR_FORMAT, caps);
2072
2073   return caps;
2074 }
2075
2076 static gboolean
2077 gst_video_decoder_sink_query_default (GstVideoDecoder * decoder,
2078     GstQuery * query)
2079 {
2080   GstPad *pad = GST_VIDEO_DECODER_SINK_PAD (decoder);
2081   GstVideoDecoderPrivate *priv;
2082   gboolean res = FALSE;
2083
2084   priv = decoder->priv;
2085
2086   GST_LOG_OBJECT (decoder, "handling query: %" GST_PTR_FORMAT, query);
2087
2088   switch (GST_QUERY_TYPE (query)) {
2089     case GST_QUERY_CONVERT:
2090     {
2091       GstFormat src_fmt, dest_fmt;
2092       gint64 src_val, dest_val;
2093
2094       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
2095       GST_OBJECT_LOCK (decoder);
2096       res =
2097           __gst_video_encoded_video_convert (priv->bytes_out, priv->time,
2098           src_fmt, src_val, &dest_fmt, &dest_val);
2099       GST_OBJECT_UNLOCK (decoder);
2100       if (!res)
2101         goto error;
2102       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
2103       break;
2104     }
2105     case GST_QUERY_ALLOCATION:{
2106       GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
2107
2108       if (klass->propose_allocation)
2109         res = klass->propose_allocation (decoder, query);
2110       break;
2111     }
2112     case GST_QUERY_CAPS:{
2113       GstCaps *filter, *caps;
2114
2115       gst_query_parse_caps (query, &filter);
2116       caps = gst_video_decoder_sink_getcaps (decoder, filter);
2117       gst_query_set_caps_result (query, caps);
2118       gst_caps_unref (caps);
2119       res = TRUE;
2120       break;
2121     }
2122     case GST_QUERY_ACCEPT_CAPS:{
2123       if (decoder->priv->use_default_pad_acceptcaps) {
2124         res =
2125             gst_pad_query_default (GST_VIDEO_DECODER_SINK_PAD (decoder),
2126             GST_OBJECT_CAST (decoder), query);
2127       } else {
2128         GstCaps *caps;
2129         GstCaps *allowed_caps;
2130         GstCaps *template_caps;
2131         gboolean accept;
2132
2133         gst_query_parse_accept_caps (query, &caps);
2134
2135         template_caps = gst_pad_get_pad_template_caps (pad);
2136         accept = gst_caps_is_subset (caps, template_caps);
2137         gst_caps_unref (template_caps);
2138
2139         if (accept) {
2140           allowed_caps =
2141               gst_pad_query_caps (GST_VIDEO_DECODER_SINK_PAD (decoder), caps);
2142
2143           accept = gst_caps_can_intersect (caps, allowed_caps);
2144
2145           gst_caps_unref (allowed_caps);
2146         }
2147
2148         gst_query_set_accept_caps_result (query, accept);
2149         res = TRUE;
2150       }
2151       break;
2152     }
2153     default:
2154       res = gst_pad_query_default (pad, GST_OBJECT (decoder), query);
2155       break;
2156   }
2157 done:
2158
2159   return res;
2160 error:
2161   GST_DEBUG_OBJECT (decoder, "query failed");
2162   goto done;
2163
2164 }
2165
2166 static gboolean
2167 gst_video_decoder_sink_query (GstPad * pad, GstObject * parent,
2168     GstQuery * query)
2169 {
2170   GstVideoDecoder *decoder;
2171   GstVideoDecoderClass *decoder_class;
2172   gboolean ret = FALSE;
2173
2174   decoder = GST_VIDEO_DECODER (parent);
2175   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
2176
2177   GST_DEBUG_OBJECT (decoder, "received query %d, %s", GST_QUERY_TYPE (query),
2178       GST_QUERY_TYPE_NAME (query));
2179
2180   if (decoder_class->sink_query)
2181     ret = decoder_class->sink_query (decoder, query);
2182
2183   return ret;
2184 }
2185
2186 typedef struct _Timestamp Timestamp;
2187 struct _Timestamp
2188 {
2189   guint64 offset;
2190   GstClockTime pts;
2191   GstClockTime dts;
2192   GstClockTime duration;
2193   guint flags;
2194 };
2195
2196 static void
2197 timestamp_free (Timestamp * ts)
2198 {
2199   g_slice_free (Timestamp, ts);
2200 }
2201
2202 static void
2203 gst_video_decoder_add_buffer_info (GstVideoDecoder * decoder,
2204     GstBuffer * buffer)
2205 {
2206   GstVideoDecoderPrivate *priv = decoder->priv;
2207   Timestamp *ts;
2208
2209   if (!GST_BUFFER_PTS_IS_VALID (buffer) &&
2210       !GST_BUFFER_DTS_IS_VALID (buffer) &&
2211       !GST_BUFFER_DURATION_IS_VALID (buffer) &&
2212       GST_BUFFER_FLAGS (buffer) == 0) {
2213     /* Save memory - don't bother storing info
2214      * for buffers with no distinguishing info */
2215     return;
2216   }
2217
2218   ts = g_slice_new (Timestamp);
2219
2220   GST_LOG_OBJECT (decoder,
2221       "adding PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT
2222       " (offset:%" G_GUINT64_FORMAT ")",
2223       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2224       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)), priv->input_offset);
2225
2226   ts->offset = priv->input_offset;
2227   ts->pts = GST_BUFFER_PTS (buffer);
2228   ts->dts = GST_BUFFER_DTS (buffer);
2229   ts->duration = GST_BUFFER_DURATION (buffer);
2230   ts->flags = GST_BUFFER_FLAGS (buffer);
2231
2232   g_queue_push_tail (&priv->timestamps, ts);
2233
2234   if (g_queue_get_length (&priv->timestamps) > 40) {
2235     GST_WARNING_OBJECT (decoder,
2236         "decoder timestamp list getting long: %d timestamps,"
2237         "possible internal leaking?", g_queue_get_length (&priv->timestamps));
2238   }
2239 }
2240
2241 static void
2242 gst_video_decoder_get_buffer_info_at_offset (GstVideoDecoder *
2243     decoder, guint64 offset, GstClockTime * pts, GstClockTime * dts,
2244     GstClockTime * duration, guint * flags)
2245 {
2246 #ifndef GST_DISABLE_GST_DEBUG
2247   guint64 got_offset = 0;
2248 #endif
2249   Timestamp *ts;
2250   GList *g;
2251
2252   *pts = GST_CLOCK_TIME_NONE;
2253   *dts = GST_CLOCK_TIME_NONE;
2254   *duration = GST_CLOCK_TIME_NONE;
2255   *flags = 0;
2256
2257   g = decoder->priv->timestamps.head;
2258   while (g) {
2259     ts = g->data;
2260     if (ts->offset <= offset) {
2261       GList *next = g->next;
2262 #ifndef GST_DISABLE_GST_DEBUG
2263       got_offset = ts->offset;
2264 #endif
2265       *pts = ts->pts;
2266       *dts = ts->dts;
2267       *duration = ts->duration;
2268       *flags = ts->flags;
2269       g_queue_delete_link (&decoder->priv->timestamps, g);
2270       g = next;
2271       timestamp_free (ts);
2272     } else {
2273       break;
2274     }
2275   }
2276
2277   GST_LOG_OBJECT (decoder,
2278       "got PTS %" GST_TIME_FORMAT " DTS %" GST_TIME_FORMAT " flags %x @ offs %"
2279       G_GUINT64_FORMAT " (wanted offset:%" G_GUINT64_FORMAT ")",
2280       GST_TIME_ARGS (*pts), GST_TIME_ARGS (*dts), *flags, got_offset, offset);
2281 }
2282
2283 #if !GLIB_CHECK_VERSION(2, 60, 0)
2284 #define g_queue_clear_full queue_clear_full
2285 static void
2286 queue_clear_full (GQueue * queue, GDestroyNotify free_func)
2287 {
2288   gpointer data;
2289
2290   while ((data = g_queue_pop_head (queue)) != NULL)
2291     free_func (data);
2292 }
2293 #endif
2294
2295 static void
2296 gst_video_decoder_clear_queues (GstVideoDecoder * dec)
2297 {
2298   GstVideoDecoderPrivate *priv = dec->priv;
2299
2300   g_list_free_full (priv->output_queued,
2301       (GDestroyNotify) gst_mini_object_unref);
2302   priv->output_queued = NULL;
2303
2304   g_list_free_full (priv->gather, (GDestroyNotify) gst_mini_object_unref);
2305   priv->gather = NULL;
2306   g_list_free_full (priv->decode, (GDestroyNotify) gst_video_codec_frame_unref);
2307   priv->decode = NULL;
2308   g_list_free_full (priv->parse, (GDestroyNotify) gst_mini_object_unref);
2309   priv->parse = NULL;
2310   g_list_free_full (priv->parse_gather,
2311       (GDestroyNotify) gst_video_codec_frame_unref);
2312   priv->parse_gather = NULL;
2313   g_queue_clear_full (&priv->frames,
2314       (GDestroyNotify) gst_video_codec_frame_unref);
2315 }
2316
2317 static void
2318 gst_video_decoder_reset (GstVideoDecoder * decoder, gboolean full,
2319     gboolean flush_hard)
2320 {
2321   GstVideoDecoderPrivate *priv = decoder->priv;
2322
2323   GST_DEBUG_OBJECT (decoder, "reset full %d", full);
2324
2325   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2326
2327   if (full || flush_hard) {
2328     gst_segment_init (&decoder->input_segment, GST_FORMAT_UNDEFINED);
2329     gst_segment_init (&decoder->output_segment, GST_FORMAT_UNDEFINED);
2330     gst_video_decoder_clear_queues (decoder);
2331     decoder->priv->in_out_segment_sync = TRUE;
2332
2333     if (priv->current_frame) {
2334       gst_video_codec_frame_unref (priv->current_frame);
2335       priv->current_frame = NULL;
2336     }
2337
2338     g_list_free_full (priv->current_frame_events,
2339         (GDestroyNotify) gst_event_unref);
2340     priv->current_frame_events = NULL;
2341     g_list_free_full (priv->pending_events, (GDestroyNotify) gst_event_unref);
2342     priv->pending_events = NULL;
2343
2344     priv->error_count = 0;
2345     priv->had_output_data = FALSE;
2346     priv->had_input_data = FALSE;
2347
2348     GST_OBJECT_LOCK (decoder);
2349     priv->earliest_time = GST_CLOCK_TIME_NONE;
2350     priv->proportion = 0.5;
2351     priv->decode_flags_override = FALSE;
2352
2353     priv->request_sync_point_flags = 0;
2354     priv->request_sync_point_frame_number = REQUEST_SYNC_POINT_UNSET;
2355     priv->last_force_key_unit_time = GST_CLOCK_TIME_NONE;
2356     GST_OBJECT_UNLOCK (decoder);
2357     priv->distance_from_sync = -1;
2358   }
2359
2360   if (full) {
2361     if (priv->input_state)
2362       gst_video_codec_state_unref (priv->input_state);
2363     priv->input_state = NULL;
2364     GST_OBJECT_LOCK (decoder);
2365     if (priv->output_state)
2366       gst_video_codec_state_unref (priv->output_state);
2367     priv->output_state = NULL;
2368
2369     priv->qos_frame_duration = 0;
2370     GST_OBJECT_UNLOCK (decoder);
2371
2372     if (priv->tags)
2373       gst_tag_list_unref (priv->tags);
2374     priv->tags = NULL;
2375     priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
2376     if (priv->upstream_tags) {
2377       gst_tag_list_unref (priv->upstream_tags);
2378       priv->upstream_tags = NULL;
2379     }
2380     priv->tags_changed = FALSE;
2381     priv->reordered_output = FALSE;
2382
2383     priv->dropped = 0;
2384     priv->processed = 0;
2385
2386     priv->decode_frame_number = 0;
2387     priv->base_picture_number = 0;
2388
2389     if (priv->pool) {
2390       GST_DEBUG_OBJECT (decoder, "deactivate pool %" GST_PTR_FORMAT,
2391           priv->pool);
2392       gst_buffer_pool_set_active (priv->pool, FALSE);
2393       gst_object_unref (priv->pool);
2394       priv->pool = NULL;
2395     }
2396
2397     if (priv->allocator) {
2398       gst_object_unref (priv->allocator);
2399       priv->allocator = NULL;
2400     }
2401   }
2402
2403   priv->discont = TRUE;
2404
2405   priv->base_timestamp = GST_CLOCK_TIME_NONE;
2406   priv->last_timestamp_out = GST_CLOCK_TIME_NONE;
2407   priv->pts_delta = GST_CLOCK_TIME_NONE;
2408
2409   priv->input_offset = 0;
2410   priv->frame_offset = 0;
2411   gst_adapter_clear (priv->input_adapter);
2412   gst_adapter_clear (priv->output_adapter);
2413   g_queue_clear_full (&priv->timestamps, (GDestroyNotify) timestamp_free);
2414
2415   GST_OBJECT_LOCK (decoder);
2416   priv->bytes_out = 0;
2417   priv->time = 0;
2418   GST_OBJECT_UNLOCK (decoder);
2419
2420 #ifndef GST_DISABLE_DEBUG
2421   priv->last_reset_time = gst_util_get_timestamp ();
2422 #endif
2423
2424   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2425 }
2426
2427 static GstFlowReturn
2428 gst_video_decoder_chain_forward (GstVideoDecoder * decoder,
2429     GstBuffer * buf, gboolean at_eos)
2430 {
2431   GstVideoDecoderPrivate *priv;
2432   GstVideoDecoderClass *klass;
2433   GstFlowReturn ret = GST_FLOW_OK;
2434
2435   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
2436   priv = decoder->priv;
2437
2438   g_return_val_if_fail (priv->packetized || klass->parse, GST_FLOW_ERROR);
2439
2440   /* Draining on DISCONT is handled in chain_reverse() for reverse playback,
2441    * and this function would only be called to get everything collected GOP
2442    * by GOP in the parse_gather list */
2443   if (decoder->input_segment.rate > 0.0 && GST_BUFFER_IS_DISCONT (buf)
2444       && (decoder->input_segment.flags & GST_SEEK_FLAG_TRICKMODE_KEY_UNITS))
2445     ret = gst_video_decoder_drain_out (decoder, FALSE);
2446
2447   if (priv->current_frame == NULL)
2448     priv->current_frame = gst_video_decoder_new_frame (decoder);
2449
2450   if (!priv->packetized)
2451     gst_video_decoder_add_buffer_info (decoder, buf);
2452
2453   priv->input_offset += gst_buffer_get_size (buf);
2454
2455   if (priv->packetized) {
2456     GstVideoCodecFrame *frame;
2457     gboolean was_keyframe = FALSE;
2458
2459     frame = priv->current_frame;
2460
2461     frame->abidata.ABI.num_subframes++;
2462     if (gst_video_decoder_get_subframe_mode (decoder)) {
2463       /* End the frame if the marker flag is set */
2464       if (!GST_BUFFER_FLAG_IS_SET (buf, GST_VIDEO_BUFFER_FLAG_MARKER)
2465           && (decoder->input_segment.rate > 0.0))
2466         priv->current_frame = gst_video_codec_frame_ref (frame);
2467       else
2468         priv->current_frame = NULL;
2469     } else {
2470       priv->current_frame = frame;
2471     }
2472
2473     if (!GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2474       was_keyframe = TRUE;
2475       GST_DEBUG_OBJECT (decoder, "Marking current_frame as sync point");
2476       GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (frame);
2477     }
2478
2479     if (frame->input_buffer) {
2480       gst_video_decoder_copy_metas (decoder, frame, frame->input_buffer, buf);
2481       gst_buffer_unref (frame->input_buffer);
2482     }
2483     frame->input_buffer = buf;
2484
2485     if (decoder->input_segment.rate < 0.0) {
2486       priv->parse_gather = g_list_prepend (priv->parse_gather, frame);
2487       priv->current_frame = NULL;
2488     } else {
2489       ret = gst_video_decoder_decode_frame (decoder, frame);
2490       if (!gst_video_decoder_get_subframe_mode (decoder))
2491         priv->current_frame = NULL;
2492     }
2493     /* If in trick mode and it was a keyframe, drain decoder to avoid extra
2494      * latency. Only do this for forwards playback as reverse playback handles
2495      * draining on keyframes in flush_parse(), and would otherwise call back
2496      * from drain_out() to here causing an infinite loop.
2497      * Also this function is only called for reverse playback to gather frames
2498      * GOP by GOP, and does not do any actual decoding. That would be done by
2499      * flush_decode() */
2500     if (ret == GST_FLOW_OK && was_keyframe && decoder->input_segment.rate > 0.0
2501         && (decoder->input_segment.flags & GST_SEEK_FLAG_TRICKMODE_KEY_UNITS))
2502       ret = gst_video_decoder_drain_out (decoder, FALSE);
2503   } else {
2504     gst_adapter_push (priv->input_adapter, buf);
2505
2506     ret = gst_video_decoder_parse_available (decoder, at_eos, TRUE);
2507   }
2508
2509   if (ret == GST_VIDEO_DECODER_FLOW_NEED_DATA)
2510     return GST_FLOW_OK;
2511
2512   return ret;
2513 }
2514
2515 static GstFlowReturn
2516 gst_video_decoder_flush_decode (GstVideoDecoder * dec)
2517 {
2518   GstVideoDecoderPrivate *priv = dec->priv;
2519   GstFlowReturn res = GST_FLOW_OK;
2520   GList *walk;
2521   GstVideoCodecFrame *current_frame = NULL;
2522   gboolean last_subframe;
2523   GST_DEBUG_OBJECT (dec, "flushing buffers to decode");
2524
2525   walk = priv->decode;
2526   while (walk) {
2527     GList *next;
2528     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
2529     last_subframe = TRUE;
2530     /* In subframe mode, we need to get rid of intermediary frames
2531      * created during the buffer gather stage. That's why that we keep a current
2532      * frame as the main frame and drop all the frame afterwhile until the end
2533      * of the subframes batch.
2534      * */
2535     if (gst_video_decoder_get_subframe_mode (dec)) {
2536       if (current_frame == NULL) {
2537         current_frame = gst_video_codec_frame_ref (frame);
2538       } else {
2539         if (current_frame->input_buffer) {
2540           gst_video_decoder_copy_metas (dec, current_frame,
2541               current_frame->input_buffer, current_frame->output_buffer);
2542           gst_buffer_unref (current_frame->input_buffer);
2543         }
2544         current_frame->input_buffer = gst_buffer_ref (frame->input_buffer);
2545         gst_video_codec_frame_unref (frame);
2546       }
2547       last_subframe = GST_BUFFER_FLAG_IS_SET (current_frame->input_buffer,
2548           GST_VIDEO_BUFFER_FLAG_MARKER);
2549     } else {
2550       current_frame = frame;
2551     }
2552
2553     GST_DEBUG_OBJECT (dec, "decoding frame %p buffer %p, PTS %" GST_TIME_FORMAT
2554         ", DTS %" GST_TIME_FORMAT, frame, frame->input_buffer,
2555         GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)),
2556         GST_TIME_ARGS (GST_BUFFER_DTS (frame->input_buffer)));
2557
2558     next = walk->next;
2559
2560     priv->decode = g_list_delete_link (priv->decode, walk);
2561
2562     /* decode buffer, resulting data prepended to queue */
2563     res = gst_video_decoder_decode_frame (dec, current_frame);
2564     if (res != GST_FLOW_OK)
2565       break;
2566     if (!gst_video_decoder_get_subframe_mode (dec)
2567         || last_subframe)
2568       current_frame = NULL;
2569     walk = next;
2570   }
2571
2572   return res;
2573 }
2574
2575 /* gst_video_decoder_flush_parse is called from the
2576  * chain_reverse() function when a buffer containing
2577  * a DISCONT - indicating that reverse playback
2578  * looped back to the next data block, and therefore
2579  * all available data should be fed through the
2580  * decoder and frames gathered for reversed output
2581  */
2582 static GstFlowReturn
2583 gst_video_decoder_flush_parse (GstVideoDecoder * dec, gboolean at_eos)
2584 {
2585   GstVideoDecoderPrivate *priv = dec->priv;
2586   GstFlowReturn res = GST_FLOW_OK;
2587   GList *walk;
2588   GstVideoDecoderClass *decoder_class;
2589
2590   decoder_class = GST_VIDEO_DECODER_GET_CLASS (dec);
2591
2592   GST_DEBUG_OBJECT (dec, "flushing buffers to parsing");
2593
2594   /* Reverse the gather list, and prepend it to the parse list,
2595    * then flush to parse whatever we can */
2596   priv->gather = g_list_reverse (priv->gather);
2597   priv->parse = g_list_concat (priv->gather, priv->parse);
2598   priv->gather = NULL;
2599
2600   /* clear buffer and decoder state */
2601   gst_video_decoder_flush (dec, FALSE);
2602
2603   walk = priv->parse;
2604   while (walk) {
2605     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
2606     GList *next = walk->next;
2607
2608     GST_DEBUG_OBJECT (dec, "parsing buffer %p, PTS %" GST_TIME_FORMAT
2609         ", DTS %" GST_TIME_FORMAT " flags %x", buf,
2610         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2611         GST_TIME_ARGS (GST_BUFFER_DTS (buf)), GST_BUFFER_FLAGS (buf));
2612
2613     /* parse buffer, resulting frames prepended to parse_gather queue */
2614     gst_buffer_ref (buf);
2615     res = gst_video_decoder_chain_forward (dec, buf, at_eos);
2616
2617     /* if we generated output, we can discard the buffer, else we
2618      * keep it in the queue */
2619     if (priv->parse_gather) {
2620       GST_DEBUG_OBJECT (dec, "parsed buffer to %p", priv->parse_gather->data);
2621       priv->parse = g_list_delete_link (priv->parse, walk);
2622       gst_buffer_unref (buf);
2623     } else {
2624       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
2625     }
2626     walk = next;
2627   }
2628
2629   walk = priv->parse_gather;
2630   while (walk) {
2631     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
2632     GList *walk2;
2633
2634     /* this is reverse playback, check if we need to apply some segment
2635      * to the output before decoding, as during decoding the segment.rate
2636      * must be used to determine if a buffer should be pushed or added to
2637      * the output list for reverse pushing.
2638      *
2639      * The new segment is not immediately pushed here because we must
2640      * wait for negotiation to happen before it can be pushed to avoid
2641      * pushing a segment before caps event. Negotiation only happens
2642      * when finish_frame is called.
2643      */
2644     for (walk2 = frame->events; walk2;) {
2645       GList *cur = walk2;
2646       GstEvent *event = walk2->data;
2647
2648       walk2 = g_list_next (walk2);
2649       if (GST_EVENT_TYPE (event) <= GST_EVENT_SEGMENT) {
2650
2651         if (GST_EVENT_TYPE (event) == GST_EVENT_SEGMENT) {
2652           GstSegment segment;
2653
2654           GST_DEBUG_OBJECT (dec, "Segment at frame %p %" GST_TIME_FORMAT,
2655               frame, GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)));
2656           gst_event_copy_segment (event, &segment);
2657           if (segment.format == GST_FORMAT_TIME) {
2658             dec->output_segment = segment;
2659             dec->priv->in_out_segment_sync =
2660                 gst_segment_is_equal (&dec->input_segment, &segment);
2661           }
2662         }
2663         dec->priv->pending_events =
2664             g_list_append (dec->priv->pending_events, event);
2665         frame->events = g_list_delete_link (frame->events, cur);
2666       }
2667     }
2668
2669     walk = walk->next;
2670   }
2671
2672   /* now we can process frames. Start by moving each frame from the parse_gather
2673    * to the decode list, reverse the order as we go, and stopping when/if we
2674    * copy a keyframe. */
2675   GST_DEBUG_OBJECT (dec, "checking parsed frames for a keyframe to decode");
2676   walk = priv->parse_gather;
2677   while (walk) {
2678     GstVideoCodecFrame *frame = (GstVideoCodecFrame *) (walk->data);
2679
2680     /* remove from the gather list */
2681     priv->parse_gather = g_list_remove_link (priv->parse_gather, walk);
2682
2683     /* move it to the front of the decode queue */
2684     priv->decode = g_list_concat (walk, priv->decode);
2685
2686     /* if we copied a keyframe, flush and decode the decode queue */
2687     if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
2688       GST_DEBUG_OBJECT (dec, "found keyframe %p with PTS %" GST_TIME_FORMAT
2689           ", DTS %" GST_TIME_FORMAT, frame,
2690           GST_TIME_ARGS (GST_BUFFER_PTS (frame->input_buffer)),
2691           GST_TIME_ARGS (GST_BUFFER_DTS (frame->input_buffer)));
2692       res = gst_video_decoder_flush_decode (dec);
2693       if (res != GST_FLOW_OK)
2694         goto done;
2695
2696       /* We need to tell the subclass to drain now.
2697        * We prefer the drain vfunc, but for backward-compat
2698        * we use a finish() vfunc if drain isn't implemented */
2699       if (decoder_class->drain) {
2700         GST_DEBUG_OBJECT (dec, "Draining");
2701         res = decoder_class->drain (dec);
2702       } else if (decoder_class->finish) {
2703         GST_FIXME_OBJECT (dec, "Sub-class should implement drain(). "
2704             "Calling finish() for backwards-compat");
2705         res = decoder_class->finish (dec);
2706       }
2707
2708       if (res != GST_FLOW_OK)
2709         goto done;
2710
2711       /* now send queued data downstream */
2712       walk = priv->output_queued;
2713       while (walk) {
2714         GstBuffer *buf = GST_BUFFER_CAST (walk->data);
2715
2716         priv->output_queued =
2717             g_list_delete_link (priv->output_queued, priv->output_queued);
2718
2719         if (G_LIKELY (res == GST_FLOW_OK)) {
2720           /* avoid stray DISCONT from forward processing,
2721            * which have no meaning in reverse pushing */
2722           GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
2723
2724           /* Last chance to calculate a timestamp as we loop backwards
2725            * through the list */
2726           if (GST_BUFFER_TIMESTAMP (buf) != GST_CLOCK_TIME_NONE)
2727             priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
2728           else if (priv->last_timestamp_out != GST_CLOCK_TIME_NONE &&
2729               GST_BUFFER_DURATION (buf) != GST_CLOCK_TIME_NONE) {
2730             GST_BUFFER_TIMESTAMP (buf) =
2731                 priv->last_timestamp_out - GST_BUFFER_DURATION (buf);
2732             priv->last_timestamp_out = GST_BUFFER_TIMESTAMP (buf);
2733             GST_LOG_OBJECT (dec,
2734                 "Calculated TS %" GST_TIME_FORMAT " working backwards",
2735                 GST_TIME_ARGS (priv->last_timestamp_out));
2736           }
2737
2738           res = gst_video_decoder_clip_and_push_buf (dec, buf);
2739         } else {
2740           gst_buffer_unref (buf);
2741         }
2742
2743         walk = priv->output_queued;
2744       }
2745
2746       /* clear buffer and decoder state again
2747        * before moving to the previous keyframe */
2748       gst_video_decoder_flush (dec, FALSE);
2749     }
2750
2751     walk = priv->parse_gather;
2752   }
2753
2754 done:
2755   return res;
2756 }
2757
2758 static GstFlowReturn
2759 gst_video_decoder_chain_reverse (GstVideoDecoder * dec, GstBuffer * buf)
2760 {
2761   GstVideoDecoderPrivate *priv = dec->priv;
2762   GstFlowReturn result = GST_FLOW_OK;
2763
2764   /* if we have a discont, move buffers to the decode list */
2765   if (!buf || GST_BUFFER_IS_DISCONT (buf)) {
2766     GST_DEBUG_OBJECT (dec, "received discont");
2767
2768     /* parse and decode stuff in the gather and parse queues */
2769     result = gst_video_decoder_flush_parse (dec, FALSE);
2770   }
2771
2772   if (G_LIKELY (buf)) {
2773     GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %" G_GSIZE_FORMAT ", "
2774         "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
2775         GST_TIME_FORMAT, buf, gst_buffer_get_size (buf),
2776         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2777         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2778         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
2779
2780     /* add buffer to gather queue */
2781     priv->gather = g_list_prepend (priv->gather, buf);
2782   }
2783
2784   return result;
2785 }
2786
2787 static GstFlowReturn
2788 gst_video_decoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buf)
2789 {
2790   GstVideoDecoder *decoder;
2791   GstFlowReturn ret = GST_FLOW_OK;
2792
2793   decoder = GST_VIDEO_DECODER (parent);
2794
2795   if (G_UNLIKELY (!decoder->priv->input_state && decoder->priv->needs_format))
2796     goto not_negotiated;
2797
2798   GST_LOG_OBJECT (decoder,
2799       "chain PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT " duration %"
2800       GST_TIME_FORMAT " size %" G_GSIZE_FORMAT " flags %x",
2801       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2802       GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2803       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)),
2804       gst_buffer_get_size (buf), GST_BUFFER_FLAGS (buf));
2805
2806   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2807
2808   /* NOTE:
2809    * requiring the pad to be negotiated makes it impossible to use
2810    * oggdemux or filesrc ! decoder */
2811
2812   if (decoder->input_segment.format == GST_FORMAT_UNDEFINED) {
2813     GstEvent *event;
2814     GstSegment *segment = &decoder->input_segment;
2815
2816     GST_WARNING_OBJECT (decoder,
2817         "Received buffer without a new-segment. "
2818         "Assuming timestamps start from 0.");
2819
2820     gst_segment_init (segment, GST_FORMAT_TIME);
2821
2822     event = gst_event_new_segment (segment);
2823
2824     decoder->priv->current_frame_events =
2825         g_list_prepend (decoder->priv->current_frame_events, event);
2826   }
2827
2828   decoder->priv->had_input_data = TRUE;
2829
2830   if (decoder->input_segment.rate > 0.0)
2831     ret = gst_video_decoder_chain_forward (decoder, buf, FALSE);
2832   else
2833     ret = gst_video_decoder_chain_reverse (decoder, buf);
2834
2835   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2836   return ret;
2837
2838   /* ERRORS */
2839 not_negotiated:
2840   {
2841     GST_ELEMENT_ERROR (decoder, CORE, NEGOTIATION, (NULL),
2842         ("decoder not initialized"));
2843     gst_buffer_unref (buf);
2844     return GST_FLOW_NOT_NEGOTIATED;
2845   }
2846 }
2847
2848 static GstStateChangeReturn
2849 gst_video_decoder_change_state (GstElement * element, GstStateChange transition)
2850 {
2851   GstVideoDecoder *decoder;
2852   GstVideoDecoderClass *decoder_class;
2853   GstStateChangeReturn ret;
2854
2855   decoder = GST_VIDEO_DECODER (element);
2856   decoder_class = GST_VIDEO_DECODER_GET_CLASS (element);
2857
2858   switch (transition) {
2859     case GST_STATE_CHANGE_NULL_TO_READY:
2860       /* open device/library if needed */
2861       if (decoder_class->open && !decoder_class->open (decoder))
2862         goto open_failed;
2863       break;
2864     case GST_STATE_CHANGE_READY_TO_PAUSED:
2865       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2866       gst_video_decoder_reset (decoder, TRUE, TRUE);
2867       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2868
2869       /* Initialize device/library if needed */
2870       if (decoder_class->start && !decoder_class->start (decoder))
2871         goto start_failed;
2872       break;
2873     default:
2874       break;
2875   }
2876
2877   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2878
2879   switch (transition) {
2880     case GST_STATE_CHANGE_PAUSED_TO_READY:{
2881       gboolean stopped = TRUE;
2882
2883       if (decoder_class->stop)
2884         stopped = decoder_class->stop (decoder);
2885
2886       GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2887       gst_video_decoder_reset (decoder, TRUE, TRUE);
2888       GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2889
2890       if (!stopped)
2891         goto stop_failed;
2892
2893       break;
2894     }
2895     case GST_STATE_CHANGE_READY_TO_NULL:
2896       /* close device/library if needed */
2897       if (decoder_class->close && !decoder_class->close (decoder))
2898         goto close_failed;
2899       break;
2900     default:
2901       break;
2902   }
2903
2904   return ret;
2905
2906   /* Errors */
2907 open_failed:
2908   {
2909     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2910         ("Failed to open decoder"));
2911     return GST_STATE_CHANGE_FAILURE;
2912   }
2913
2914 start_failed:
2915   {
2916     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2917         ("Failed to start decoder"));
2918     return GST_STATE_CHANGE_FAILURE;
2919   }
2920
2921 stop_failed:
2922   {
2923     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2924         ("Failed to stop decoder"));
2925     return GST_STATE_CHANGE_FAILURE;
2926   }
2927
2928 close_failed:
2929   {
2930     GST_ELEMENT_ERROR (decoder, LIBRARY, INIT, (NULL),
2931         ("Failed to close decoder"));
2932     return GST_STATE_CHANGE_FAILURE;
2933   }
2934 }
2935
2936 static GstVideoCodecFrame *
2937 gst_video_decoder_new_frame (GstVideoDecoder * decoder)
2938 {
2939   GstVideoDecoderPrivate *priv = decoder->priv;
2940   GstVideoCodecFrame *frame;
2941
2942   frame = g_slice_new0 (GstVideoCodecFrame);
2943
2944   frame->ref_count = 1;
2945
2946   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
2947   frame->system_frame_number = priv->system_frame_number;
2948   priv->system_frame_number++;
2949   frame->decode_frame_number = priv->decode_frame_number;
2950   priv->decode_frame_number++;
2951
2952   frame->dts = GST_CLOCK_TIME_NONE;
2953   frame->pts = GST_CLOCK_TIME_NONE;
2954   frame->duration = GST_CLOCK_TIME_NONE;
2955   frame->events = priv->current_frame_events;
2956   priv->current_frame_events = NULL;
2957
2958   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
2959
2960   GST_LOG_OBJECT (decoder, "Created new frame %p (sfn:%d)",
2961       frame, frame->system_frame_number);
2962
2963   return frame;
2964 }
2965
2966 static void
2967 gst_video_decoder_push_event_list (GstVideoDecoder * decoder, GList * events)
2968 {
2969   GList *l;
2970
2971   /* events are stored in reverse order */
2972   for (l = g_list_last (events); l; l = g_list_previous (l)) {
2973     GST_LOG_OBJECT (decoder, "pushing %s event", GST_EVENT_TYPE_NAME (l->data));
2974     gst_video_decoder_push_event (decoder, l->data);
2975   }
2976   g_list_free (events);
2977 }
2978
2979 static void
2980 gst_video_decoder_prepare_finish_frame (GstVideoDecoder *
2981     decoder, GstVideoCodecFrame * frame, gboolean dropping)
2982 {
2983   GstVideoDecoderPrivate *priv = decoder->priv;
2984   GList *l, *events = NULL;
2985   gboolean sync;
2986
2987 #ifndef GST_DISABLE_GST_DEBUG
2988   GST_LOG_OBJECT (decoder, "n %d in %" G_GSIZE_FORMAT " out %" G_GSIZE_FORMAT,
2989       priv->frames.length,
2990       gst_adapter_available (priv->input_adapter),
2991       gst_adapter_available (priv->output_adapter));
2992 #endif
2993
2994   sync = GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame);
2995
2996   GST_LOG_OBJECT (decoder,
2997       "finish frame %p (#%d)(sub=#%d) sync:%d PTS:%" GST_TIME_FORMAT " DTS:%"
2998       GST_TIME_FORMAT,
2999       frame, frame->system_frame_number, frame->abidata.ABI.num_subframes,
3000       sync, GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->dts));
3001
3002   /* Push all pending events that arrived before this frame */
3003   for (l = priv->frames.head; l; l = l->next) {
3004     GstVideoCodecFrame *tmp = l->data;
3005
3006     if (tmp->events) {
3007       events = g_list_concat (tmp->events, events);
3008       tmp->events = NULL;
3009     }
3010
3011     if (tmp == frame)
3012       break;
3013   }
3014
3015   if (dropping || !decoder->priv->output_state) {
3016     /* Push before the next frame that is not dropped */
3017     decoder->priv->pending_events =
3018         g_list_concat (events, decoder->priv->pending_events);
3019   } else {
3020     gst_video_decoder_push_event_list (decoder, decoder->priv->pending_events);
3021     decoder->priv->pending_events = NULL;
3022
3023     gst_video_decoder_push_event_list (decoder, events);
3024   }
3025
3026   /* Check if the data should not be displayed. For example altref/invisible
3027    * frame in vp8. In this case we should not update the timestamps. */
3028   if (GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame))
3029     return;
3030
3031   /* If the frame is meant to be output but we don't have an output_buffer
3032    * we have a problem :) */
3033   if (G_UNLIKELY ((frame->output_buffer == NULL) && !dropping))
3034     goto no_output_buffer;
3035
3036   if (GST_CLOCK_TIME_IS_VALID (frame->pts)) {
3037     if (frame->pts != priv->base_timestamp) {
3038       GST_DEBUG_OBJECT (decoder,
3039           "sync timestamp %" GST_TIME_FORMAT " diff %" GST_STIME_FORMAT,
3040           GST_TIME_ARGS (frame->pts),
3041           GST_STIME_ARGS (GST_CLOCK_DIFF (frame->pts,
3042                   decoder->output_segment.start)));
3043       priv->base_timestamp = frame->pts;
3044       priv->base_picture_number = frame->decode_frame_number;
3045     }
3046   }
3047
3048   if (frame->duration == GST_CLOCK_TIME_NONE) {
3049     frame->duration = gst_video_decoder_get_frame_duration (decoder, frame);
3050     GST_LOG_OBJECT (decoder,
3051         "Guessing duration %" GST_TIME_FORMAT " for frame...",
3052         GST_TIME_ARGS (frame->duration));
3053   }
3054
3055   /* PTS is expected montone ascending,
3056    * so a good guess is lowest unsent DTS */
3057   {
3058     GstClockTime min_ts = GST_CLOCK_TIME_NONE;
3059     GstVideoCodecFrame *oframe = NULL;
3060     gboolean seen_none = FALSE;
3061
3062     /* some maintenance regardless */
3063     for (l = priv->frames.head; l; l = l->next) {
3064       GstVideoCodecFrame *tmp = l->data;
3065
3066       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts)) {
3067         seen_none = TRUE;
3068         continue;
3069       }
3070
3071       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts < min_ts) {
3072         min_ts = tmp->abidata.ABI.ts;
3073         oframe = tmp;
3074       }
3075     }
3076     /* save a ts if needed */
3077     if (oframe && oframe != frame) {
3078       oframe->abidata.ABI.ts = frame->abidata.ABI.ts;
3079     }
3080
3081     /* and set if needed;
3082      * valid delta means we have reasonable DTS input */
3083     /* also, if we ended up reordered, means this approach is conflicting
3084      * with some sparse existing PTS, and so it does not work out */
3085     if (!priv->reordered_output &&
3086         !GST_CLOCK_TIME_IS_VALID (frame->pts) && !seen_none &&
3087         GST_CLOCK_TIME_IS_VALID (priv->pts_delta)) {
3088       frame->pts = min_ts + priv->pts_delta;
3089       GST_DEBUG_OBJECT (decoder,
3090           "no valid PTS, using oldest DTS %" GST_TIME_FORMAT,
3091           GST_TIME_ARGS (frame->pts));
3092     }
3093
3094     /* some more maintenance, ts2 holds PTS */
3095     min_ts = GST_CLOCK_TIME_NONE;
3096     seen_none = FALSE;
3097     for (l = priv->frames.head; l; l = l->next) {
3098       GstVideoCodecFrame *tmp = l->data;
3099
3100       if (!GST_CLOCK_TIME_IS_VALID (tmp->abidata.ABI.ts2)) {
3101         seen_none = TRUE;
3102         continue;
3103       }
3104
3105       if (!GST_CLOCK_TIME_IS_VALID (min_ts) || tmp->abidata.ABI.ts2 < min_ts) {
3106         min_ts = tmp->abidata.ABI.ts2;
3107         oframe = tmp;
3108       }
3109     }
3110     /* save a ts if needed */
3111     if (oframe && oframe != frame) {
3112       oframe->abidata.ABI.ts2 = frame->abidata.ABI.ts2;
3113     }
3114
3115     /* if we detected reordered output, then PTS are void,
3116      * however those were obtained; bogus input, subclass etc */
3117     if (priv->reordered_output && !seen_none) {
3118       GST_DEBUG_OBJECT (decoder, "invalidating PTS");
3119       frame->pts = GST_CLOCK_TIME_NONE;
3120     }
3121
3122     if (!GST_CLOCK_TIME_IS_VALID (frame->pts) && !seen_none) {
3123       frame->pts = min_ts;
3124       GST_DEBUG_OBJECT (decoder,
3125           "no valid PTS, using oldest PTS %" GST_TIME_FORMAT,
3126           GST_TIME_ARGS (frame->pts));
3127     }
3128   }
3129
3130
3131   if (frame->pts == GST_CLOCK_TIME_NONE) {
3132     /* Last ditch timestamp guess: Just add the duration to the previous
3133      * frame. If it's the first frame, just use the segment start. */
3134     if (frame->duration != GST_CLOCK_TIME_NONE) {
3135       if (GST_CLOCK_TIME_IS_VALID (priv->last_timestamp_out))
3136         frame->pts = priv->last_timestamp_out + frame->duration;
3137       else if (frame->dts != GST_CLOCK_TIME_NONE) {
3138         frame->pts = frame->dts;
3139         GST_LOG_OBJECT (decoder,
3140             "Setting DTS as PTS %" GST_TIME_FORMAT " for frame...",
3141             GST_TIME_ARGS (frame->pts));
3142       } else if (decoder->output_segment.rate > 0.0)
3143         frame->pts = decoder->output_segment.start;
3144       GST_INFO_OBJECT (decoder,
3145           "Guessing PTS=%" GST_TIME_FORMAT " for frame... DTS=%"
3146           GST_TIME_FORMAT, GST_TIME_ARGS (frame->pts),
3147           GST_TIME_ARGS (frame->dts));
3148     } else if (sync && frame->dts != GST_CLOCK_TIME_NONE) {
3149       frame->pts = frame->dts;
3150       GST_LOG_OBJECT (decoder,
3151           "Setting DTS as PTS %" GST_TIME_FORMAT " for frame...",
3152           GST_TIME_ARGS (frame->pts));
3153     }
3154   }
3155
3156   if (GST_CLOCK_TIME_IS_VALID (priv->last_timestamp_out)) {
3157     if (frame->pts < priv->last_timestamp_out) {
3158       GST_WARNING_OBJECT (decoder,
3159           "decreasing timestamp (%" GST_TIME_FORMAT " < %"
3160           GST_TIME_FORMAT ")",
3161           GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (priv->last_timestamp_out));
3162       priv->reordered_output = TRUE;
3163       /* make it a bit less weird downstream */
3164       frame->pts = priv->last_timestamp_out;
3165     }
3166   }
3167
3168   if (GST_CLOCK_TIME_IS_VALID (frame->pts))
3169     priv->last_timestamp_out = frame->pts;
3170
3171   return;
3172
3173   /* ERRORS */
3174 no_output_buffer:
3175   {
3176     GST_ERROR_OBJECT (decoder, "No buffer to output !");
3177   }
3178 }
3179
3180 /**
3181  * gst_video_decoder_release_frame:
3182  * @dec: a #GstVideoDecoder
3183  * @frame: (transfer full): the #GstVideoCodecFrame to release
3184  *
3185  * Similar to gst_video_decoder_drop_frame(), but simply releases @frame
3186  * without any processing other than removing it from list of pending frames,
3187  * after which it is considered finished and released.
3188  *
3189  * Since: 1.2.2
3190  */
3191 void
3192 gst_video_decoder_release_frame (GstVideoDecoder * dec,
3193     GstVideoCodecFrame * frame)
3194 {
3195   GList *link;
3196
3197   /* unref once from the list */
3198   GST_VIDEO_DECODER_STREAM_LOCK (dec);
3199   link = g_queue_find (&dec->priv->frames, frame);
3200   if (link) {
3201     gst_video_codec_frame_unref (frame);
3202     g_queue_delete_link (&dec->priv->frames, link);
3203   }
3204   if (frame->events) {
3205     dec->priv->pending_events =
3206         g_list_concat (frame->events, dec->priv->pending_events);
3207     frame->events = NULL;
3208   }
3209   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
3210
3211   /* unref because this function takes ownership */
3212   gst_video_codec_frame_unref (frame);
3213 }
3214
3215 /* called with STREAM_LOCK */
3216 static void
3217 gst_video_decoder_post_qos_drop (GstVideoDecoder * dec, GstClockTime timestamp)
3218 {
3219   GstClockTime stream_time, jitter, earliest_time, qostime;
3220   GstSegment *segment;
3221   GstMessage *qos_msg;
3222   gdouble proportion;
3223   dec->priv->dropped++;
3224
3225   /* post QoS message */
3226   GST_OBJECT_LOCK (dec);
3227   proportion = dec->priv->proportion;
3228   earliest_time = dec->priv->earliest_time;
3229   GST_OBJECT_UNLOCK (dec);
3230
3231   segment = &dec->output_segment;
3232   if (G_UNLIKELY (segment->format == GST_FORMAT_UNDEFINED))
3233     segment = &dec->input_segment;
3234   stream_time =
3235       gst_segment_to_stream_time (segment, GST_FORMAT_TIME, timestamp);
3236   qostime = gst_segment_to_running_time (segment, GST_FORMAT_TIME, timestamp);
3237   jitter = GST_CLOCK_DIFF (qostime, earliest_time);
3238   qos_msg =
3239       gst_message_new_qos (GST_OBJECT_CAST (dec), FALSE, qostime, stream_time,
3240       timestamp, GST_CLOCK_TIME_NONE);
3241   gst_message_set_qos_values (qos_msg, jitter, proportion, 1000000);
3242   gst_message_set_qos_stats (qos_msg, GST_FORMAT_BUFFERS,
3243       dec->priv->processed, dec->priv->dropped);
3244   gst_element_post_message (GST_ELEMENT_CAST (dec), qos_msg);
3245 }
3246
3247 /**
3248  * gst_video_decoder_drop_frame:
3249  * @dec: a #GstVideoDecoder
3250  * @frame: (transfer full): the #GstVideoCodecFrame to drop
3251  *
3252  * Similar to gst_video_decoder_finish_frame(), but drops @frame in any
3253  * case and posts a QoS message with the frame's details on the bus.
3254  * In any case, the frame is considered finished and released.
3255  *
3256  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
3257  */
3258 GstFlowReturn
3259 gst_video_decoder_drop_frame (GstVideoDecoder * dec, GstVideoCodecFrame * frame)
3260 {
3261   GST_LOG_OBJECT (dec, "drop frame %p", frame);
3262
3263   if (gst_video_decoder_get_subframe_mode (dec))
3264     GST_DEBUG_OBJECT (dec, "Drop subframe %d. Must be the last one.",
3265         frame->abidata.ABI.num_subframes);
3266
3267   GST_VIDEO_DECODER_STREAM_LOCK (dec);
3268
3269   gst_video_decoder_prepare_finish_frame (dec, frame, TRUE);
3270
3271   GST_DEBUG_OBJECT (dec, "dropping frame %" GST_TIME_FORMAT,
3272       GST_TIME_ARGS (frame->pts));
3273
3274   gst_video_decoder_post_qos_drop (dec, frame->pts);
3275
3276   /* now free the frame */
3277   gst_video_decoder_release_frame (dec, frame);
3278
3279   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
3280
3281   return GST_FLOW_OK;
3282 }
3283
3284 /**
3285  * gst_video_decoder_drop_subframe:
3286  * @dec: a #GstVideoDecoder
3287  * @frame: (transfer full): the #GstVideoCodecFrame
3288  *
3289  * Drops input data.
3290  * The frame is not considered finished until the whole frame
3291  * is finished or dropped by the subclass.
3292  *
3293  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
3294  *
3295  * Since: 1.20
3296  */
3297 GstFlowReturn
3298 gst_video_decoder_drop_subframe (GstVideoDecoder * dec,
3299     GstVideoCodecFrame * frame)
3300 {
3301   g_return_val_if_fail (gst_video_decoder_get_subframe_mode (dec),
3302       GST_FLOW_NOT_SUPPORTED);
3303
3304   GST_LOG_OBJECT (dec, "drop subframe %p num=%d", frame->input_buffer,
3305       gst_video_decoder_get_input_subframe_index (dec, frame));
3306
3307   GST_VIDEO_DECODER_STREAM_LOCK (dec);
3308
3309   gst_video_codec_frame_unref (frame);
3310
3311   GST_VIDEO_DECODER_STREAM_UNLOCK (dec);
3312
3313   return GST_FLOW_OK;
3314 }
3315
3316 static gboolean
3317 gst_video_decoder_transform_meta_default (GstVideoDecoder *
3318     decoder, GstVideoCodecFrame * frame, GstMeta * meta)
3319 {
3320   const GstMetaInfo *info = meta->info;
3321   const gchar *const *tags;
3322   const gchar *const supported_tags[] = {
3323     GST_META_TAG_VIDEO_STR,
3324     GST_META_TAG_VIDEO_ORIENTATION_STR,
3325     GST_META_TAG_VIDEO_SIZE_STR,
3326     NULL,
3327   };
3328
3329   tags = gst_meta_api_type_get_tags (info->api);
3330
3331   if (!tags)
3332     return TRUE;
3333
3334   while (*tags) {
3335     if (!g_strv_contains (supported_tags, *tags))
3336       return FALSE;
3337     tags++;
3338   }
3339
3340   return TRUE;
3341 }
3342
3343 typedef struct
3344 {
3345   GstVideoDecoder *decoder;
3346   GstVideoCodecFrame *frame;
3347   GstBuffer *buffer;
3348 } CopyMetaData;
3349
3350 static gboolean
3351 foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
3352 {
3353   CopyMetaData *data = user_data;
3354   GstVideoDecoder *decoder = data->decoder;
3355   GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
3356   GstVideoCodecFrame *frame = data->frame;
3357   GstBuffer *buffer = data->buffer;
3358   const GstMetaInfo *info = (*meta)->info;
3359   gboolean do_copy = FALSE;
3360
3361   if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
3362     /* never call the transform_meta with memory specific metadata */
3363     GST_DEBUG_OBJECT (decoder, "not copying memory specific metadata %s",
3364         g_type_name (info->api));
3365     do_copy = FALSE;
3366   } else if (klass->transform_meta) {
3367     do_copy = klass->transform_meta (decoder, frame, *meta);
3368     GST_DEBUG_OBJECT (decoder, "transformed metadata %s: copy: %d",
3369         g_type_name (info->api), do_copy);
3370   }
3371
3372   /* we only copy metadata when the subclass implemented a transform_meta
3373    * function and when it returns %TRUE */
3374   if (do_copy && info->transform_func) {
3375     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
3376     GST_DEBUG_OBJECT (decoder, "copy metadata %s", g_type_name (info->api));
3377     /* simply copy then */
3378
3379     info->transform_func (buffer, *meta, inbuf, _gst_meta_transform_copy,
3380         &copy_data);
3381   }
3382   return TRUE;
3383 }
3384
3385 static void
3386 gst_video_decoder_copy_metas (GstVideoDecoder * decoder,
3387     GstVideoCodecFrame * frame, GstBuffer * src_buffer, GstBuffer * dest_buffer)
3388 {
3389   GstVideoDecoderClass *decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
3390
3391   if (decoder_class->transform_meta) {
3392     if (G_LIKELY (frame)) {
3393       CopyMetaData data;
3394
3395       data.decoder = decoder;
3396       data.frame = frame;
3397       data.buffer = dest_buffer;
3398       gst_buffer_foreach_meta (src_buffer, foreach_metadata, &data);
3399     } else {
3400       GST_WARNING_OBJECT (decoder,
3401           "Can't copy metadata because input frame disappeared");
3402     }
3403   }
3404 }
3405
3406 /**
3407  * gst_video_decoder_finish_frame:
3408  * @decoder: a #GstVideoDecoder
3409  * @frame: (transfer full): a decoded #GstVideoCodecFrame
3410  *
3411  * @frame should have a valid decoded data buffer, whose metadata fields
3412  * are then appropriately set according to frame data and pushed downstream.
3413  * If no output data is provided, @frame is considered skipped.
3414  * In any case, the frame is considered finished and released.
3415  *
3416  * After calling this function the output buffer of the frame is to be
3417  * considered read-only. This function will also change the metadata
3418  * of the buffer.
3419  *
3420  * Returns: a #GstFlowReturn resulting from sending data downstream
3421  */
3422 GstFlowReturn
3423 gst_video_decoder_finish_frame (GstVideoDecoder * decoder,
3424     GstVideoCodecFrame * frame)
3425 {
3426   GstFlowReturn ret = GST_FLOW_OK;
3427   GstVideoDecoderPrivate *priv = decoder->priv;
3428   GstBuffer *output_buffer;
3429   gboolean needs_reconfigure = FALSE;
3430
3431   GST_LOG_OBJECT (decoder, "finish frame %p", frame);
3432
3433   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3434
3435   needs_reconfigure = gst_pad_check_reconfigure (decoder->srcpad);
3436   if (G_UNLIKELY (priv->output_state_changed || (priv->output_state
3437               && needs_reconfigure))) {
3438     if (!gst_video_decoder_negotiate_unlocked (decoder)) {
3439       gst_pad_mark_reconfigure (decoder->srcpad);
3440       if (GST_PAD_IS_FLUSHING (decoder->srcpad))
3441         ret = GST_FLOW_FLUSHING;
3442       else
3443         ret = GST_FLOW_NOT_NEGOTIATED;
3444       goto done;
3445     }
3446   }
3447
3448   gst_video_decoder_prepare_finish_frame (decoder, frame, FALSE);
3449   priv->processed++;
3450
3451   if (priv->tags_changed) {
3452     GstEvent *tags_event;
3453
3454     tags_event = gst_video_decoder_create_merged_tags_event (decoder);
3455
3456     if (tags_event != NULL)
3457       gst_video_decoder_push_event (decoder, tags_event);
3458
3459     priv->tags_changed = FALSE;
3460   }
3461
3462   /* no buffer data means this frame is skipped */
3463   if (!frame->output_buffer || GST_VIDEO_CODEC_FRAME_IS_DECODE_ONLY (frame)) {
3464     GST_DEBUG_OBJECT (decoder,
3465         "skipping frame %" GST_TIME_FORMAT " because not output was produced",
3466         GST_TIME_ARGS (frame->pts));
3467     goto done;
3468   }
3469
3470   /* Mark output as corrupted if the subclass requested so and we're either
3471    * still before the sync point after the request, or we don't even know the
3472    * frame number of the sync point yet (it is 0) */
3473   GST_OBJECT_LOCK (decoder);
3474   if (frame->system_frame_number <= priv->request_sync_point_frame_number
3475       && priv->request_sync_point_frame_number != REQUEST_SYNC_POINT_UNSET) {
3476     if (priv->request_sync_point_flags &
3477         GST_VIDEO_DECODER_REQUEST_SYNC_POINT_CORRUPT_OUTPUT) {
3478       GST_DEBUG_OBJECT (decoder,
3479           "marking frame %" GST_TIME_FORMAT
3480           " as corrupted because it is still before the sync point",
3481           GST_TIME_ARGS (frame->pts));
3482       GST_VIDEO_CODEC_FRAME_FLAG_SET (frame,
3483           GST_VIDEO_CODEC_FRAME_FLAG_CORRUPTED);
3484     }
3485   } else {
3486     /* Reset to -1 to mark it as unset now that we've reached the frame */
3487     priv->request_sync_point_frame_number = REQUEST_SYNC_POINT_UNSET;
3488   }
3489   GST_OBJECT_UNLOCK (decoder);
3490
3491   if (priv->discard_corrupted_frames
3492       && (GST_VIDEO_CODEC_FRAME_FLAG_IS_SET (frame,
3493               GST_VIDEO_CODEC_FRAME_FLAG_CORRUPTED)
3494           || GST_BUFFER_FLAG_IS_SET (frame->output_buffer,
3495               GST_BUFFER_FLAG_CORRUPTED))) {
3496     GST_DEBUG_OBJECT (decoder,
3497         "skipping frame %" GST_TIME_FORMAT " because it is corrupted",
3498         GST_TIME_ARGS (frame->pts));
3499     goto done;
3500   }
3501
3502   /* We need a writable buffer for the metadata changes below */
3503   output_buffer = frame->output_buffer =
3504       gst_buffer_make_writable (frame->output_buffer);
3505
3506   GST_BUFFER_FLAG_UNSET (output_buffer, GST_BUFFER_FLAG_DELTA_UNIT);
3507
3508   GST_BUFFER_PTS (output_buffer) = frame->pts;
3509   GST_BUFFER_DTS (output_buffer) = GST_CLOCK_TIME_NONE;
3510   GST_BUFFER_DURATION (output_buffer) = frame->duration;
3511
3512   GST_BUFFER_OFFSET (output_buffer) = GST_BUFFER_OFFSET_NONE;
3513   GST_BUFFER_OFFSET_END (output_buffer) = GST_BUFFER_OFFSET_NONE;
3514
3515   if (priv->discont) {
3516     GST_BUFFER_FLAG_SET (output_buffer, GST_BUFFER_FLAG_DISCONT);
3517   }
3518
3519   if (GST_VIDEO_CODEC_FRAME_FLAG_IS_SET (frame,
3520           GST_VIDEO_CODEC_FRAME_FLAG_CORRUPTED)) {
3521     GST_DEBUG_OBJECT (decoder,
3522         "marking frame %" GST_TIME_FORMAT " as corrupted",
3523         GST_TIME_ARGS (frame->pts));
3524     GST_BUFFER_FLAG_SET (output_buffer, GST_BUFFER_FLAG_CORRUPTED);
3525   }
3526
3527   gst_video_decoder_copy_metas (decoder, frame, frame->input_buffer,
3528       frame->output_buffer);
3529
3530   /* Get an additional ref to the buffer, which is going to be pushed
3531    * downstream, the original ref is owned by the frame
3532    */
3533   output_buffer = gst_buffer_ref (output_buffer);
3534
3535   /* Release frame so the buffer is writable when we push it downstream
3536    * if possible, i.e. if the subclass does not hold additional references
3537    * to the frame
3538    */
3539   gst_video_decoder_release_frame (decoder, frame);
3540   frame = NULL;
3541
3542   if (decoder->output_segment.rate < 0.0
3543       && !(decoder->output_segment.flags & GST_SEEK_FLAG_TRICKMODE_KEY_UNITS)) {
3544     GST_LOG_OBJECT (decoder, "queued frame");
3545     priv->output_queued = g_list_prepend (priv->output_queued, output_buffer);
3546   } else {
3547     ret = gst_video_decoder_clip_and_push_buf (decoder, output_buffer);
3548   }
3549
3550 done:
3551   if (frame)
3552     gst_video_decoder_release_frame (decoder, frame);
3553   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3554   return ret;
3555 }
3556
3557 /**
3558  * gst_video_decoder_finish_subframe:
3559  * @decoder: a #GstVideoDecoder
3560  * @frame: (transfer full): the #GstVideoCodecFrame
3561  *
3562  * Indicate that a subframe has been finished to be decoded
3563  * by the subclass. This method should be called for all subframes
3564  * except the last subframe where @gst_video_decoder_finish_frame
3565  * should be called instead.
3566  *
3567  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
3568  *
3569  * Since: 1.20
3570  */
3571 GstFlowReturn
3572 gst_video_decoder_finish_subframe (GstVideoDecoder * decoder,
3573     GstVideoCodecFrame * frame)
3574 {
3575   g_return_val_if_fail (gst_video_decoder_get_subframe_mode (decoder),
3576       GST_FLOW_NOT_SUPPORTED);
3577
3578   GST_LOG_OBJECT (decoder, "finish subframe %p num=%d", frame->input_buffer,
3579       gst_video_decoder_get_input_subframe_index (decoder, frame));
3580
3581   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3582   frame->abidata.ABI.subframes_processed++;
3583   gst_video_codec_frame_unref (frame);
3584
3585   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3586
3587   return GST_FLOW_OK;
3588 }
3589
3590 /* With stream lock, takes the frame reference */
3591 static GstFlowReturn
3592 gst_video_decoder_clip_and_push_buf (GstVideoDecoder * decoder, GstBuffer * buf)
3593 {
3594   GstFlowReturn ret = GST_FLOW_OK;
3595   GstVideoDecoderPrivate *priv = decoder->priv;
3596   guint64 start, stop;
3597   guint64 cstart, cstop;
3598   GstSegment *segment;
3599   GstClockTime duration;
3600
3601   /* Check for clipping */
3602   start = GST_BUFFER_PTS (buf);
3603   duration = GST_BUFFER_DURATION (buf);
3604
3605   /* store that we have valid decoded data */
3606   priv->had_output_data = TRUE;
3607
3608   stop = GST_CLOCK_TIME_NONE;
3609
3610   if (GST_CLOCK_TIME_IS_VALID (start) && GST_CLOCK_TIME_IS_VALID (duration)) {
3611     stop = start + duration;
3612   } else if (GST_CLOCK_TIME_IS_VALID (start)
3613       && !GST_CLOCK_TIME_IS_VALID (duration)) {
3614     /* If we don't clip away buffers that far before the segment we
3615      * can cause the pipeline to lockup. This can happen if audio is
3616      * properly clipped, and thus the audio sink does not preroll yet
3617      * but the video sink prerolls because we already outputted a
3618      * buffer here... and then queues run full.
3619      *
3620      * In the worst case we will clip one buffer too many here now if no
3621      * framerate is given, no buffer duration is given and the actual
3622      * framerate is lower than 25fps */
3623     stop = start + 40 * GST_MSECOND;
3624   }
3625
3626   segment = &decoder->output_segment;
3627   if (gst_segment_clip (segment, GST_FORMAT_TIME, start, stop, &cstart, &cstop)) {
3628     GST_BUFFER_PTS (buf) = cstart;
3629
3630     if (stop != GST_CLOCK_TIME_NONE && GST_CLOCK_TIME_IS_VALID (duration))
3631       GST_BUFFER_DURATION (buf) = cstop - cstart;
3632
3633     GST_LOG_OBJECT (decoder,
3634         "accepting buffer inside segment: %" GST_TIME_FORMAT " %"
3635         GST_TIME_FORMAT " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
3636         " time %" GST_TIME_FORMAT,
3637         GST_TIME_ARGS (cstart),
3638         GST_TIME_ARGS (cstop),
3639         GST_TIME_ARGS (segment->start), GST_TIME_ARGS (segment->stop),
3640         GST_TIME_ARGS (segment->time));
3641   } else {
3642     GST_LOG_OBJECT (decoder,
3643         "dropping buffer outside segment: %" GST_TIME_FORMAT
3644         " %" GST_TIME_FORMAT
3645         " seg %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT
3646         " time %" GST_TIME_FORMAT,
3647         GST_TIME_ARGS (start), GST_TIME_ARGS (stop),
3648         GST_TIME_ARGS (segment->start),
3649         GST_TIME_ARGS (segment->stop), GST_TIME_ARGS (segment->time));
3650     /* only check and return EOS if upstream still
3651      * in the same segment and interested as such */
3652     if (decoder->priv->in_out_segment_sync) {
3653       if (segment->rate >= 0) {
3654         if (GST_BUFFER_PTS (buf) >= segment->stop)
3655           ret = GST_FLOW_EOS;
3656       } else if (GST_BUFFER_PTS (buf) < segment->start) {
3657         ret = GST_FLOW_EOS;
3658       }
3659     }
3660     gst_buffer_unref (buf);
3661     goto done;
3662   }
3663
3664   /* Is buffer too late (QoS) ? */
3665   if (priv->do_qos && GST_CLOCK_TIME_IS_VALID (priv->earliest_time)
3666       && GST_CLOCK_TIME_IS_VALID (cstart)) {
3667     GstClockTime deadline =
3668         gst_segment_to_running_time (segment, GST_FORMAT_TIME, cstart);
3669     if (GST_CLOCK_TIME_IS_VALID (deadline) && deadline < priv->earliest_time) {
3670       GST_WARNING_OBJECT (decoder,
3671           "Dropping frame due to QoS. start:%" GST_TIME_FORMAT " deadline:%"
3672           GST_TIME_FORMAT " earliest_time:%" GST_TIME_FORMAT,
3673           GST_TIME_ARGS (start), GST_TIME_ARGS (deadline),
3674           GST_TIME_ARGS (priv->earliest_time));
3675       gst_video_decoder_post_qos_drop (decoder, cstart);
3676       gst_buffer_unref (buf);
3677       priv->discont = TRUE;
3678       goto done;
3679     }
3680   }
3681
3682   /* Set DISCONT flag here ! */
3683
3684   if (priv->discont) {
3685     GST_DEBUG_OBJECT (decoder, "Setting discont on output buffer");
3686     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
3687     priv->discont = FALSE;
3688   }
3689
3690   /* update rate estimate */
3691   GST_OBJECT_LOCK (decoder);
3692   priv->bytes_out += gst_buffer_get_size (buf);
3693   if (GST_CLOCK_TIME_IS_VALID (duration)) {
3694     priv->time += duration;
3695   } else {
3696     /* FIXME : Use difference between current and previous outgoing
3697      * timestamp, and relate to difference between current and previous
3698      * bytes */
3699     /* better none than nothing valid */
3700     priv->time = GST_CLOCK_TIME_NONE;
3701   }
3702   GST_OBJECT_UNLOCK (decoder);
3703
3704   GST_DEBUG_OBJECT (decoder, "pushing buffer %p of size %" G_GSIZE_FORMAT ", "
3705       "PTS %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
3706       gst_buffer_get_size (buf),
3707       GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
3708       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
3709
3710   /* we got data, so note things are looking up again, reduce
3711    * the error count, if there is one */
3712   if (G_UNLIKELY (priv->error_count))
3713     priv->error_count = 0;
3714
3715 #ifndef GST_DISABLE_DEBUG
3716   if (G_UNLIKELY (priv->last_reset_time != GST_CLOCK_TIME_NONE)) {
3717     GstClockTime elapsed = gst_util_get_timestamp () - priv->last_reset_time;
3718
3719     /* First buffer since reset, report how long we took */
3720     GST_INFO_OBJECT (decoder, "First buffer since flush took %" GST_TIME_FORMAT
3721         " to produce", GST_TIME_ARGS (elapsed));
3722     priv->last_reset_time = GST_CLOCK_TIME_NONE;
3723   }
3724 #endif
3725
3726   /* release STREAM_LOCK not to block upstream
3727    * while pushing buffer downstream */
3728   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3729   ret = gst_pad_push (decoder->srcpad, buf);
3730   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3731
3732 done:
3733   return ret;
3734 }
3735
3736 /**
3737  * gst_video_decoder_add_to_frame:
3738  * @decoder: a #GstVideoDecoder
3739  * @n_bytes: the number of bytes to add
3740  *
3741  * Removes next @n_bytes of input data and adds it to currently parsed frame.
3742  */
3743 void
3744 gst_video_decoder_add_to_frame (GstVideoDecoder * decoder, int n_bytes)
3745 {
3746   GstVideoDecoderPrivate *priv = decoder->priv;
3747   GstBuffer *buf;
3748
3749   GST_LOG_OBJECT (decoder, "add %d bytes to frame", n_bytes);
3750
3751   if (n_bytes == 0)
3752     return;
3753
3754   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3755   if (gst_adapter_available (priv->output_adapter) == 0) {
3756     priv->frame_offset =
3757         priv->input_offset - gst_adapter_available (priv->input_adapter);
3758   }
3759   buf = gst_adapter_take_buffer (priv->input_adapter, n_bytes);
3760
3761   gst_adapter_push (priv->output_adapter, buf);
3762   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3763 }
3764
3765 /**
3766  * gst_video_decoder_get_pending_frame_size:
3767  * @decoder: a #GstVideoDecoder
3768  *
3769  * Returns the number of bytes previously added to the current frame
3770  * by calling gst_video_decoder_add_to_frame().
3771  *
3772  * Returns: The number of bytes pending for the current frame
3773  *
3774  * Since: 1.4
3775  */
3776 gsize
3777 gst_video_decoder_get_pending_frame_size (GstVideoDecoder * decoder)
3778 {
3779   GstVideoDecoderPrivate *priv = decoder->priv;
3780   gsize ret;
3781
3782   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3783   ret = gst_adapter_available (priv->output_adapter);
3784   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3785
3786   GST_LOG_OBJECT (decoder, "Current pending frame has %" G_GSIZE_FORMAT "bytes",
3787       ret);
3788
3789   return ret;
3790 }
3791
3792 static guint64
3793 gst_video_decoder_get_frame_duration (GstVideoDecoder * decoder,
3794     GstVideoCodecFrame * frame)
3795 {
3796   GstVideoCodecState *state = decoder->priv->output_state;
3797
3798   /* it's possible that we don't have a state yet when we are dropping the
3799    * initial buffers */
3800   if (state == NULL)
3801     return GST_CLOCK_TIME_NONE;
3802
3803   if (state->info.fps_d == 0 || state->info.fps_n == 0) {
3804     return GST_CLOCK_TIME_NONE;
3805   }
3806
3807   /* FIXME: For interlaced frames this needs to take into account
3808    * the number of valid fields in the frame
3809    */
3810
3811   return gst_util_uint64_scale (GST_SECOND, state->info.fps_d,
3812       state->info.fps_n);
3813 }
3814
3815 /**
3816  * gst_video_decoder_have_frame:
3817  * @decoder: a #GstVideoDecoder
3818  *
3819  * Gathers all data collected for currently parsed frame, gathers corresponding
3820  * metadata and passes it along for further processing, i.e. @handle_frame.
3821  *
3822  * Returns: a #GstFlowReturn
3823  */
3824 GstFlowReturn
3825 gst_video_decoder_have_frame (GstVideoDecoder * decoder)
3826 {
3827   GstVideoDecoderPrivate *priv = decoder->priv;
3828   GstBuffer *buffer;
3829   int n_available;
3830   GstClockTime pts, dts, duration;
3831   guint flags;
3832   GstFlowReturn ret = GST_FLOW_OK;
3833
3834   GST_LOG_OBJECT (decoder, "have_frame at offset %" G_GUINT64_FORMAT,
3835       priv->frame_offset);
3836
3837   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
3838
3839   n_available = gst_adapter_available (priv->output_adapter);
3840   if (n_available) {
3841     buffer = gst_adapter_take_buffer (priv->output_adapter, n_available);
3842   } else {
3843     buffer = gst_buffer_new_and_alloc (0);
3844   }
3845
3846   if (priv->current_frame->input_buffer) {
3847     gst_video_decoder_copy_metas (decoder, priv->current_frame,
3848         priv->current_frame->input_buffer, buffer);
3849     gst_buffer_unref (priv->current_frame->input_buffer);
3850   }
3851   priv->current_frame->input_buffer = buffer;
3852
3853   gst_video_decoder_get_buffer_info_at_offset (decoder,
3854       priv->frame_offset, &pts, &dts, &duration, &flags);
3855
3856   GST_BUFFER_PTS (buffer) = pts;
3857   GST_BUFFER_DTS (buffer) = dts;
3858   GST_BUFFER_DURATION (buffer) = duration;
3859   GST_BUFFER_FLAGS (buffer) = flags;
3860
3861   GST_LOG_OBJECT (decoder, "collected frame size %d, "
3862       "PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dur %"
3863       GST_TIME_FORMAT, n_available, GST_TIME_ARGS (pts), GST_TIME_ARGS (dts),
3864       GST_TIME_ARGS (duration));
3865
3866   if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT)) {
3867     GST_DEBUG_OBJECT (decoder, "Marking as sync point");
3868     GST_VIDEO_CODEC_FRAME_SET_SYNC_POINT (priv->current_frame);
3869   }
3870
3871   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_CORRUPTED)) {
3872     GST_DEBUG_OBJECT (decoder, "Marking as corrupted");
3873     GST_VIDEO_CODEC_FRAME_FLAG_SET (priv->current_frame,
3874         GST_VIDEO_CODEC_FRAME_FLAG_CORRUPTED);
3875   }
3876
3877   /* In reverse playback, just capture and queue frames for later processing */
3878   if (decoder->input_segment.rate < 0.0) {
3879     priv->parse_gather =
3880         g_list_prepend (priv->parse_gather, priv->current_frame);
3881     priv->current_frame = NULL;
3882   } else {
3883     GstVideoCodecFrame *frame = priv->current_frame;
3884     frame->abidata.ABI.num_subframes++;
3885     /* In subframe mode, we keep a ref for ourselves
3886      * as this frame will be kept during the data collection
3887      * in parsed mode. The frame reference will be released by
3888      * finish_(sub)frame or drop_(sub)frame.*/
3889     if (gst_video_decoder_get_subframe_mode (decoder))
3890       gst_video_codec_frame_ref (priv->current_frame);
3891     else
3892       priv->current_frame = NULL;
3893
3894     /* Decode the frame, which gives away our ref */
3895     ret = gst_video_decoder_decode_frame (decoder, frame);
3896   }
3897
3898   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
3899
3900   return ret;
3901 }
3902
3903 /* Pass the frame in priv->current_frame through the
3904  * handle_frame() callback for decoding and passing to gvd_finish_frame(),
3905  * or dropping by passing to gvd_drop_frame() */
3906 static GstFlowReturn
3907 gst_video_decoder_decode_frame (GstVideoDecoder * decoder,
3908     GstVideoCodecFrame * frame)
3909 {
3910   GstVideoDecoderPrivate *priv = decoder->priv;
3911   GstVideoDecoderClass *decoder_class;
3912   GstFlowReturn ret = GST_FLOW_OK;
3913
3914   decoder_class = GST_VIDEO_DECODER_GET_CLASS (decoder);
3915
3916   /* FIXME : This should only have to be checked once (either the subclass has an
3917    * implementation, or it doesn't) */
3918   g_return_val_if_fail (decoder_class->handle_frame != NULL, GST_FLOW_ERROR);
3919   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
3920
3921   frame->pts = GST_BUFFER_PTS (frame->input_buffer);
3922   frame->dts = GST_BUFFER_DTS (frame->input_buffer);
3923   frame->duration = GST_BUFFER_DURATION (frame->input_buffer);
3924
3925   /* For keyframes, PTS = DTS + constant_offset, usually 0 to 3 frame
3926    * durations. */
3927   /* FIXME upstream can be quite wrong about the keyframe aspect,
3928    * so we could be going off here as well,
3929    * maybe let subclass decide if it really is/was a keyframe */
3930   if (GST_VIDEO_CODEC_FRAME_IS_SYNC_POINT (frame)) {
3931     priv->distance_from_sync = 0;
3932
3933     GST_OBJECT_LOCK (decoder);
3934     priv->request_sync_point_flags &=
3935         ~GST_VIDEO_DECODER_REQUEST_SYNC_POINT_DISCARD_INPUT;
3936     if (priv->request_sync_point_frame_number == REQUEST_SYNC_POINT_PENDING)
3937       priv->request_sync_point_frame_number = frame->system_frame_number;
3938     GST_OBJECT_UNLOCK (decoder);
3939
3940     if (GST_CLOCK_TIME_IS_VALID (frame->pts)
3941         && GST_CLOCK_TIME_IS_VALID (frame->dts)) {
3942       /* just in case they are not equal as might ideally be,
3943        * e.g. quicktime has a (positive) delta approach */
3944       priv->pts_delta = frame->pts - frame->dts;
3945       GST_DEBUG_OBJECT (decoder, "PTS delta %d ms",
3946           (gint) (priv->pts_delta / GST_MSECOND));
3947     }
3948   } else {
3949     if (priv->distance_from_sync == -1 && priv->automatic_request_sync_points) {
3950       GST_DEBUG_OBJECT (decoder,
3951           "Didn't receive a keyframe yet, requesting sync point");
3952       gst_video_decoder_request_sync_point (decoder, frame,
3953           priv->automatic_request_sync_point_flags);
3954     }
3955
3956     GST_OBJECT_LOCK (decoder);
3957     if ((priv->needs_sync_point && priv->distance_from_sync == -1)
3958         || (priv->request_sync_point_flags &
3959             GST_VIDEO_DECODER_REQUEST_SYNC_POINT_DISCARD_INPUT)) {
3960       GST_WARNING_OBJECT (decoder,
3961           "Subclass requires a sync point but we didn't receive one yet, discarding input");
3962       GST_OBJECT_UNLOCK (decoder);
3963       gst_video_decoder_release_frame (decoder, frame);
3964       return GST_FLOW_OK;
3965     }
3966     GST_OBJECT_UNLOCK (decoder);
3967
3968     priv->distance_from_sync++;
3969   }
3970
3971   frame->distance_from_sync = priv->distance_from_sync;
3972
3973   if (frame->abidata.ABI.num_subframes == 1) {
3974     frame->abidata.ABI.ts = frame->dts;
3975     frame->abidata.ABI.ts2 = frame->pts;
3976   }
3977
3978   GST_LOG_OBJECT (decoder,
3979       "frame %p PTS %" GST_TIME_FORMAT ", DTS %" GST_TIME_FORMAT ", dist %d",
3980       frame, GST_TIME_ARGS (frame->pts), GST_TIME_ARGS (frame->dts),
3981       frame->distance_from_sync);
3982   /* FIXME: suboptimal way to add a unique frame to the list, in case of subframe mode. */
3983   if (!g_queue_find (&priv->frames, frame)) {
3984     g_queue_push_tail (&priv->frames, gst_video_codec_frame_ref (frame));
3985   } else {
3986     GST_LOG_OBJECT (decoder,
3987         "Do not add an existing frame used to decode subframes");
3988   }
3989
3990   if (priv->frames.length > 10) {
3991     GST_DEBUG_OBJECT (decoder, "decoder frame list getting long: %d frames,"
3992         "possible internal leaking?", priv->frames.length);
3993   }
3994
3995   frame->deadline =
3996       gst_segment_to_running_time (&decoder->input_segment, GST_FORMAT_TIME,
3997       frame->pts);
3998
3999   /* do something with frame */
4000   ret = decoder_class->handle_frame (decoder, frame);
4001   if (ret != GST_FLOW_OK)
4002     GST_DEBUG_OBJECT (decoder, "flow error %s", gst_flow_get_name (ret));
4003
4004   /* the frame has either been added to parse_gather or sent to
4005      handle frame so there is no need to unref it */
4006   return ret;
4007 }
4008
4009
4010 /**
4011  * gst_video_decoder_get_output_state:
4012  * @decoder: a #GstVideoDecoder
4013  *
4014  * Get the #GstVideoCodecState currently describing the output stream.
4015  *
4016  * Returns: (transfer full): #GstVideoCodecState describing format of video data.
4017  */
4018 GstVideoCodecState *
4019 gst_video_decoder_get_output_state (GstVideoDecoder * decoder)
4020 {
4021   GstVideoCodecState *state = NULL;
4022
4023   GST_OBJECT_LOCK (decoder);
4024   if (decoder->priv->output_state)
4025     state = gst_video_codec_state_ref (decoder->priv->output_state);
4026   GST_OBJECT_UNLOCK (decoder);
4027
4028   return state;
4029 }
4030
4031 static GstVideoCodecState *
4032 _set_interlaced_output_state (GstVideoDecoder * decoder,
4033     GstVideoFormat fmt, GstVideoInterlaceMode interlace_mode, guint width,
4034     guint height, GstVideoCodecState * reference, gboolean copy_interlace_mode)
4035 {
4036   GstVideoDecoderPrivate *priv = decoder->priv;
4037   GstVideoCodecState *state;
4038
4039   g_assert ((copy_interlace_mode
4040           && interlace_mode == GST_VIDEO_INTERLACE_MODE_PROGRESSIVE)
4041       || !copy_interlace_mode);
4042
4043   GST_DEBUG_OBJECT (decoder,
4044       "fmt:%d, width:%d, height:%d, interlace-mode: %s, reference:%p", fmt,
4045       width, height, gst_video_interlace_mode_to_string (interlace_mode),
4046       reference);
4047
4048   /* Create the new output state */
4049   state =
4050       _new_output_state (fmt, interlace_mode, width, height, reference,
4051       copy_interlace_mode);
4052   if (!state)
4053     return NULL;
4054
4055   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4056
4057   GST_OBJECT_LOCK (decoder);
4058   /* Replace existing output state by new one */
4059   if (priv->output_state)
4060     gst_video_codec_state_unref (priv->output_state);
4061   priv->output_state = gst_video_codec_state_ref (state);
4062
4063   if (priv->output_state != NULL && priv->output_state->info.fps_n > 0) {
4064     priv->qos_frame_duration =
4065         gst_util_uint64_scale (GST_SECOND, priv->output_state->info.fps_d,
4066         priv->output_state->info.fps_n);
4067   } else {
4068     priv->qos_frame_duration = 0;
4069   }
4070   priv->output_state_changed = TRUE;
4071   GST_OBJECT_UNLOCK (decoder);
4072
4073   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4074
4075   return state;
4076 }
4077
4078 /**
4079  * gst_video_decoder_set_output_state:
4080  * @decoder: a #GstVideoDecoder
4081  * @fmt: a #GstVideoFormat
4082  * @width: The width in pixels
4083  * @height: The height in pixels
4084  * @reference: (allow-none) (transfer none): An optional reference #GstVideoCodecState
4085  *
4086  * Creates a new #GstVideoCodecState with the specified @fmt, @width and @height
4087  * as the output state for the decoder.
4088  * Any previously set output state on @decoder will be replaced by the newly
4089  * created one.
4090  *
4091  * If the subclass wishes to copy over existing fields (like pixel aspec ratio,
4092  * or framerate) from an existing #GstVideoCodecState, it can be provided as a
4093  * @reference.
4094  *
4095  * If the subclass wishes to override some fields from the output state (like
4096  * pixel-aspect-ratio or framerate) it can do so on the returned #GstVideoCodecState.
4097  *
4098  * The new output state will only take effect (set on pads and buffers) starting
4099  * from the next call to #gst_video_decoder_finish_frame().
4100  *
4101  * Returns: (transfer full): the newly configured output state.
4102  */
4103 GstVideoCodecState *
4104 gst_video_decoder_set_output_state (GstVideoDecoder * decoder,
4105     GstVideoFormat fmt, guint width, guint height,
4106     GstVideoCodecState * reference)
4107 {
4108   return _set_interlaced_output_state (decoder, fmt,
4109       GST_VIDEO_INTERLACE_MODE_PROGRESSIVE, width, height, reference, TRUE);
4110 }
4111
4112 /**
4113  * gst_video_decoder_set_interlaced_output_state:
4114  * @decoder: a #GstVideoDecoder
4115  * @fmt: a #GstVideoFormat
4116  * @width: The width in pixels
4117  * @height: The height in pixels
4118  * @interlace_mode: A #GstVideoInterlaceMode
4119  * @reference: (allow-none) (transfer none): An optional reference #GstVideoCodecState
4120  *
4121  * Same as #gst_video_decoder_set_output_state() but also allows you to also set
4122  * the interlacing mode.
4123  *
4124  * Returns: (transfer full): the newly configured output state.
4125  *
4126  * Since: 1.16.
4127  */
4128 GstVideoCodecState *
4129 gst_video_decoder_set_interlaced_output_state (GstVideoDecoder * decoder,
4130     GstVideoFormat fmt, GstVideoInterlaceMode interlace_mode, guint width,
4131     guint height, GstVideoCodecState * reference)
4132 {
4133   return _set_interlaced_output_state (decoder, fmt, interlace_mode, width,
4134       height, reference, FALSE);
4135 }
4136
4137
4138 /**
4139  * gst_video_decoder_get_oldest_frame:
4140  * @decoder: a #GstVideoDecoder
4141  *
4142  * Get the oldest pending unfinished #GstVideoCodecFrame
4143  *
4144  * Returns: (transfer full): oldest pending unfinished #GstVideoCodecFrame.
4145  */
4146 GstVideoCodecFrame *
4147 gst_video_decoder_get_oldest_frame (GstVideoDecoder * decoder)
4148 {
4149   GstVideoCodecFrame *frame = NULL;
4150
4151   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4152   if (decoder->priv->frames.head)
4153     frame = gst_video_codec_frame_ref (decoder->priv->frames.head->data);
4154   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4155
4156   return (GstVideoCodecFrame *) frame;
4157 }
4158
4159 /**
4160  * gst_video_decoder_get_frame:
4161  * @decoder: a #GstVideoDecoder
4162  * @frame_number: system_frame_number of a frame
4163  *
4164  * Get a pending unfinished #GstVideoCodecFrame
4165  *
4166  * Returns: (transfer full): pending unfinished #GstVideoCodecFrame identified by @frame_number.
4167  */
4168 GstVideoCodecFrame *
4169 gst_video_decoder_get_frame (GstVideoDecoder * decoder, int frame_number)
4170 {
4171   GList *g;
4172   GstVideoCodecFrame *frame = NULL;
4173
4174   GST_DEBUG_OBJECT (decoder, "frame_number : %d", frame_number);
4175
4176   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4177   for (g = decoder->priv->frames.head; g; g = g->next) {
4178     GstVideoCodecFrame *tmp = g->data;
4179
4180     if (tmp->system_frame_number == frame_number) {
4181       frame = gst_video_codec_frame_ref (tmp);
4182       break;
4183     }
4184   }
4185   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4186
4187   return frame;
4188 }
4189
4190 /**
4191  * gst_video_decoder_get_frames:
4192  * @decoder: a #GstVideoDecoder
4193  *
4194  * Get all pending unfinished #GstVideoCodecFrame
4195  *
4196  * Returns: (transfer full) (element-type GstVideoCodecFrame): pending unfinished #GstVideoCodecFrame.
4197  */
4198 GList *
4199 gst_video_decoder_get_frames (GstVideoDecoder * decoder)
4200 {
4201   GList *frames;
4202
4203   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4204   frames =
4205       g_list_copy_deep (decoder->priv->frames.head,
4206       (GCopyFunc) gst_video_codec_frame_ref, NULL);
4207   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4208
4209   return frames;
4210 }
4211
4212 static gboolean
4213 gst_video_decoder_decide_allocation_default (GstVideoDecoder * decoder,
4214     GstQuery * query)
4215 {
4216   GstCaps *outcaps = NULL;
4217   GstBufferPool *pool = NULL;
4218   guint size, min, max;
4219   GstAllocator *allocator = NULL;
4220   GstAllocationParams params;
4221   GstStructure *config;
4222   gboolean update_pool, update_allocator;
4223   GstVideoInfo vinfo;
4224
4225   gst_query_parse_allocation (query, &outcaps, NULL);
4226   gst_video_info_init (&vinfo);
4227   if (outcaps)
4228     gst_video_info_from_caps (&vinfo, outcaps);
4229
4230   /* we got configuration from our peer or the decide_allocation method,
4231    * parse them */
4232   if (gst_query_get_n_allocation_params (query) > 0) {
4233     /* try the allocator */
4234     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
4235     update_allocator = TRUE;
4236   } else {
4237     allocator = NULL;
4238     gst_allocation_params_init (&params);
4239     update_allocator = FALSE;
4240   }
4241
4242   if (gst_query_get_n_allocation_pools (query) > 0) {
4243     gst_query_parse_nth_allocation_pool (query, 0, &pool, &size, &min, &max);
4244     size = MAX (size, vinfo.size);
4245     update_pool = TRUE;
4246   } else {
4247     pool = NULL;
4248     size = vinfo.size;
4249     min = max = 0;
4250
4251     update_pool = FALSE;
4252   }
4253
4254   if (pool == NULL) {
4255     /* no pool, we can make our own */
4256     GST_DEBUG_OBJECT (decoder, "no pool, making new pool");
4257     pool = gst_video_buffer_pool_new ();
4258   }
4259
4260   /* now configure */
4261   config = gst_buffer_pool_get_config (pool);
4262   gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
4263   gst_buffer_pool_config_set_allocator (config, allocator, &params);
4264
4265   GST_DEBUG_OBJECT (decoder,
4266       "setting config %" GST_PTR_FORMAT " in pool %" GST_PTR_FORMAT, config,
4267       pool);
4268   if (!gst_buffer_pool_set_config (pool, config)) {
4269     config = gst_buffer_pool_get_config (pool);
4270
4271     /* If change are not acceptable, fallback to generic pool */
4272     if (!gst_buffer_pool_config_validate_params (config, outcaps, size, min,
4273             max)) {
4274       GST_DEBUG_OBJECT (decoder, "unsupported pool, making new pool");
4275
4276       gst_object_unref (pool);
4277       pool = gst_video_buffer_pool_new ();
4278       gst_buffer_pool_config_set_params (config, outcaps, size, min, max);
4279       gst_buffer_pool_config_set_allocator (config, allocator, &params);
4280     }
4281
4282     if (!gst_buffer_pool_set_config (pool, config))
4283       goto config_failed;
4284   }
4285
4286   if (update_allocator)
4287     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
4288   else
4289     gst_query_add_allocation_param (query, allocator, &params);
4290   if (allocator)
4291     gst_object_unref (allocator);
4292
4293   if (update_pool)
4294     gst_query_set_nth_allocation_pool (query, 0, pool, size, min, max);
4295   else
4296     gst_query_add_allocation_pool (query, pool, size, min, max);
4297
4298   if (pool)
4299     gst_object_unref (pool);
4300
4301   return TRUE;
4302
4303 config_failed:
4304   if (allocator)
4305     gst_object_unref (allocator);
4306   if (pool)
4307     gst_object_unref (pool);
4308   GST_ELEMENT_ERROR (decoder, RESOURCE, SETTINGS,
4309       ("Failed to configure the buffer pool"),
4310       ("Configuration is most likely invalid, please report this issue."));
4311   return FALSE;
4312 }
4313
4314 static gboolean
4315 gst_video_decoder_propose_allocation_default (GstVideoDecoder * decoder,
4316     GstQuery * query)
4317 {
4318   return TRUE;
4319 }
4320
4321 static gboolean
4322 gst_video_decoder_negotiate_pool (GstVideoDecoder * decoder, GstCaps * caps)
4323 {
4324   GstVideoDecoderClass *klass;
4325   GstQuery *query = NULL;
4326   GstBufferPool *pool = NULL;
4327   GstAllocator *allocator;
4328   GstAllocationParams params;
4329   gboolean ret = TRUE;
4330
4331   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
4332
4333   query = gst_query_new_allocation (caps, TRUE);
4334
4335   GST_DEBUG_OBJECT (decoder, "do query ALLOCATION");
4336
4337   if (!gst_pad_peer_query (decoder->srcpad, query)) {
4338     GST_DEBUG_OBJECT (decoder, "didn't get downstream ALLOCATION hints");
4339   }
4340
4341   g_assert (klass->decide_allocation != NULL);
4342   ret = klass->decide_allocation (decoder, query);
4343
4344   GST_DEBUG_OBJECT (decoder, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, ret,
4345       query);
4346
4347   if (!ret)
4348     goto no_decide_allocation;
4349
4350   /* we got configuration from our peer or the decide_allocation method,
4351    * parse them */
4352   if (gst_query_get_n_allocation_params (query) > 0) {
4353     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
4354   } else {
4355     allocator = NULL;
4356     gst_allocation_params_init (&params);
4357   }
4358
4359   if (gst_query_get_n_allocation_pools (query) > 0)
4360     gst_query_parse_nth_allocation_pool (query, 0, &pool, NULL, NULL, NULL);
4361   if (!pool) {
4362     if (allocator)
4363       gst_object_unref (allocator);
4364     ret = FALSE;
4365     goto no_decide_allocation;
4366   }
4367
4368   if (decoder->priv->allocator)
4369     gst_object_unref (decoder->priv->allocator);
4370   decoder->priv->allocator = allocator;
4371   decoder->priv->params = params;
4372
4373   if (decoder->priv->pool) {
4374     /* do not set the bufferpool to inactive here, it will be done
4375      * on its finalize function. As videodecoder do late renegotiation
4376      * it might happen that some element downstream is already using this
4377      * same bufferpool and deactivating it will make it fail.
4378      * Happens when a downstream element changes from passthrough to
4379      * non-passthrough and gets this same bufferpool to use */
4380     GST_DEBUG_OBJECT (decoder, "unref pool %" GST_PTR_FORMAT,
4381         decoder->priv->pool);
4382     gst_object_unref (decoder->priv->pool);
4383   }
4384   decoder->priv->pool = pool;
4385
4386   /* and activate */
4387   GST_DEBUG_OBJECT (decoder, "activate pool %" GST_PTR_FORMAT, pool);
4388   gst_buffer_pool_set_active (pool, TRUE);
4389
4390 done:
4391   if (query)
4392     gst_query_unref (query);
4393
4394   return ret;
4395
4396   /* Errors */
4397 no_decide_allocation:
4398   {
4399     GST_WARNING_OBJECT (decoder, "Subclass failed to decide allocation");
4400     goto done;
4401   }
4402 }
4403
4404 static gboolean
4405 gst_video_decoder_negotiate_default (GstVideoDecoder * decoder)
4406 {
4407   GstVideoCodecState *state = decoder->priv->output_state;
4408   gboolean ret = TRUE;
4409   GstVideoCodecFrame *frame;
4410   GstCaps *prevcaps;
4411   GstCaps *incaps;
4412
4413   if (!state) {
4414     GST_DEBUG_OBJECT (decoder,
4415         "Trying to negotiate the pool with out setting the o/p format");
4416     ret = gst_video_decoder_negotiate_pool (decoder, NULL);
4417     goto done;
4418   }
4419
4420   g_return_val_if_fail (GST_VIDEO_INFO_WIDTH (&state->info) != 0, FALSE);
4421   g_return_val_if_fail (GST_VIDEO_INFO_HEIGHT (&state->info) != 0, FALSE);
4422
4423   /* If the base class didn't set any multiview params, assume mono
4424    * now */
4425   if (GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) ==
4426       GST_VIDEO_MULTIVIEW_MODE_NONE) {
4427     GST_VIDEO_INFO_MULTIVIEW_MODE (&state->info) =
4428         GST_VIDEO_MULTIVIEW_MODE_MONO;
4429     GST_VIDEO_INFO_MULTIVIEW_FLAGS (&state->info) =
4430         GST_VIDEO_MULTIVIEW_FLAGS_NONE;
4431   }
4432
4433   GST_DEBUG_OBJECT (decoder, "output_state par %d/%d fps %d/%d",
4434       state->info.par_n, state->info.par_d,
4435       state->info.fps_n, state->info.fps_d);
4436
4437   if (state->caps == NULL)
4438     state->caps = gst_video_info_to_caps (&state->info);
4439
4440   incaps = gst_pad_get_current_caps (GST_VIDEO_DECODER_SINK_PAD (decoder));
4441   if (incaps) {
4442     GstStructure *in_struct;
4443
4444     in_struct = gst_caps_get_structure (incaps, 0);
4445     if (gst_structure_has_field (in_struct, "mastering-display-info") ||
4446         gst_structure_has_field (in_struct, "content-light-level")) {
4447       const gchar *s;
4448
4449       /* prefer upstream information */
4450       state->caps = gst_caps_make_writable (state->caps);
4451       if ((s = gst_structure_get_string (in_struct, "mastering-display-info"))) {
4452         gst_caps_set_simple (state->caps,
4453             "mastering-display-info", G_TYPE_STRING, s, NULL);
4454       }
4455
4456       if ((s = gst_structure_get_string (in_struct, "content-light-level"))) {
4457         gst_caps_set_simple (state->caps,
4458             "content-light-level", G_TYPE_STRING, s, NULL);
4459       }
4460     }
4461     if (gst_structure_has_field (in_struct, "hdr-format")) {
4462       const gchar *s;
4463       state->caps = gst_caps_make_writable (state->caps);
4464
4465       if ((s = gst_structure_get_string (in_struct, "hdr-format"))) {
4466         gst_caps_set_simple (state->caps, "hdr-format", G_TYPE_STRING, s, NULL);
4467       }
4468     }
4469
4470     gst_caps_unref (incaps);
4471   }
4472
4473   if (state->allocation_caps == NULL)
4474     state->allocation_caps = gst_caps_ref (state->caps);
4475
4476   GST_DEBUG_OBJECT (decoder, "setting caps %" GST_PTR_FORMAT, state->caps);
4477
4478   /* Push all pending pre-caps events of the oldest frame before
4479    * setting caps */
4480   frame = decoder->priv->frames.head ? decoder->priv->frames.head->data : NULL;
4481   if (frame || decoder->priv->current_frame_events) {
4482     GList **events, *l;
4483
4484     if (frame) {
4485       events = &frame->events;
4486     } else {
4487       events = &decoder->priv->current_frame_events;
4488     }
4489
4490     for (l = g_list_last (*events); l;) {
4491       GstEvent *event = GST_EVENT (l->data);
4492       GList *tmp;
4493
4494       if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
4495         gst_video_decoder_push_event (decoder, event);
4496         tmp = l;
4497         l = l->prev;
4498         *events = g_list_delete_link (*events, tmp);
4499       } else {
4500         l = l->prev;
4501       }
4502     }
4503   }
4504
4505   prevcaps = gst_pad_get_current_caps (decoder->srcpad);
4506   if (!prevcaps || !gst_caps_is_equal (prevcaps, state->caps)) {
4507     if (!prevcaps) {
4508       GST_DEBUG_OBJECT (decoder, "decoder src pad has currently NULL caps");
4509     }
4510     ret = gst_pad_set_caps (decoder->srcpad, state->caps);
4511   } else {
4512     ret = TRUE;
4513     GST_DEBUG_OBJECT (decoder,
4514         "current src pad and output state caps are the same");
4515   }
4516   if (prevcaps)
4517     gst_caps_unref (prevcaps);
4518
4519   if (!ret)
4520     goto done;
4521   decoder->priv->output_state_changed = FALSE;
4522   /* Negotiate pool */
4523   ret = gst_video_decoder_negotiate_pool (decoder, state->allocation_caps);
4524
4525 done:
4526   return ret;
4527 }
4528
4529 static gboolean
4530 gst_video_decoder_negotiate_unlocked (GstVideoDecoder * decoder)
4531 {
4532   GstVideoDecoderClass *klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
4533   gboolean ret = TRUE;
4534
4535   if (G_LIKELY (klass->negotiate))
4536     ret = klass->negotiate (decoder);
4537
4538   return ret;
4539 }
4540
4541 /**
4542  * gst_video_decoder_negotiate:
4543  * @decoder: a #GstVideoDecoder
4544  *
4545  * Negotiate with downstream elements to currently configured #GstVideoCodecState.
4546  * Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if
4547  * negotiate fails.
4548  *
4549  * Returns: %TRUE if the negotiation succeeded, else %FALSE.
4550  */
4551 gboolean
4552 gst_video_decoder_negotiate (GstVideoDecoder * decoder)
4553 {
4554   GstVideoDecoderClass *klass;
4555   gboolean ret = TRUE;
4556
4557   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), FALSE);
4558
4559   klass = GST_VIDEO_DECODER_GET_CLASS (decoder);
4560
4561   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4562   gst_pad_check_reconfigure (decoder->srcpad);
4563   if (klass->negotiate) {
4564     ret = klass->negotiate (decoder);
4565     if (!ret)
4566       gst_pad_mark_reconfigure (decoder->srcpad);
4567   }
4568   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4569
4570   return ret;
4571 }
4572
4573 /**
4574  * gst_video_decoder_allocate_output_buffer:
4575  * @decoder: a #GstVideoDecoder
4576  *
4577  * Helper function that allocates a buffer to hold a video frame for @decoder's
4578  * current #GstVideoCodecState.
4579  *
4580  * You should use gst_video_decoder_allocate_output_frame() instead of this
4581  * function, if possible at all.
4582  *
4583  * Returns: (transfer full): allocated buffer, or NULL if no buffer could be
4584  *     allocated (e.g. when downstream is flushing or shutting down)
4585  */
4586 GstBuffer *
4587 gst_video_decoder_allocate_output_buffer (GstVideoDecoder * decoder)
4588 {
4589   GstFlowReturn flow;
4590   GstBuffer *buffer = NULL;
4591   gboolean needs_reconfigure = FALSE;
4592
4593   GST_DEBUG ("alloc src buffer");
4594
4595   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4596   needs_reconfigure = gst_pad_check_reconfigure (decoder->srcpad);
4597   if (G_UNLIKELY (!decoder->priv->output_state
4598           || decoder->priv->output_state_changed || needs_reconfigure)) {
4599     if (!gst_video_decoder_negotiate_unlocked (decoder)) {
4600       if (decoder->priv->output_state) {
4601         GST_DEBUG_OBJECT (decoder, "Failed to negotiate, fallback allocation");
4602         gst_pad_mark_reconfigure (decoder->srcpad);
4603         goto fallback;
4604       } else {
4605         GST_DEBUG_OBJECT (decoder, "Failed to negotiate, output_buffer=NULL");
4606         goto failed_allocation;
4607       }
4608     }
4609   }
4610
4611   flow = gst_buffer_pool_acquire_buffer (decoder->priv->pool, &buffer, NULL);
4612
4613   if (flow != GST_FLOW_OK) {
4614     GST_INFO_OBJECT (decoder, "couldn't allocate output buffer, flow %s",
4615         gst_flow_get_name (flow));
4616     if (decoder->priv->output_state && decoder->priv->output_state->info.size)
4617       goto fallback;
4618     else
4619       goto failed_allocation;
4620   }
4621   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4622
4623   return buffer;
4624
4625 fallback:
4626   GST_INFO_OBJECT (decoder,
4627       "Fallback allocation, creating new buffer which doesn't belongs to any buffer pool");
4628   buffer =
4629       gst_buffer_new_allocate (NULL, decoder->priv->output_state->info.size,
4630       NULL);
4631
4632 failed_allocation:
4633   GST_ERROR_OBJECT (decoder, "Failed to allocate the buffer..");
4634   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4635
4636   return buffer;
4637 }
4638
4639 /**
4640  * gst_video_decoder_allocate_output_frame:
4641  * @decoder: a #GstVideoDecoder
4642  * @frame: a #GstVideoCodecFrame
4643  *
4644  * Helper function that allocates a buffer to hold a video frame for @decoder's
4645  * current #GstVideoCodecState.  Subclass should already have configured video
4646  * state and set src pad caps.
4647  *
4648  * The buffer allocated here is owned by the frame and you should only
4649  * keep references to the frame, not the buffer.
4650  *
4651  * Returns: %GST_FLOW_OK if an output buffer could be allocated
4652  */
4653 GstFlowReturn
4654 gst_video_decoder_allocate_output_frame (GstVideoDecoder *
4655     decoder, GstVideoCodecFrame * frame)
4656 {
4657   return gst_video_decoder_allocate_output_frame_with_params (decoder, frame,
4658       NULL);
4659 }
4660
4661 /**
4662  * gst_video_decoder_allocate_output_frame_with_params:
4663  * @decoder: a #GstVideoDecoder
4664  * @frame: a #GstVideoCodecFrame
4665  * @params: a #GstBufferPoolAcquireParams
4666  *
4667  * Same as #gst_video_decoder_allocate_output_frame except it allows passing
4668  * #GstBufferPoolAcquireParams to the sub call gst_buffer_pool_acquire_buffer.
4669  *
4670  * Returns: %GST_FLOW_OK if an output buffer could be allocated
4671  *
4672  * Since: 1.12
4673  */
4674 GstFlowReturn
4675 gst_video_decoder_allocate_output_frame_with_params (GstVideoDecoder *
4676     decoder, GstVideoCodecFrame * frame, GstBufferPoolAcquireParams * params)
4677 {
4678   GstFlowReturn flow_ret;
4679   GstVideoCodecState *state;
4680   int num_bytes;
4681   gboolean needs_reconfigure = FALSE;
4682
4683   g_return_val_if_fail (decoder->priv->output_state, GST_FLOW_NOT_NEGOTIATED);
4684   g_return_val_if_fail (frame->output_buffer == NULL, GST_FLOW_ERROR);
4685
4686   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4687
4688   state = decoder->priv->output_state;
4689   if (state == NULL) {
4690     g_warning ("Output state should be set before allocating frame");
4691     goto error;
4692   }
4693   num_bytes = GST_VIDEO_INFO_SIZE (&state->info);
4694   if (num_bytes == 0) {
4695     g_warning ("Frame size should not be 0");
4696     goto error;
4697   }
4698
4699   needs_reconfigure = gst_pad_check_reconfigure (decoder->srcpad);
4700   if (G_UNLIKELY (decoder->priv->output_state_changed || needs_reconfigure)) {
4701     if (!gst_video_decoder_negotiate_unlocked (decoder)) {
4702       gst_pad_mark_reconfigure (decoder->srcpad);
4703       if (GST_PAD_IS_FLUSHING (decoder->srcpad)) {
4704         GST_DEBUG_OBJECT (decoder,
4705             "Failed to negotiate a pool: pad is flushing");
4706         goto flushing;
4707       } else if (!decoder->priv->pool || decoder->priv->output_state_changed) {
4708         GST_DEBUG_OBJECT (decoder,
4709             "Failed to negotiate a pool and no previous pool to reuse");
4710         goto error;
4711       } else {
4712         GST_DEBUG_OBJECT (decoder,
4713             "Failed to negotiate a pool, falling back to the previous pool");
4714       }
4715     }
4716   }
4717
4718   GST_LOG_OBJECT (decoder, "alloc buffer size %d", num_bytes);
4719
4720   flow_ret = gst_buffer_pool_acquire_buffer (decoder->priv->pool,
4721       &frame->output_buffer, params);
4722
4723   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4724
4725   return flow_ret;
4726
4727 flushing:
4728   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4729   return GST_FLOW_FLUSHING;
4730
4731 error:
4732   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4733   return GST_FLOW_ERROR;
4734 }
4735
4736 /**
4737  * gst_video_decoder_get_max_decode_time:
4738  * @decoder: a #GstVideoDecoder
4739  * @frame: a #GstVideoCodecFrame
4740  *
4741  * Determines maximum possible decoding time for @frame that will
4742  * allow it to decode and arrive in time (as determined by QoS events).
4743  * In particular, a negative result means decoding in time is no longer possible
4744  * and should therefore occur as soon/skippy as possible.
4745  *
4746  * Returns: max decoding time.
4747  */
4748 GstClockTimeDiff
4749 gst_video_decoder_get_max_decode_time (GstVideoDecoder *
4750     decoder, GstVideoCodecFrame * frame)
4751 {
4752   GstClockTimeDiff deadline;
4753   GstClockTime earliest_time;
4754
4755   GST_OBJECT_LOCK (decoder);
4756   earliest_time = decoder->priv->earliest_time;
4757   if (GST_CLOCK_TIME_IS_VALID (earliest_time)
4758       && GST_CLOCK_TIME_IS_VALID (frame->deadline))
4759     deadline = GST_CLOCK_DIFF (earliest_time, frame->deadline);
4760   else
4761     deadline = G_MAXINT64;
4762
4763   GST_LOG_OBJECT (decoder, "earliest %" GST_TIME_FORMAT
4764       ", frame deadline %" GST_TIME_FORMAT ", deadline %" GST_STIME_FORMAT,
4765       GST_TIME_ARGS (earliest_time), GST_TIME_ARGS (frame->deadline),
4766       GST_STIME_ARGS (deadline));
4767
4768   GST_OBJECT_UNLOCK (decoder);
4769
4770   return deadline;
4771 }
4772
4773 /**
4774  * gst_video_decoder_get_qos_proportion:
4775  * @decoder: a #GstVideoDecoder
4776  *     current QoS proportion, or %NULL
4777  *
4778  * Returns: The current QoS proportion.
4779  *
4780  * Since: 1.0.3
4781  */
4782 gdouble
4783 gst_video_decoder_get_qos_proportion (GstVideoDecoder * decoder)
4784 {
4785   gdouble proportion;
4786
4787   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), 1.0);
4788
4789   GST_OBJECT_LOCK (decoder);
4790   proportion = decoder->priv->proportion;
4791   GST_OBJECT_UNLOCK (decoder);
4792
4793   return proportion;
4794 }
4795
4796 GstFlowReturn
4797 _gst_video_decoder_error (GstVideoDecoder * dec, gint weight,
4798     GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file,
4799     const gchar * function, gint line)
4800 {
4801   if (txt)
4802     GST_WARNING_OBJECT (dec, "error: %s", txt);
4803   if (dbg)
4804     GST_WARNING_OBJECT (dec, "error: %s", dbg);
4805   dec->priv->error_count += weight;
4806   dec->priv->discont = TRUE;
4807   if (dec->priv->max_errors >= 0 &&
4808       dec->priv->error_count > dec->priv->max_errors) {
4809     gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR,
4810         domain, code, txt, dbg, file, function, line);
4811     return GST_FLOW_ERROR;
4812   } else {
4813     g_free (txt);
4814     g_free (dbg);
4815     return GST_FLOW_OK;
4816   }
4817 }
4818
4819 /**
4820  * gst_video_decoder_set_max_errors:
4821  * @dec: a #GstVideoDecoder
4822  * @num: max tolerated errors
4823  *
4824  * Sets numbers of tolerated decoder errors, where a tolerated one is then only
4825  * warned about, but more than tolerated will lead to fatal error.  You can set
4826  * -1 for never returning fatal errors. Default is set to
4827  * GST_VIDEO_DECODER_MAX_ERRORS.
4828  *
4829  * The '-1' option was added in 1.4
4830  */
4831 void
4832 gst_video_decoder_set_max_errors (GstVideoDecoder * dec, gint num)
4833 {
4834   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
4835
4836   dec->priv->max_errors = num;
4837 }
4838
4839 /**
4840  * gst_video_decoder_get_max_errors:
4841  * @dec: a #GstVideoDecoder
4842  *
4843  * Returns: currently configured decoder tolerated error count.
4844  */
4845 gint
4846 gst_video_decoder_get_max_errors (GstVideoDecoder * dec)
4847 {
4848   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
4849
4850   return dec->priv->max_errors;
4851 }
4852
4853 /**
4854  * gst_video_decoder_set_needs_format:
4855  * @dec: a #GstVideoDecoder
4856  * @enabled: new state
4857  *
4858  * Configures decoder format needs.  If enabled, subclass needs to be
4859  * negotiated with format caps before it can process any data.  It will then
4860  * never be handed any data before it has been configured.
4861  * Otherwise, it might be handed data without having been configured and
4862  * is then expected being able to do so either by default
4863  * or based on the input data.
4864  *
4865  * Since: 1.4
4866  */
4867 void
4868 gst_video_decoder_set_needs_format (GstVideoDecoder * dec, gboolean enabled)
4869 {
4870   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
4871
4872   dec->priv->needs_format = enabled;
4873 }
4874
4875 /**
4876  * gst_video_decoder_get_needs_format:
4877  * @dec: a #GstVideoDecoder
4878  *
4879  * Queries decoder required format handling.
4880  *
4881  * Returns: %TRUE if required format handling is enabled.
4882  *
4883  * Since: 1.4
4884  */
4885 gboolean
4886 gst_video_decoder_get_needs_format (GstVideoDecoder * dec)
4887 {
4888   gboolean result;
4889
4890   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), FALSE);
4891
4892   result = dec->priv->needs_format;
4893
4894   return result;
4895 }
4896
4897 /**
4898  * gst_video_decoder_set_packetized:
4899  * @decoder: a #GstVideoDecoder
4900  * @packetized: whether the input data should be considered as packetized.
4901  *
4902  * Allows baseclass to consider input data as packetized or not. If the
4903  * input is packetized, then the @parse method will not be called.
4904  */
4905 void
4906 gst_video_decoder_set_packetized (GstVideoDecoder * decoder,
4907     gboolean packetized)
4908 {
4909   decoder->priv->packetized = packetized;
4910 }
4911
4912 /**
4913  * gst_video_decoder_get_packetized:
4914  * @decoder: a #GstVideoDecoder
4915  *
4916  * Queries whether input data is considered packetized or not by the
4917  * base class.
4918  *
4919  * Returns: TRUE if input data is considered packetized.
4920  */
4921 gboolean
4922 gst_video_decoder_get_packetized (GstVideoDecoder * decoder)
4923 {
4924   return decoder->priv->packetized;
4925 }
4926
4927 /**
4928  * gst_video_decoder_have_last_subframe:
4929  * @decoder: a #GstVideoDecoder
4930  * @frame: (transfer none): the #GstVideoCodecFrame to update
4931  *
4932  * Indicates that the last subframe has been processed by the decoder
4933  * in @frame. This will release the current frame in video decoder
4934  * allowing to receive new frames from upstream elements. This method
4935  * must be called in the subclass @handle_frame callback.
4936  *
4937  * Returns: a #GstFlowReturn, usually GST_FLOW_OK.
4938  *
4939  * Since: 1.20
4940  */
4941 GstFlowReturn
4942 gst_video_decoder_have_last_subframe (GstVideoDecoder * decoder,
4943     GstVideoCodecFrame * frame)
4944 {
4945   g_return_val_if_fail (gst_video_decoder_get_subframe_mode (decoder),
4946       GST_FLOW_OK);
4947   /* unref once from the list */
4948   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
4949   if (decoder->priv->current_frame == frame) {
4950     gst_video_codec_frame_unref (decoder->priv->current_frame);
4951     decoder->priv->current_frame = NULL;
4952   }
4953   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
4954
4955   return GST_FLOW_OK;
4956 }
4957
4958 /**
4959  * gst_video_decoder_set_subframe_mode:
4960  * @decoder: a #GstVideoDecoder
4961  * @subframe_mode: whether the input data should be considered as subframes.
4962  *
4963  * If this is set to TRUE, it informs the base class that the subclass
4964  * can receive the data at a granularity lower than one frame.
4965  *
4966  * Note that in this mode, the subclass has two options. It can either
4967  * require the presence of a GST_VIDEO_BUFFER_FLAG_MARKER to mark the
4968  * end of a frame. Or it can operate in such a way that it will decode
4969  * a single frame at a time. In this second case, every buffer that
4970  * arrives to the element is considered part of the same frame until
4971  * gst_video_decoder_finish_frame() is called.
4972  *
4973  * In either case, the same #GstVideoCodecFrame will be passed to the
4974  * GstVideoDecoderClass:handle_frame vmethod repeatedly with a
4975  * different GstVideoCodecFrame:input_buffer every time until the end of the
4976  * frame has been signaled using either method.
4977  * This method must be called during the decoder subclass @set_format call.
4978  *
4979  * Since: 1.20
4980  */
4981 void
4982 gst_video_decoder_set_subframe_mode (GstVideoDecoder * decoder,
4983     gboolean subframe_mode)
4984 {
4985   decoder->priv->subframe_mode = subframe_mode;
4986 }
4987
4988 /**
4989  * gst_video_decoder_get_subframe_mode:
4990  * @decoder: a #GstVideoDecoder
4991  *
4992  * Queries whether input data is considered as subframes or not by the
4993  * base class. If FALSE, each input buffer will be considered as a full
4994  * frame.
4995  *
4996  * Returns: TRUE if input data is considered as sub frames.
4997  *
4998  * Since: 1.20
4999  */
5000 gboolean
5001 gst_video_decoder_get_subframe_mode (GstVideoDecoder * decoder)
5002 {
5003   return decoder->priv->subframe_mode;
5004 }
5005
5006 /**
5007  * gst_video_decoder_get_input_subframe_index:
5008  * @decoder: a #GstVideoDecoder
5009  * @frame: (transfer none): the #GstVideoCodecFrame to update
5010  *
5011  * Queries the number of the last subframe received by
5012  * the decoder baseclass in the @frame.
5013  *
5014  * Returns: the current subframe index received in subframe mode, 1 otherwise.
5015  *
5016  * Since: 1.20
5017  */
5018 guint
5019 gst_video_decoder_get_input_subframe_index (GstVideoDecoder * decoder,
5020     GstVideoCodecFrame * frame)
5021 {
5022   return frame->abidata.ABI.num_subframes;
5023 }
5024
5025 /**
5026  * gst_video_decoder_get_processed_subframe_index:
5027  * @decoder: a #GstVideoDecoder
5028  * @frame: (transfer none): the #GstVideoCodecFrame to update
5029  *
5030  * Queries the number of subframes in the frame processed by
5031  * the decoder baseclass.
5032  *
5033  * Returns: the current subframe processed received in subframe mode.
5034  *
5035  * Since: 1.20
5036  */
5037 guint
5038 gst_video_decoder_get_processed_subframe_index (GstVideoDecoder * decoder,
5039     GstVideoCodecFrame * frame)
5040 {
5041   return frame->abidata.ABI.subframes_processed;
5042 }
5043
5044 /**
5045  * gst_video_decoder_set_estimate_rate:
5046  * @dec: a #GstVideoDecoder
5047  * @enabled: whether to enable byte to time conversion
5048  *
5049  * Allows baseclass to perform byte to time estimated conversion.
5050  */
5051 void
5052 gst_video_decoder_set_estimate_rate (GstVideoDecoder * dec, gboolean enabled)
5053 {
5054   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
5055
5056   dec->priv->do_estimate_rate = enabled;
5057 }
5058
5059 /**
5060  * gst_video_decoder_get_estimate_rate:
5061  * @dec: a #GstVideoDecoder
5062  *
5063  * Returns: currently configured byte to time conversion setting
5064  */
5065 gboolean
5066 gst_video_decoder_get_estimate_rate (GstVideoDecoder * dec)
5067 {
5068   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), 0);
5069
5070   return dec->priv->do_estimate_rate;
5071 }
5072
5073 /**
5074  * gst_video_decoder_set_latency:
5075  * @decoder: a #GstVideoDecoder
5076  * @min_latency: minimum latency
5077  * @max_latency: maximum latency
5078  *
5079  * Lets #GstVideoDecoder sub-classes tell the baseclass what the decoder
5080  * latency is. Will also post a LATENCY message on the bus so the pipeline
5081  * can reconfigure its global latency.
5082  */
5083 void
5084 gst_video_decoder_set_latency (GstVideoDecoder * decoder,
5085     GstClockTime min_latency, GstClockTime max_latency)
5086 {
5087   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min_latency));
5088   g_return_if_fail (max_latency >= min_latency);
5089
5090   GST_OBJECT_LOCK (decoder);
5091   decoder->priv->min_latency = min_latency;
5092   decoder->priv->max_latency = max_latency;
5093   GST_OBJECT_UNLOCK (decoder);
5094
5095   gst_element_post_message (GST_ELEMENT_CAST (decoder),
5096       gst_message_new_latency (GST_OBJECT_CAST (decoder)));
5097 }
5098
5099 /**
5100  * gst_video_decoder_get_latency:
5101  * @decoder: a #GstVideoDecoder
5102  * @min_latency: (out) (allow-none): address of variable in which to store the
5103  *     configured minimum latency, or %NULL
5104  * @max_latency: (out) (allow-none): address of variable in which to store the
5105  *     configured mximum latency, or %NULL
5106  *
5107  * Query the configured decoder latency. Results will be returned via
5108  * @min_latency and @max_latency.
5109  */
5110 void
5111 gst_video_decoder_get_latency (GstVideoDecoder * decoder,
5112     GstClockTime * min_latency, GstClockTime * max_latency)
5113 {
5114   GST_OBJECT_LOCK (decoder);
5115   if (min_latency)
5116     *min_latency = decoder->priv->min_latency;
5117   if (max_latency)
5118     *max_latency = decoder->priv->max_latency;
5119   GST_OBJECT_UNLOCK (decoder);
5120 }
5121
5122 /**
5123  * gst_video_decoder_merge_tags:
5124  * @decoder: a #GstVideoDecoder
5125  * @tags: (allow-none): a #GstTagList to merge, or NULL to unset
5126  *     previously-set tags
5127  * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
5128  *
5129  * Sets the audio decoder tags and how they should be merged with any
5130  * upstream stream tags. This will override any tags previously-set
5131  * with gst_audio_decoder_merge_tags().
5132  *
5133  * Note that this is provided for convenience, and the subclass is
5134  * not required to use this and can still do tag handling on its own.
5135  *
5136  * MT safe.
5137  */
5138 void
5139 gst_video_decoder_merge_tags (GstVideoDecoder * decoder,
5140     const GstTagList * tags, GstTagMergeMode mode)
5141 {
5142   g_return_if_fail (GST_IS_VIDEO_DECODER (decoder));
5143   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
5144   g_return_if_fail (tags == NULL || mode != GST_TAG_MERGE_UNDEFINED);
5145
5146   GST_VIDEO_DECODER_STREAM_LOCK (decoder);
5147   if (decoder->priv->tags != tags) {
5148     if (decoder->priv->tags) {
5149       gst_tag_list_unref (decoder->priv->tags);
5150       decoder->priv->tags = NULL;
5151       decoder->priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
5152     }
5153     if (tags) {
5154       decoder->priv->tags = gst_tag_list_ref ((GstTagList *) tags);
5155       decoder->priv->tags_merge_mode = mode;
5156     }
5157
5158     GST_DEBUG_OBJECT (decoder, "set decoder tags to %" GST_PTR_FORMAT, tags);
5159     decoder->priv->tags_changed = TRUE;
5160   }
5161   GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
5162 }
5163
5164 /**
5165  * gst_video_decoder_get_buffer_pool:
5166  * @decoder: a #GstVideoDecoder
5167  *
5168  * Returns: (transfer full): the instance of the #GstBufferPool used
5169  * by the decoder; free it after use it
5170  */
5171 GstBufferPool *
5172 gst_video_decoder_get_buffer_pool (GstVideoDecoder * decoder)
5173 {
5174   g_return_val_if_fail (GST_IS_VIDEO_DECODER (decoder), NULL);
5175
5176   if (decoder->priv->pool)
5177     return gst_object_ref (decoder->priv->pool);
5178
5179   return NULL;
5180 }
5181
5182 /**
5183  * gst_video_decoder_get_allocator:
5184  * @decoder: a #GstVideoDecoder
5185  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
5186  * used
5187  * @params: (out) (allow-none) (transfer full): the
5188  * #GstAllocationParams of @allocator
5189  *
5190  * Lets #GstVideoDecoder sub-classes to know the memory @allocator
5191  * used by the base class and its @params.
5192  *
5193  * Unref the @allocator after use it.
5194  */
5195 void
5196 gst_video_decoder_get_allocator (GstVideoDecoder * decoder,
5197     GstAllocator ** allocator, GstAllocationParams * params)
5198 {
5199   g_return_if_fail (GST_IS_VIDEO_DECODER (decoder));
5200
5201   if (allocator)
5202     *allocator = decoder->priv->allocator ?
5203         gst_object_ref (decoder->priv->allocator) : NULL;
5204
5205   if (params)
5206     *params = decoder->priv->params;
5207 }
5208
5209 /**
5210  * gst_video_decoder_set_use_default_pad_acceptcaps:
5211  * @decoder: a #GstVideoDecoder
5212  * @use: if the default pad accept-caps query handling should be used
5213  *
5214  * Lets #GstVideoDecoder sub-classes decide if they want the sink pad
5215  * to use the default pad query handler to reply to accept-caps queries.
5216  *
5217  * By setting this to true it is possible to further customize the default
5218  * handler with %GST_PAD_SET_ACCEPT_INTERSECT and
5219  * %GST_PAD_SET_ACCEPT_TEMPLATE
5220  *
5221  * Since: 1.6
5222  */
5223 void
5224 gst_video_decoder_set_use_default_pad_acceptcaps (GstVideoDecoder * decoder,
5225     gboolean use)
5226 {
5227   decoder->priv->use_default_pad_acceptcaps = use;
5228 }
5229
5230 static void
5231 gst_video_decoder_request_sync_point_internal (GstVideoDecoder * dec,
5232     GstClockTime deadline, GstVideoDecoderRequestSyncPointFlags flags)
5233 {
5234   GstEvent *fku = NULL;
5235   GstVideoDecoderPrivate *priv;
5236
5237   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
5238
5239   priv = dec->priv;
5240
5241   GST_OBJECT_LOCK (dec);
5242
5243   /* Check if we're allowed to send a new force-keyunit event.
5244    * frame->deadline is set to the running time of the PTS. */
5245   if (priv->min_force_key_unit_interval == 0 ||
5246       deadline == GST_CLOCK_TIME_NONE ||
5247       (priv->min_force_key_unit_interval != GST_CLOCK_TIME_NONE &&
5248           (priv->last_force_key_unit_time == GST_CLOCK_TIME_NONE
5249               || (priv->last_force_key_unit_time +
5250                   priv->min_force_key_unit_interval <= deadline)))) {
5251     GST_DEBUG_OBJECT (dec,
5252         "Requesting a new key-unit for frame with deadline %" GST_TIME_FORMAT,
5253         GST_TIME_ARGS (deadline));
5254     fku =
5255         gst_video_event_new_upstream_force_key_unit (GST_CLOCK_TIME_NONE, FALSE,
5256         0);
5257     priv->last_force_key_unit_time = deadline;
5258   } else {
5259     GST_DEBUG_OBJECT (dec,
5260         "Can't request a new key-unit for frame with deadline %"
5261         GST_TIME_FORMAT, GST_TIME_ARGS (deadline));
5262   }
5263   priv->request_sync_point_flags |= flags;
5264   /* We don't know yet the frame number of the sync point so set it to a
5265    * frame number higher than any allowed frame number */
5266   priv->request_sync_point_frame_number = REQUEST_SYNC_POINT_PENDING;
5267   GST_OBJECT_UNLOCK (dec);
5268
5269   if (fku)
5270     gst_pad_push_event (dec->sinkpad, fku);
5271 }
5272
5273 /**
5274  * gst_video_decoder_request_sync_point:
5275  * @dec: a #GstVideoDecoder
5276  * @frame: a #GstVideoCodecFrame
5277  * @flags: #GstVideoDecoderRequestSyncPointFlags
5278  *
5279  * Allows the #GstVideoDecoder subclass to request from the base class that
5280  * a new sync should be requested from upstream, and that @frame was the frame
5281  * when the subclass noticed that a new sync point is required. A reason for
5282  * the subclass to do this could be missing reference frames, for example.
5283  *
5284  * The base class will then request a new sync point from upstream as long as
5285  * the time that passed since the last one is exceeding
5286  * #GstVideoDecoder:min-force-key-unit-interval.
5287  *
5288  * The subclass can signal via @flags how the frames until the next sync point
5289  * should be handled:
5290  *
5291  *   * If %GST_VIDEO_DECODER_REQUEST_SYNC_POINT_DISCARD_INPUT is selected then
5292  *     all following input frames until the next sync point are discarded.
5293  *     This can be useful if the lack of a sync point will prevent all further
5294  *     decoding and the decoder implementation is not very robust in handling
5295  *     missing references frames.
5296  *   * If %GST_VIDEO_DECODER_REQUEST_SYNC_POINT_CORRUPT_OUTPUT is selected
5297  *     then all output frames following @frame are marked as corrupted via
5298  *     %GST_BUFFER_FLAG_CORRUPTED. Corrupted frames can be automatically
5299  *     dropped by the base class, see #GstVideoDecoder:discard-corrupted-frames.
5300  *     Subclasses can manually mark frames as corrupted via %GST_VIDEO_CODEC_FRAME_FLAG_CORRUPTED
5301  *     before calling gst_video_decoder_finish_frame().
5302  *
5303  * Since: 1.20
5304  */
5305 void
5306 gst_video_decoder_request_sync_point (GstVideoDecoder * dec,
5307     GstVideoCodecFrame * frame, GstVideoDecoderRequestSyncPointFlags flags)
5308 {
5309   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
5310   g_return_if_fail (frame != NULL);
5311
5312   gst_video_decoder_request_sync_point_internal (dec, frame->deadline, flags);
5313 }
5314
5315 /**
5316  * gst_video_decoder_set_needs_sync_point:
5317  * @dec: a #GstVideoDecoder
5318  * @enabled: new state
5319  *
5320  * Configures whether the decoder requires a sync point before it starts
5321  * outputting data in the beginning. If enabled, the base class will discard
5322  * all non-sync point frames in the beginning and after a flush and does not
5323  * pass it to the subclass.
5324  *
5325  * If the first frame is not a sync point, the base class will request a sync
5326  * point via the force-key-unit event.
5327  *
5328  * Since: 1.20
5329  */
5330 void
5331 gst_video_decoder_set_needs_sync_point (GstVideoDecoder * dec, gboolean enabled)
5332 {
5333   g_return_if_fail (GST_IS_VIDEO_DECODER (dec));
5334
5335   dec->priv->needs_sync_point = enabled;
5336 }
5337
5338 /**
5339  * gst_video_decoder_get_needs_sync_point:
5340  * @dec: a #GstVideoDecoder
5341  *
5342  * Queries if the decoder requires a sync point before it starts outputting
5343  * data in the beginning.
5344  *
5345  * Returns: %TRUE if a sync point is required in the beginning.
5346  *
5347  * Since: 1.20
5348  */
5349 gboolean
5350 gst_video_decoder_get_needs_sync_point (GstVideoDecoder * dec)
5351 {
5352   gboolean result;
5353
5354   g_return_val_if_fail (GST_IS_VIDEO_DECODER (dec), FALSE);
5355
5356   result = dec->priv->needs_sync_point;
5357
5358   return result;
5359 }