baseparse: reset next_pts upon SEGMENT event
[platform/upstream/gstreamer.git] / libs / gst / base / gstbaseparse.c
1 /* GStreamer
2  * Copyright (C) 2008 Nokia Corporation. All rights reserved.
3  *   Contact: Stefan Kost <stefan.kost@nokia.com>
4  * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
5  * Copyright (C) 2011, Hewlett-Packard Development Company, L.P.
6  *   Author: Sebastian Dröge <sebastian.droege@collabora.co.uk>, Collabora Ltd.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:gstbaseparse
26  * @short_description: Base class for stream parsers
27  * @see_also: #GstBaseTransform
28  *
29  * This base class is for parser elements that process data and splits it
30  * into separate audio/video/whatever frames.
31  *
32  * It provides for:
33  * <itemizedlist>
34  *   <listitem><para>provides one sink pad and one source pad</para></listitem>
35  *   <listitem><para>handles state changes</para></listitem>
36  *   <listitem><para>can operate in pull mode or push mode</para></listitem>
37  *   <listitem><para>handles seeking in both modes</para></listitem>
38  *   <listitem><para>handles events (SEGMENT/EOS/FLUSH)</para></listitem>
39  *   <listitem><para>
40  *        handles queries (POSITION/DURATION/SEEKING/FORMAT/CONVERT)
41  *   </para></listitem>
42  *   <listitem><para>handles flushing</para></listitem>
43  * </itemizedlist>
44  *
45  * The purpose of this base class is to provide the basic functionality of
46  * a parser and share a lot of rather complex code.
47  *
48  * Description of the parsing mechanism:
49  * <orderedlist>
50  * <listitem>
51  *   <itemizedlist><title>Set-up phase</title>
52  *   <listitem><para>
53  *     GstBaseParse calls @start to inform subclass that data processing is
54  *     about to start now.
55  *   </para></listitem>
56  *   <listitem><para>
57  *     GstBaseParse class calls @set_sink_caps to inform the subclass about
58  *     incoming sinkpad caps. Subclass could already set the srcpad caps
59  *     accordingly, but this might be delayed until calling
60  *     gst_base_parse_finish_frame() with a non-queued frame.
61  *   </para></listitem>
62  *   <listitem><para>
63  *      At least at this point subclass needs to tell the GstBaseParse class
64  *      how big data chunks it wants to receive (min_frame_size). It can do
65  *      this with gst_base_parse_set_min_frame_size().
66  *   </para></listitem>
67  *   <listitem><para>
68  *      GstBaseParse class sets up appropriate data passing mode (pull/push)
69  *      and starts to process the data.
70  *   </para></listitem>
71  *   </itemizedlist>
72  * </listitem>
73  * <listitem>
74  *   <itemizedlist>
75  *   <title>Parsing phase</title>
76  *     <listitem><para>
77  *       GstBaseParse gathers at least min_frame_size bytes of data either
78  *       by pulling it from upstream or collecting buffers in an internal
79  *       #GstAdapter.
80  *     </para></listitem>
81  *     <listitem><para>
82  *       A buffer of (at least) min_frame_size bytes is passed to subclass with
83  *       @handle_frame. Subclass checks the contents and can optionally
84  *       return GST_FLOW_OK along with an amount of data to be skipped to find
85  *       a valid frame (which will result in a subsequent DISCONT).
86  *       If, otherwise, the buffer does not hold a complete frame,
87  *       @handle_frame can merely return and will be called again when additional
88  *       data is available.  In push mode this amounts to an
89  *       additional input buffer (thus minimal additional latency), in pull mode
90  *       this amounts to some arbitrary reasonable buffer size increase.
91  *       Of course, gst_base_parse_set_min_frame_size() could also be used if a
92  *       very specific known amount of additional data is required.
93  *       If, however, the buffer holds a complete valid frame, it can pass
94  *       the size of this frame to gst_base_parse_finish_frame().
95  *       If acting as a converter, it can also merely indicate consumed input data
96  *       while simultaneously providing custom output data.
97  *       Note that baseclass performs some processing (such as tracking
98  *       overall consumed data rate versus duration) for each finished frame,
99  *       but other state is only updated upon each call to @handle_frame
100  *       (such as tracking upstream input timestamp).
101  *       </para><para>
102  *       Subclass is also responsible for setting the buffer metadata
103  *       (e.g. buffer timestamp and duration, or keyframe if applicable).
104  *       (although the latter can also be done by GstBaseParse if it is
105  *       appropriately configured, see below).  Frame is provided with
106  *       timestamp derived from upstream (as much as generally possible),
107  *       duration obtained from configuration (see below), and offset
108  *       if meaningful (in pull mode).
109  *       </para><para>
110  *       Note that @check_valid_frame might receive any small
111  *       amount of input data when leftover data is being drained (e.g. at EOS).
112  *     </para></listitem>
113  *     <listitem><para>
114  *       As part of finish frame processing,
115  *       just prior to actually pushing the buffer in question,
116  *       it is passed to @pre_push_frame which gives subclass yet one
117  *       last chance to examine buffer metadata, or to send some custom (tag)
118  *       events, or to perform custom (segment) filtering.
119  *     </para></listitem>
120  *     <listitem><para>
121  *       During the parsing process GstBaseParseClass will handle both srcpad
122  *       and sinkpad events. They will be passed to subclass if @event or
123  *       @src_event callbacks have been provided.
124  *     </para></listitem>
125  *   </itemizedlist>
126  * </listitem>
127  * <listitem>
128  *   <itemizedlist><title>Shutdown phase</title>
129  *   <listitem><para>
130  *     GstBaseParse class calls @stop to inform the subclass that data
131  *     parsing will be stopped.
132  *   </para></listitem>
133  *   </itemizedlist>
134  * </listitem>
135  * </orderedlist>
136  *
137  * Subclass is responsible for providing pad template caps for
138  * source and sink pads. The pads need to be named "sink" and "src". It also
139  * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
140  * when base class calls subclass' @set_sink_caps function).
141  *
142  * This base class uses #GST_FORMAT_DEFAULT as a meaning of frames. So,
143  * subclass conversion routine needs to know that conversion from
144  * #GST_FORMAT_TIME to #GST_FORMAT_DEFAULT must return the
145  * frame number that can be found from the given byte position.
146  *
147  * GstBaseParse uses subclasses conversion methods also for seeking (or
148  * otherwise uses its own default one, see also below).
149  *
150  * Subclass @start and @stop functions will be called to inform the beginning
151  * and end of data processing.
152  *
153  * Things that subclass need to take care of:
154  * <itemizedlist>
155  *   <listitem><para>Provide pad templates</para></listitem>
156  *   <listitem><para>
157  *      Fixate the source pad caps when appropriate
158  *   </para></listitem>
159  *   <listitem><para>
160  *      Inform base class how big data chunks should be retrieved. This is
161  *      done with gst_base_parse_set_min_frame_size() function.
162  *   </para></listitem>
163  *   <listitem><para>
164  *      Examine data chunks passed to subclass with @handle_frame and pass
165  *      proper frame(s) to gst_base_parse_finish_frame(), and setting src pad
166  *      caps and timestamps on frame.
167  *   </para></listitem>
168  *   <listitem><para>Provide conversion functions</para></listitem>
169  *   <listitem><para>
170  *      Update the duration information with gst_base_parse_set_duration()
171  *   </para></listitem>
172  *   <listitem><para>
173  *      Optionally passthrough using gst_base_parse_set_passthrough()
174  *   </para></listitem>
175  *   <listitem><para>
176  *      Configure various baseparse parameters using
177  *      gst_base_parse_set_average_bitrate(), gst_base_parse_set_syncable()
178  *      and gst_base_parse_set_frame_rate().
179  *   </para></listitem>
180  *   <listitem><para>
181  *      In particular, if subclass is unable to determine a duration, but
182  *      parsing (or specs) yields a frames per seconds rate, then this can be
183  *      provided to GstBaseParse to enable it to cater for
184  *      buffer time metadata (which will be taken from upstream as much as
185  *      possible). Internally keeping track of frame durations and respective
186  *      sizes that have been pushed provides GstBaseParse with an estimated
187  *      bitrate. A default @convert (used if not overriden) will then use these
188  *      rates to perform obvious conversions.  These rates are also used to
189  *      update (estimated) duration at regular frame intervals.
190  *   </para></listitem>
191  * </itemizedlist>
192  *
193  */
194
195 /* TODO:
196  *  - In push mode provide a queue of adapter-"queued" buffers for upstream
197  *    buffer metadata
198  *  - Queue buffers/events until caps are set
199  */
200
201 #ifdef HAVE_CONFIG_H
202 #  include "config.h"
203 #endif
204
205 #include <stdlib.h>
206 #include <string.h>
207
208 #include <gst/base/gstadapter.h>
209
210 #include "gstbaseparse.h"
211
212 /* FIXME: get rid of old GstIndex code */
213 #include "gstindex.h"
214 #include "gstindex.c"
215 #include "gstmemindex.c"
216
217 #define GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC  (1 << 0)
218
219 #define MIN_FRAMES_TO_POST_BITRATE 10
220 #define TARGET_DIFFERENCE          (20 * GST_SECOND)
221 #define MAX_INDEX_ENTRIES          4096
222
223 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
224 #define GST_CAT_DEFAULT gst_base_parse_debug
225
226 /* Supported formats */
227 static const GstFormat fmtlist[] = {
228   GST_FORMAT_DEFAULT,
229   GST_FORMAT_BYTES,
230   GST_FORMAT_TIME,
231   GST_FORMAT_UNDEFINED
232 };
233
234 #define GST_BASE_PARSE_GET_PRIVATE(obj)  \
235     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
236
237 struct _GstBaseParsePrivate
238 {
239   GstPadMode pad_mode;
240
241   GstAdapter *adapter;
242
243   gint64 duration;
244   GstFormat duration_fmt;
245   gint64 estimated_duration;
246   gint64 estimated_drift;
247
248   guint min_frame_size;
249   gboolean passthrough;
250   gboolean pts_interpolate;
251   gboolean infer_ts;
252   gboolean syncable;
253   gboolean has_timing_info;
254   guint fps_num, fps_den;
255   gint update_interval;
256   guint bitrate;
257   guint lead_in, lead_out;
258   GstClockTime lead_in_ts, lead_out_ts;
259   GstClockTime min_latency, max_latency;
260
261   gboolean discont;
262   gboolean flushing;
263   gboolean drain;
264
265   gint64 offset;
266   gint64 sync_offset;
267   GstClockTime next_pts;
268   GstClockTime next_dts;
269   GstClockTime prev_pts;
270   GstClockTime prev_dts;
271   GstClockTime frame_duration;
272   gboolean seen_keyframe;
273   gboolean is_video;
274   gint flushed;
275
276   guint64 framecount;
277   guint64 bytecount;
278   guint64 data_bytecount;
279   guint64 acc_duration;
280   GstClockTime first_frame_pts;
281   GstClockTime first_frame_dts;
282   gint64 first_frame_offset;
283
284   gboolean post_min_bitrate;
285   gboolean post_avg_bitrate;
286   gboolean post_max_bitrate;
287   guint min_bitrate;
288   guint avg_bitrate;
289   guint max_bitrate;
290   guint posted_avg_bitrate;
291
292   /* frames/buffers that are queued and ready to go on OK */
293   GQueue queued_frames;
294
295   GstBuffer *cache;
296
297   /* index entry storage, either ours or provided */
298   GstIndex *index;
299   gint index_id;
300   gboolean own_index;
301   GMutex index_lock;
302
303   /* seek table entries only maintained if upstream is BYTE seekable */
304   gboolean upstream_seekable;
305   gboolean upstream_has_duration;
306   gint64 upstream_size;
307   /* minimum distance between two index entries */
308   GstClockTimeDiff idx_interval;
309   guint64 idx_byte_interval;
310   /* ts and offset of last entry added */
311   GstClockTime index_last_ts;
312   gint64 index_last_offset;
313   gboolean index_last_valid;
314
315   /* timestamps currently produced are accurate, e.g. started from 0 onwards */
316   gboolean exact_position;
317   /* seek events are temporarily kept to match them with newsegments */
318   GSList *pending_seeks;
319
320   /* reverse playback */
321   GSList *buffers_pending;
322   GSList *buffers_head;
323   GSList *buffers_queued;
324   GSList *buffers_send;
325   GstClockTime last_pts;
326   GstClockTime last_dts;
327   gint64 last_offset;
328
329   /* Pending serialized events */
330   GList *pending_events;
331   /* Newsegment event to be sent after SEEK */
332   gboolean pending_segment;
333
334   /* offset of last parsed frame/data */
335   gint64 prev_offset;
336   /* force a new frame, regardless of offset */
337   gboolean new_frame;
338   /* whether we are merely scanning for a frame */
339   gboolean scanning;
340   /* ... and resulting frame, if any */
341   GstBaseParseFrame *scanned_frame;
342
343   /* TRUE if we're still detecting the format, i.e.
344    * if ::detect() is still called for future buffers */
345   gboolean detecting;
346   GList *detect_buffers;
347   guint detect_buffers_size;
348
349   /* if TRUE, a STREAM_START event needs to be pushed */
350   gboolean push_stream_start;
351 };
352
353 typedef struct _GstBaseParseSeek
354 {
355   GstSegment segment;
356   gboolean accurate;
357   gint64 offset;
358   GstClockTime start_ts;
359 } GstBaseParseSeek;
360
361 #define GST_BASE_PARSE_INDEX_LOCK(parse) \
362   g_mutex_lock (&parse->priv->index_lock);
363 #define GST_BASE_PARSE_INDEX_UNLOCK(parse) \
364   g_mutex_unlock (&parse->priv->index_lock);
365
366 static GstElementClass *parent_class = NULL;
367
368 static void gst_base_parse_class_init (GstBaseParseClass * klass);
369 static void gst_base_parse_init (GstBaseParse * parse,
370     GstBaseParseClass * klass);
371
372 GType
373 gst_base_parse_get_type (void)
374 {
375   static volatile gsize base_parse_type = 0;
376
377   if (g_once_init_enter (&base_parse_type)) {
378     static const GTypeInfo base_parse_info = {
379       sizeof (GstBaseParseClass),
380       (GBaseInitFunc) NULL,
381       (GBaseFinalizeFunc) NULL,
382       (GClassInitFunc) gst_base_parse_class_init,
383       NULL,
384       NULL,
385       sizeof (GstBaseParse),
386       0,
387       (GInstanceInitFunc) gst_base_parse_init,
388     };
389     GType _type;
390
391     _type = g_type_register_static (GST_TYPE_ELEMENT,
392         "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
393     g_once_init_leave (&base_parse_type, _type);
394   }
395   return (GType) base_parse_type;
396 }
397
398 static void gst_base_parse_finalize (GObject * object);
399
400 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
401     GstStateChange transition);
402 static void gst_base_parse_reset (GstBaseParse * parse);
403
404 #if 0
405 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
406 static GstIndex *gst_base_parse_get_index (GstElement * element);
407 #endif
408
409 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad,
410     GstObject * parent);
411 static gboolean gst_base_parse_sink_activate_mode (GstPad * pad,
412     GstObject * parent, GstPadMode mode, gboolean active);
413 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
414     GstEvent * event);
415 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
416
417 static gboolean gst_base_parse_src_event (GstPad * pad, GstObject * parent,
418     GstEvent * event);
419 static gboolean gst_base_parse_src_query (GstPad * pad, GstObject * parent,
420     GstQuery * query);
421
422 static gboolean gst_base_parse_sink_event (GstPad * pad, GstObject * parent,
423     GstEvent * event);
424 static gboolean gst_base_parse_sink_query (GstPad * pad, GstObject * parent,
425     GstQuery * query);
426
427 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstObject * parent,
428     GstBuffer * buffer);
429 static void gst_base_parse_loop (GstPad * pad);
430
431 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
432     GstBaseParseFrame * frame);
433
434 static gboolean gst_base_parse_sink_event_default (GstBaseParse * parse,
435     GstEvent * event);
436
437 static gboolean gst_base_parse_src_event_default (GstBaseParse * parse,
438     GstEvent * event);
439
440 static gboolean gst_base_parse_sink_query_default (GstBaseParse * parse,
441     GstQuery * query);
442 static gboolean gst_base_parse_src_query_default (GstBaseParse * parse,
443     GstQuery * query);
444
445 static void gst_base_parse_drain (GstBaseParse * parse);
446
447 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
448     gboolean post_min, gboolean post_avg, gboolean post_max);
449
450 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
451     GstClockTime time, gboolean before, GstClockTime * _ts);
452 static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
453     GstClockTime * _time, gint64 * _offset);
454
455 static GstFlowReturn gst_base_parse_start_fragment (GstBaseParse * parse);
456 static GstFlowReturn gst_base_parse_finish_fragment (GstBaseParse * parse,
457     gboolean prev_head);
458
459 static inline GstFlowReturn gst_base_parse_check_sync (GstBaseParse * parse);
460
461 static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);
462
463 static void
464 gst_base_parse_clear_queues (GstBaseParse * parse)
465 {
466   g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
467   g_slist_free (parse->priv->buffers_queued);
468   parse->priv->buffers_queued = NULL;
469   g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
470       NULL);
471   g_slist_free (parse->priv->buffers_pending);
472   parse->priv->buffers_pending = NULL;
473   g_slist_foreach (parse->priv->buffers_head, (GFunc) gst_buffer_unref, NULL);
474   g_slist_free (parse->priv->buffers_head);
475   parse->priv->buffers_head = NULL;
476   g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
477   g_slist_free (parse->priv->buffers_send);
478   parse->priv->buffers_send = NULL;
479
480   g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
481   g_list_free (parse->priv->detect_buffers);
482   parse->priv->detect_buffers = NULL;
483   parse->priv->detect_buffers_size = 0;
484
485   g_queue_foreach (&parse->priv->queued_frames,
486       (GFunc) gst_base_parse_frame_free, NULL);
487   g_queue_clear (&parse->priv->queued_frames);
488
489   gst_buffer_replace (&parse->priv->cache, NULL);
490
491   g_list_foreach (parse->priv->pending_events, (GFunc) gst_event_unref, NULL);
492   g_list_free (parse->priv->pending_events);
493   parse->priv->pending_events = NULL;
494   parse->priv->pending_segment = FALSE;
495 }
496
497 static void
498 gst_base_parse_finalize (GObject * object)
499 {
500   GstBaseParse *parse = GST_BASE_PARSE (object);
501
502   g_object_unref (parse->priv->adapter);
503
504   if (parse->priv->cache) {
505     gst_buffer_unref (parse->priv->cache);
506     parse->priv->cache = NULL;
507   }
508
509   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
510       NULL);
511   g_list_free (parse->priv->pending_events);
512   parse->priv->pending_events = NULL;
513   parse->priv->pending_segment = FALSE;
514
515   if (parse->priv->index) {
516     gst_object_unref (parse->priv->index);
517     parse->priv->index = NULL;
518   }
519   g_mutex_clear (&parse->priv->index_lock);
520
521   gst_base_parse_clear_queues (parse);
522
523   G_OBJECT_CLASS (parent_class)->finalize (object);
524 }
525
526 static void
527 gst_base_parse_class_init (GstBaseParseClass * klass)
528 {
529   GObjectClass *gobject_class;
530   GstElementClass *gstelement_class;
531
532   gobject_class = G_OBJECT_CLASS (klass);
533   g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
534   parent_class = g_type_class_peek_parent (klass);
535   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
536
537   gstelement_class = (GstElementClass *) klass;
538   gstelement_class->change_state =
539       GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
540
541 #if 0
542   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
543   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
544 #endif
545
546   /* Default handlers */
547   klass->sink_event = gst_base_parse_sink_event_default;
548   klass->src_event = gst_base_parse_src_event_default;
549   klass->sink_query = gst_base_parse_sink_query_default;
550   klass->src_query = gst_base_parse_src_query_default;
551   klass->convert = gst_base_parse_convert_default;
552
553   GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
554       "baseparse element");
555 }
556
557 static void
558 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
559 {
560   GstPadTemplate *pad_template;
561
562   GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
563
564   parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
565
566   pad_template =
567       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
568   g_return_if_fail (pad_template != NULL);
569   parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
570   gst_pad_set_event_function (parse->sinkpad,
571       GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
572   gst_pad_set_query_function (parse->sinkpad,
573       GST_DEBUG_FUNCPTR (gst_base_parse_sink_query));
574   gst_pad_set_chain_function (parse->sinkpad,
575       GST_DEBUG_FUNCPTR (gst_base_parse_chain));
576   gst_pad_set_activate_function (parse->sinkpad,
577       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
578   gst_pad_set_activatemode_function (parse->sinkpad,
579       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_mode));
580   GST_PAD_SET_PROXY_ALLOCATION (parse->sinkpad);
581   gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
582
583   GST_DEBUG_OBJECT (parse, "sinkpad created");
584
585   pad_template =
586       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
587   g_return_if_fail (pad_template != NULL);
588   parse->srcpad = gst_pad_new_from_template (pad_template, "src");
589   gst_pad_set_event_function (parse->srcpad,
590       GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
591   gst_pad_set_query_function (parse->srcpad,
592       GST_DEBUG_FUNCPTR (gst_base_parse_src_query));
593   gst_pad_use_fixed_caps (parse->srcpad);
594   gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
595   GST_DEBUG_OBJECT (parse, "src created");
596
597   g_queue_init (&parse->priv->queued_frames);
598
599   parse->priv->adapter = gst_adapter_new ();
600
601   parse->priv->pad_mode = GST_PAD_MODE_NONE;
602
603   g_mutex_init (&parse->priv->index_lock);
604
605   /* init state */
606   gst_base_parse_reset (parse);
607   GST_DEBUG_OBJECT (parse, "init ok");
608
609   GST_OBJECT_FLAG_SET (parse, GST_ELEMENT_FLAG_INDEXABLE);
610 }
611
612 static GstBaseParseFrame *
613 gst_base_parse_frame_copy (GstBaseParseFrame * frame)
614 {
615   GstBaseParseFrame *copy;
616
617   copy = g_slice_dup (GstBaseParseFrame, frame);
618   copy->buffer = gst_buffer_ref (frame->buffer);
619   copy->_private_flags &= ~GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
620
621   GST_TRACE ("copied frame %p -> %p", frame, copy);
622
623   return copy;
624 }
625
626 void
627 gst_base_parse_frame_free (GstBaseParseFrame * frame)
628 {
629   GST_TRACE ("freeing frame %p", frame);
630
631   if (frame->buffer) {
632     gst_buffer_unref (frame->buffer);
633     frame->buffer = NULL;
634   }
635
636   if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
637     g_slice_free (GstBaseParseFrame, frame);
638   } else {
639     memset (frame, 0, sizeof (*frame));
640   }
641 }
642
643 G_DEFINE_BOXED_TYPE (GstBaseParseFrame, gst_base_parse_frame,
644     (GBoxedCopyFunc) gst_base_parse_frame_copy,
645     (GBoxedFreeFunc) gst_base_parse_frame_free);
646
647 /**
648  * gst_base_parse_frame_init:
649  * @frame: #GstBaseParseFrame.
650  *
651  * Sets a #GstBaseParseFrame to initial state.  Currently this means
652  * all public fields are zero-ed and a private flag is set to make
653  * sure gst_base_parse_frame_free() only frees the contents but not
654  * the actual frame. Use this function to initialise a #GstBaseParseFrame
655  * allocated on the stack.
656  */
657 void
658 gst_base_parse_frame_init (GstBaseParseFrame * frame)
659 {
660   memset (frame, 0, sizeof (GstBaseParseFrame));
661   frame->_private_flags = GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC;
662   GST_TRACE ("inited frame %p", frame);
663 }
664
665 /**
666  * gst_base_parse_frame_new:
667  * @buffer: (transfer none): a #GstBuffer
668  * @flags: the flags
669  * @overhead: number of bytes in this frame which should be counted as
670  *     metadata overhead, ie. not used to calculate the average bitrate.
671  *     Set to -1 to mark the entire frame as metadata. If in doubt, set to 0.
672  *
673  * Allocates a new #GstBaseParseFrame. This function is mainly for bindings,
674  * elements written in C should usually allocate the frame on the stack and
675  * then use gst_base_parse_frame_init() to initialise it.
676  *
677  * Returns: a newly-allocated #GstBaseParseFrame. Free with
678  *     gst_base_parse_frame_free() when no longer needed.
679  */
680 GstBaseParseFrame *
681 gst_base_parse_frame_new (GstBuffer * buffer, GstBaseParseFrameFlags flags,
682     gint overhead)
683 {
684   GstBaseParseFrame *frame;
685
686   frame = g_slice_new0 (GstBaseParseFrame);
687   frame->buffer = gst_buffer_ref (buffer);
688
689   GST_TRACE ("created frame %p", frame);
690   return frame;
691 }
692
693 static inline void
694 gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
695     GstBuffer * buf)
696 {
697   gst_buffer_replace (&frame->buffer, buf);
698
699   parse->flags = 0;
700
701   /* set flags one by one for clarity */
702   if (G_UNLIKELY (parse->priv->drain))
703     parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;
704
705   /* losing sync is pretty much a discont (and vice versa), no ? */
706   if (G_UNLIKELY (parse->priv->discont))
707     parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
708 }
709
710 static void
711 gst_base_parse_reset (GstBaseParse * parse)
712 {
713   GST_OBJECT_LOCK (parse);
714   gst_segment_init (&parse->segment, GST_FORMAT_TIME);
715   parse->priv->duration = -1;
716   parse->priv->min_frame_size = 1;
717   parse->priv->discont = TRUE;
718   parse->priv->flushing = FALSE;
719   parse->priv->offset = 0;
720   parse->priv->sync_offset = 0;
721   parse->priv->update_interval = -1;
722   parse->priv->fps_num = parse->priv->fps_den = 0;
723   parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
724   parse->priv->lead_in = parse->priv->lead_out = 0;
725   parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
726   parse->priv->bitrate = 0;
727   parse->priv->framecount = 0;
728   parse->priv->bytecount = 0;
729   parse->priv->acc_duration = 0;
730   parse->priv->first_frame_pts = GST_CLOCK_TIME_NONE;
731   parse->priv->first_frame_dts = GST_CLOCK_TIME_NONE;
732   parse->priv->first_frame_offset = -1;
733   parse->priv->estimated_duration = -1;
734   parse->priv->estimated_drift = 0;
735   parse->priv->next_pts = GST_CLOCK_TIME_NONE;
736   parse->priv->next_dts = 0;
737   parse->priv->syncable = TRUE;
738   parse->priv->passthrough = FALSE;
739   parse->priv->pts_interpolate = TRUE;
740   parse->priv->infer_ts = TRUE;
741   parse->priv->has_timing_info = FALSE;
742   parse->priv->post_min_bitrate = TRUE;
743   parse->priv->post_avg_bitrate = TRUE;
744   parse->priv->post_max_bitrate = TRUE;
745   parse->priv->min_bitrate = G_MAXUINT;
746   parse->priv->max_bitrate = 0;
747   parse->priv->avg_bitrate = 0;
748   parse->priv->posted_avg_bitrate = 0;
749
750   parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
751   parse->priv->index_last_offset = -1;
752   parse->priv->index_last_valid = TRUE;
753   parse->priv->upstream_seekable = FALSE;
754   parse->priv->upstream_size = 0;
755   parse->priv->upstream_has_duration = FALSE;
756   parse->priv->idx_interval = 0;
757   parse->priv->idx_byte_interval = 0;
758   parse->priv->exact_position = TRUE;
759   parse->priv->seen_keyframe = FALSE;
760
761   parse->priv->last_dts = GST_CLOCK_TIME_NONE;
762   parse->priv->last_pts = GST_CLOCK_TIME_NONE;
763   parse->priv->last_offset = 0;
764
765   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
766       NULL);
767   g_list_free (parse->priv->pending_events);
768   parse->priv->pending_events = NULL;
769   parse->priv->pending_segment = FALSE;
770
771   if (parse->priv->cache) {
772     gst_buffer_unref (parse->priv->cache);
773     parse->priv->cache = NULL;
774   }
775
776   g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
777   g_slist_free (parse->priv->pending_seeks);
778   parse->priv->pending_seeks = NULL;
779
780   if (parse->priv->adapter)
781     gst_adapter_clear (parse->priv->adapter);
782
783   parse->priv->new_frame = TRUE;
784
785   g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref, NULL);
786   g_list_free (parse->priv->detect_buffers);
787   parse->priv->detect_buffers = NULL;
788   parse->priv->detect_buffers_size = 0;
789   GST_OBJECT_UNLOCK (parse);
790 }
791
792 /* gst_base_parse_parse_frame:
793  * @parse: #GstBaseParse.
794  * @buffer: #GstBuffer.
795  *
796  * Default callback for parse_frame.
797  */
798 static GstFlowReturn
799 gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
800 {
801   GstBuffer *buffer = frame->buffer;
802
803   if (!GST_BUFFER_PTS_IS_VALID (buffer) &&
804       GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts)) {
805     GST_BUFFER_PTS (buffer) = parse->priv->next_pts;
806   }
807   if (!GST_BUFFER_DTS_IS_VALID (buffer) &&
808       GST_CLOCK_TIME_IS_VALID (parse->priv->next_dts)) {
809     GST_BUFFER_DTS (buffer) = parse->priv->next_dts;
810   }
811   if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
812       GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
813     GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
814   }
815   return GST_FLOW_OK;
816 }
817
818 /* gst_base_parse_convert:
819  * @parse: #GstBaseParse.
820  * @src_format: #GstFormat describing the source format.
821  * @src_value: Source value to be converted.
822  * @dest_format: #GstFormat defining the converted format.
823  * @dest_value: Pointer where the conversion result will be put.
824  *
825  * Converts using configured "convert" vmethod in #GstBaseParse class.
826  *
827  * Returns: TRUE if conversion was successful.
828  */
829 static gboolean
830 gst_base_parse_convert (GstBaseParse * parse,
831     GstFormat src_format,
832     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
833 {
834   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
835   gboolean ret;
836
837   g_return_val_if_fail (dest_value != NULL, FALSE);
838
839   if (!klass->convert)
840     return FALSE;
841
842   ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
843
844 #ifndef GST_DISABLE_GST_DEBUG
845   {
846     if (ret) {
847       if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
848         GST_LOG_OBJECT (parse,
849             "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
850             GST_TIME_ARGS (src_value), *dest_value);
851       } else if (dest_format == GST_FORMAT_TIME &&
852           src_format == GST_FORMAT_BYTES) {
853         GST_LOG_OBJECT (parse,
854             "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
855             src_value, GST_TIME_ARGS (*dest_value));
856       } else {
857         GST_LOG_OBJECT (parse,
858             "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
859             GST_STR_NULL (gst_format_get_name (src_format)),
860             GST_STR_NULL (gst_format_get_name (dest_format)),
861             src_value, *dest_value);
862       }
863     } else {
864       GST_DEBUG_OBJECT (parse, "conversion failed");
865     }
866   }
867 #endif
868
869   return ret;
870 }
871
872 /* gst_base_parse_sink_event:
873  * @pad: #GstPad that received the event.
874  * @event: #GstEvent to be handled.
875  *
876  * Handler for sink pad events.
877  *
878  * Returns: TRUE if the event was handled.
879  */
880 static gboolean
881 gst_base_parse_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
882 {
883   GstBaseParse *parse = GST_BASE_PARSE (parent);
884   GstBaseParseClass *bclass = GST_BASE_PARSE_GET_CLASS (parse);
885   gboolean ret;
886
887   ret = bclass->sink_event (parse, event);
888
889   return ret;
890 }
891
892
893 /* gst_base_parse_sink_event_default:
894  * @parse: #GstBaseParse.
895  * @event: #GstEvent to be handled.
896  *
897  * Element-level event handler function.
898  *
899  * The event will be unreffed only if it has been handled and this
900  * function returns %TRUE
901  *
902  * Returns: %TRUE if the event was handled and not need forwarding.
903  */
904 static gboolean
905 gst_base_parse_sink_event_default (GstBaseParse * parse, GstEvent * event)
906 {
907   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
908   gboolean ret = FALSE;
909   gboolean forward_immediate = FALSE;
910
911   GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
912       GST_EVENT_TYPE_NAME (event));
913
914   switch (GST_EVENT_TYPE (event)) {
915     case GST_EVENT_CAPS:
916     {
917       GstCaps *caps;
918
919       gst_event_parse_caps (event, &caps);
920       GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
921
922       if (klass->set_sink_caps)
923         ret = klass->set_sink_caps (parse, caps);
924       else
925         ret = TRUE;
926
927       /* will send our own caps downstream */
928       gst_event_unref (event);
929       event = NULL;
930       break;
931     }
932     case GST_EVENT_SEGMENT:
933     {
934       const GstSegment *in_segment;
935       GstSegment out_segment;
936       gint64 offset = 0, next_dts;
937
938       gst_event_parse_segment (event, &in_segment);
939       gst_segment_init (&out_segment, GST_FORMAT_TIME);
940
941       GST_DEBUG_OBJECT (parse, "segment %" GST_SEGMENT_FORMAT, in_segment);
942
943       if (in_segment->format == GST_FORMAT_BYTES) {
944         GstBaseParseSeek *seek = NULL;
945         GSList *node;
946
947         /* stop time is allowed to be open-ended, but not start & pos */
948         offset = in_segment->time;
949
950         GST_OBJECT_LOCK (parse);
951         for (node = parse->priv->pending_seeks; node; node = node->next) {
952           GstBaseParseSeek *tmp = node->data;
953
954           if (tmp->offset == offset) {
955             seek = tmp;
956             break;
957           }
958         }
959         parse->priv->pending_seeks =
960             g_slist_remove (parse->priv->pending_seeks, seek);
961         GST_OBJECT_UNLOCK (parse);
962
963         if (seek) {
964           GST_DEBUG_OBJECT (parse,
965               "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
966               seek->accurate ? " accurate" : "", &seek->segment);
967
968           out_segment.start = seek->segment.start;
969           out_segment.stop = seek->segment.stop;
970           out_segment.time = seek->segment.start;
971
972           next_dts = seek->start_ts;
973           parse->priv->exact_position = seek->accurate;
974           g_free (seek);
975         } else {
976           /* best attempt convert */
977           /* as these are only estimates, stop is kept open-ended to avoid
978            * premature cutting */
979           gst_base_parse_convert (parse, GST_FORMAT_BYTES, in_segment->start,
980               GST_FORMAT_TIME, (gint64 *) & next_dts);
981
982           out_segment.start = next_dts;
983           out_segment.stop = GST_CLOCK_TIME_NONE;
984           out_segment.time = next_dts;
985
986           parse->priv->exact_position = (in_segment->start == 0);
987         }
988
989         gst_event_unref (event);
990
991         event = gst_event_new_segment (&out_segment);
992
993         GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. %"
994             GST_SEGMENT_FORMAT, in_segment);
995
996       } else if (in_segment->format != GST_FORMAT_TIME) {
997         /* Unknown incoming segment format. Output a default open-ended
998          * TIME segment */
999         gst_event_unref (event);
1000
1001         out_segment.start = 0;
1002         out_segment.stop = GST_CLOCK_TIME_NONE;
1003         out_segment.time = 0;
1004
1005         event = gst_event_new_segment (&out_segment);
1006
1007         next_dts = 0;
1008       } else {
1009         /* not considered BYTE seekable if it is talking to us in TIME,
1010          * whatever else it might claim */
1011         parse->priv->upstream_seekable = FALSE;
1012         next_dts = in_segment->start;
1013       }
1014
1015       memcpy (&parse->segment, &out_segment, sizeof (GstSegment));
1016
1017       /*
1018          gst_segment_set_newsegment (&parse->segment, update, rate,
1019          applied_rate, format, start, stop, start);
1020        */
1021
1022       /* save the segment for later, right before we push a new buffer so that
1023        * the caps are fixed and the next linked element can receive
1024        * the segment. */
1025       parse->priv->pending_segment = TRUE;
1026       ret = TRUE;
1027
1028       /* but finish the current segment */
1029       GST_DEBUG_OBJECT (parse, "draining current segment");
1030       if (in_segment->rate > 0.0)
1031         gst_base_parse_drain (parse);
1032       else
1033         gst_base_parse_finish_fragment (parse, FALSE);
1034       gst_adapter_clear (parse->priv->adapter);
1035
1036       parse->priv->offset = offset;
1037       parse->priv->sync_offset = offset;
1038       parse->priv->next_dts = next_dts;
1039       parse->priv->next_pts = GST_CLOCK_TIME_NONE;
1040       parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1041       parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1042       parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
1043       parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
1044       parse->priv->discont = TRUE;
1045       parse->priv->seen_keyframe = FALSE;
1046       break;
1047     }
1048
1049     case GST_EVENT_FLUSH_START:
1050       GST_OBJECT_LOCK (parse);
1051       parse->priv->flushing = TRUE;
1052       GST_OBJECT_UNLOCK (parse);
1053       break;
1054
1055     case GST_EVENT_FLUSH_STOP:
1056       gst_adapter_clear (parse->priv->adapter);
1057       gst_base_parse_clear_queues (parse);
1058       parse->priv->flushing = FALSE;
1059       parse->priv->discont = TRUE;
1060       parse->priv->last_pts = GST_CLOCK_TIME_NONE;
1061       parse->priv->last_dts = GST_CLOCK_TIME_NONE;
1062       parse->priv->new_frame = TRUE;
1063
1064       forward_immediate = TRUE;
1065       break;
1066
1067     case GST_EVENT_EOS:
1068       if (parse->segment.rate > 0.0)
1069         gst_base_parse_drain (parse);
1070       else
1071         gst_base_parse_finish_fragment (parse, TRUE);
1072
1073       /* If we STILL have zero frames processed, fire an error */
1074       if (parse->priv->framecount == 0) {
1075         GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
1076             ("No valid frames found before end of stream"), (NULL));
1077       }
1078       /* newsegment and other serialized events before eos */
1079       if (G_UNLIKELY (parse->priv->pending_events)) {
1080         GList *l;
1081
1082         for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1083           gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1084         }
1085         g_list_free (parse->priv->pending_events);
1086         parse->priv->pending_events = NULL;
1087         parse->priv->pending_segment = FALSE;
1088       }
1089       if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1090         /* We've not posted bitrate tags yet - do so now */
1091         gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
1092       }
1093       forward_immediate = TRUE;
1094       break;
1095     case GST_EVENT_CUSTOM_DOWNSTREAM:{
1096       /* FIXME: Code duplicated from libgstvideo because core can't depend on -base */
1097 #ifndef GST_VIDEO_EVENT_STILL_STATE_NAME
1098 #define GST_VIDEO_EVENT_STILL_STATE_NAME "GstEventStillFrame"
1099 #endif
1100
1101       const GstStructure *s;
1102       gboolean ev_still_state;
1103
1104       s = gst_event_get_structure (event);
1105       if (s != NULL &&
1106           gst_structure_has_name (s, GST_VIDEO_EVENT_STILL_STATE_NAME) &&
1107           gst_structure_get_boolean (s, "still-state", &ev_still_state)) {
1108         if (ev_still_state) {
1109           GST_DEBUG_OBJECT (parse, "draining current data for still-frame");
1110           if (parse->segment.rate > 0.0)
1111             gst_base_parse_drain (parse);
1112           else
1113             gst_base_parse_finish_fragment (parse, TRUE);
1114         }
1115         forward_immediate = TRUE;
1116       }
1117       break;
1118     }
1119     case GST_EVENT_GAP:
1120     {
1121       GST_DEBUG_OBJECT (parse, "draining current data due to gap event");
1122       if (parse->segment.rate > 0.0)
1123         gst_base_parse_drain (parse);
1124       else
1125         gst_base_parse_finish_fragment (parse, TRUE);
1126       forward_immediate = TRUE;
1127       break;
1128     }
1129     case GST_EVENT_TAG:
1130       /* See if any bitrate tags were posted */
1131       gst_base_parse_handle_tag (parse, event);
1132       break;
1133
1134     case GST_EVENT_STREAM_START:
1135       if (parse->priv->pad_mode != GST_PAD_MODE_PULL)
1136         forward_immediate = TRUE;
1137       break;
1138
1139     default:
1140       break;
1141   }
1142
1143   /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1144    * For EOS this is required because no buffer or serialized event
1145    * will come after EOS and nothing could trigger another
1146    * _finish_frame() call.   *
1147    * If the subclass handles sending of EOS manually it can return
1148    * _DROPPED from ::finish() and all other subclasses should have
1149    * decoded/flushed all remaining data before this
1150    *
1151    * For FLUSH_STOP this is required because it is expected
1152    * to be forwarded immediately and no buffers are queued anyway.
1153    */
1154   if (event) {
1155     if (!GST_EVENT_IS_SERIALIZED (event) || forward_immediate) {
1156       ret = gst_pad_push_event (parse->srcpad, event);
1157     } else {
1158       // GST_VIDEO_DECODER_STREAM_LOCK (decoder);
1159       parse->priv->pending_events =
1160           g_list_prepend (parse->priv->pending_events, event);
1161       // GST_VIDEO_DECODER_STREAM_UNLOCK (decoder);
1162       ret = TRUE;
1163     }
1164   }
1165
1166   GST_DEBUG_OBJECT (parse, "event handled");
1167
1168   return ret;
1169 }
1170
1171 static gboolean
1172 gst_base_parse_sink_query_default (GstBaseParse * parse, GstQuery * query)
1173 {
1174   GstPad *pad;
1175   gboolean res;
1176
1177   pad = GST_BASE_PARSE_SINK_PAD (parse);
1178
1179   switch (GST_QUERY_TYPE (query)) {
1180     case GST_QUERY_CAPS:
1181     {
1182       GstBaseParseClass *bclass;
1183
1184       bclass = GST_BASE_PARSE_GET_CLASS (parse);
1185
1186       if (bclass->get_sink_caps) {
1187         GstCaps *caps, *filter;
1188
1189         gst_query_parse_caps (query, &filter);
1190         caps = bclass->get_sink_caps (parse, filter);
1191         GST_LOG_OBJECT (parse, "sink getcaps returning caps %" GST_PTR_FORMAT,
1192             caps);
1193         gst_query_set_caps_result (query, caps);
1194         gst_caps_unref (caps);
1195
1196         res = TRUE;
1197       } else {
1198         GstCaps *caps, *template_caps, *filter;
1199
1200         gst_query_parse_caps (query, &filter);
1201         template_caps = gst_pad_get_pad_template_caps (pad);
1202         if (filter != NULL) {
1203           caps =
1204               gst_caps_intersect_full (filter, template_caps,
1205               GST_CAPS_INTERSECT_FIRST);
1206           gst_caps_unref (template_caps);
1207         } else {
1208           caps = template_caps;
1209         }
1210         gst_query_set_caps_result (query, caps);
1211         gst_caps_unref (caps);
1212
1213         res = TRUE;
1214       }
1215       break;
1216     }
1217     default:
1218     {
1219       res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
1220       break;
1221     }
1222   }
1223
1224   return res;
1225 }
1226
1227 static gboolean
1228 gst_base_parse_sink_query (GstPad * pad, GstObject * parent, GstQuery * query)
1229 {
1230   GstBaseParseClass *bclass;
1231   GstBaseParse *parse;
1232   gboolean ret;
1233
1234   parse = GST_BASE_PARSE (parent);
1235   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1236
1237   GST_DEBUG_OBJECT (parse, "%s query", GST_QUERY_TYPE_NAME (query));
1238
1239   if (bclass->sink_query)
1240     ret = bclass->sink_query (parse, query);
1241   else
1242     ret = FALSE;
1243
1244   GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1245       GST_QUERY_TYPE_NAME (query), ret, query);
1246
1247   return ret;
1248 }
1249
1250 static gboolean
1251 gst_base_parse_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1252 {
1253   GstBaseParseClass *bclass;
1254   GstBaseParse *parse;
1255   gboolean ret;
1256
1257   parse = GST_BASE_PARSE (parent);
1258   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1259
1260   GST_DEBUG_OBJECT (parse, "%s query: %" GST_PTR_FORMAT,
1261       GST_QUERY_TYPE_NAME (query), query);
1262
1263   if (bclass->src_query)
1264     ret = bclass->src_query (parse, query);
1265   else
1266     ret = FALSE;
1267
1268   GST_LOG_OBJECT (parse, "%s query result: %d %" GST_PTR_FORMAT,
1269       GST_QUERY_TYPE_NAME (query), ret, query);
1270
1271   return ret;
1272 }
1273
1274 /* gst_base_parse_src_event:
1275  * @pad: #GstPad that received the event.
1276  * @event: #GstEvent that was received.
1277  *
1278  * Handler for source pad events.
1279  *
1280  * Returns: TRUE if the event was handled.
1281  */
1282 static gboolean
1283 gst_base_parse_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1284 {
1285   GstBaseParse *parse;
1286   GstBaseParseClass *bclass;
1287   gboolean ret = TRUE;
1288
1289   parse = GST_BASE_PARSE (parent);
1290   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1291
1292   GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
1293       GST_EVENT_TYPE_NAME (event));
1294
1295   if (bclass->src_event)
1296     ret = bclass->src_event (parse, event);
1297   else
1298     gst_event_unref (event);
1299
1300   return ret;
1301 }
1302
1303 static gboolean
1304 gst_base_parse_is_seekable (GstBaseParse * parse)
1305 {
1306   /* FIXME: could do more here, e.g. check index or just send data from 0
1307    * in pull mode and let decoder/sink clip */
1308   return parse->priv->syncable;
1309 }
1310
1311 /* gst_base_parse_src_event_default:
1312  * @parse: #GstBaseParse.
1313  * @event: #GstEvent that was received.
1314  *
1315  * Default srcpad event handler.
1316  *
1317  * Returns: TRUE if the event was handled and can be dropped.
1318  */
1319 static gboolean
1320 gst_base_parse_src_event_default (GstBaseParse * parse, GstEvent * event)
1321 {
1322   gboolean res = FALSE;
1323
1324   switch (GST_EVENT_TYPE (event)) {
1325     case GST_EVENT_SEEK:
1326       if (gst_base_parse_is_seekable (parse))
1327         res = gst_base_parse_handle_seek (parse, event);
1328       break;
1329     default:
1330       res = gst_pad_event_default (parse->srcpad, GST_OBJECT_CAST (parse),
1331           event);
1332       break;
1333   }
1334   return res;
1335 }
1336
1337
1338 /**
1339  * gst_base_parse_convert_default:
1340  * @parse: #GstBaseParse.
1341  * @src_format: #GstFormat describing the source format.
1342  * @src_value: Source value to be converted.
1343  * @dest_format: #GstFormat defining the converted format.
1344  * @dest_value: Pointer where the conversion result will be put.
1345  *
1346  * Default implementation of "convert" vmethod in #GstBaseParse class.
1347  *
1348  * Returns: TRUE if conversion was successful.
1349  */
1350 gboolean
1351 gst_base_parse_convert_default (GstBaseParse * parse,
1352     GstFormat src_format,
1353     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
1354 {
1355   gboolean ret = FALSE;
1356   guint64 bytes, duration;
1357
1358   if (G_UNLIKELY (src_format == dest_format)) {
1359     *dest_value = src_value;
1360     return TRUE;
1361   }
1362
1363   if (G_UNLIKELY (src_value == -1)) {
1364     *dest_value = -1;
1365     return TRUE;
1366   }
1367
1368   if (G_UNLIKELY (src_value == 0)) {
1369     *dest_value = 0;
1370     return TRUE;
1371   }
1372
1373   /* need at least some frames */
1374   if (!parse->priv->framecount)
1375     goto no_framecount;
1376
1377   duration = parse->priv->acc_duration / GST_MSECOND;
1378   bytes = parse->priv->bytecount;
1379
1380   if (G_UNLIKELY (!duration || !bytes))
1381     goto no_duration_bytes;
1382
1383   if (src_format == GST_FORMAT_BYTES) {
1384     if (dest_format == GST_FORMAT_TIME) {
1385       /* BYTES -> TIME conversion */
1386       GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1387       *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1388       *dest_value *= GST_MSECOND;
1389       GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1390           *dest_value / GST_MSECOND);
1391       ret = TRUE;
1392     } else {
1393       GST_DEBUG_OBJECT (parse, "converting bytes -> other not implemented");
1394     }
1395   } else if (src_format == GST_FORMAT_TIME) {
1396     if (dest_format == GST_FORMAT_BYTES) {
1397       GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1398       *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1399           duration);
1400       GST_DEBUG_OBJECT (parse,
1401           "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1402           src_value / GST_MSECOND, *dest_value);
1403       ret = TRUE;
1404     } else {
1405       GST_DEBUG_OBJECT (parse, "converting time -> other not implemented");
1406     }
1407   } else if (src_format == GST_FORMAT_DEFAULT) {
1408     /* DEFAULT == frame-based */
1409     if (dest_format == GST_FORMAT_TIME) {
1410       GST_DEBUG_OBJECT (parse, "converting default -> time");
1411       if (parse->priv->fps_den) {
1412         *dest_value = gst_util_uint64_scale (src_value,
1413             GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1414         ret = TRUE;
1415       }
1416     } else {
1417       GST_DEBUG_OBJECT (parse, "converting default -> other not implemented");
1418     }
1419   } else {
1420     GST_DEBUG_OBJECT (parse, "conversion not implemented");
1421   }
1422   return ret;
1423
1424   /* ERRORS */
1425 no_framecount:
1426   {
1427     GST_DEBUG_OBJECT (parse, "no framecount");
1428     return FALSE;
1429   }
1430 no_duration_bytes:
1431   {
1432     GST_DEBUG_OBJECT (parse, "no duration %" G_GUINT64_FORMAT ", bytes %"
1433         G_GUINT64_FORMAT, duration, bytes);
1434     return FALSE;
1435   }
1436
1437 }
1438
1439 static void
1440 gst_base_parse_update_duration (GstBaseParse * baseparse)
1441 {
1442   GstPad *peer;
1443   GstBaseParse *parse;
1444
1445   parse = GST_BASE_PARSE (baseparse);
1446
1447   peer = gst_pad_get_peer (parse->sinkpad);
1448   if (peer) {
1449     gboolean qres = FALSE;
1450     gint64 ptot, dest_value;
1451
1452     qres = gst_pad_query_duration (peer, GST_FORMAT_BYTES, &ptot);
1453     gst_object_unref (GST_OBJECT (peer));
1454     if (qres) {
1455       if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, ptot,
1456               GST_FORMAT_TIME, &dest_value)) {
1457
1458         /* inform if duration changed, but try to avoid spamming */
1459         parse->priv->estimated_drift +=
1460             dest_value - parse->priv->estimated_duration;
1461         if (parse->priv->estimated_drift > GST_SECOND ||
1462             parse->priv->estimated_drift < -GST_SECOND) {
1463           gst_element_post_message (GST_ELEMENT (parse),
1464               gst_message_new_duration_changed (GST_OBJECT (parse)));
1465           parse->priv->estimated_drift = 0;
1466         }
1467         parse->priv->estimated_duration = dest_value;
1468         GST_LOG_OBJECT (parse,
1469             "updated estimated duration to %" GST_TIME_FORMAT,
1470             GST_TIME_ARGS (dest_value));
1471       }
1472     }
1473   }
1474 }
1475
1476 static void
1477 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1478     gboolean post_avg, gboolean post_max)
1479 {
1480   GstTagList *taglist = NULL;
1481
1482   if (post_min && parse->priv->post_min_bitrate) {
1483     taglist = gst_tag_list_new_empty ();
1484
1485     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1486         GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1487   }
1488
1489   if (post_avg && parse->priv->post_avg_bitrate) {
1490     if (taglist == NULL)
1491       taglist = gst_tag_list_new_empty ();
1492
1493     parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1494     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1495         parse->priv->avg_bitrate, NULL);
1496   }
1497
1498   if (post_max && parse->priv->post_max_bitrate) {
1499     if (taglist == NULL)
1500       taglist = gst_tag_list_new_empty ();
1501
1502     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1503         GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1504   }
1505
1506   GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1507       parse->priv->min_bitrate, parse->priv->avg_bitrate,
1508       parse->priv->max_bitrate);
1509
1510   if (taglist != NULL) {
1511     gst_pad_push_event (parse->srcpad, gst_event_new_tag (taglist));
1512   }
1513 }
1514
1515 /* gst_base_parse_update_bitrates:
1516  * @parse: #GstBaseParse.
1517  * @buffer: Current frame as a #GstBuffer
1518  *
1519  * Keeps track of the minimum and maximum bitrates, and also maintains a
1520  * running average bitrate of the stream so far.
1521  */
1522 static void
1523 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1524 {
1525   /* Only update the tag on a 10 kbps delta */
1526   static const gint update_threshold = 10000;
1527
1528   guint64 data_len, frame_dur;
1529   gint overhead, frame_bitrate, old_avg_bitrate;
1530   gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1531   GstBuffer *buffer = frame->buffer;
1532
1533   overhead = frame->overhead;
1534   if (overhead == -1)
1535     return;
1536
1537   data_len = gst_buffer_get_size (buffer) - overhead;
1538   parse->priv->data_bytecount += data_len;
1539
1540   /* duration should be valid by now,
1541    * either set by subclass or maybe based on fps settings */
1542   if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1543     /* Calculate duration of a frame from buffer properties */
1544     frame_dur = GST_BUFFER_DURATION (buffer);
1545     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1546         parse->priv->acc_duration;
1547
1548   } else {
1549     /* No way to figure out frame duration (is this even possible?) */
1550     return;
1551   }
1552
1553   /* override if subclass provided bitrate, e.g. metadata based */
1554   if (parse->priv->bitrate) {
1555     parse->priv->avg_bitrate = parse->priv->bitrate;
1556     /* spread this (confirmed) info ASAP */
1557     if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
1558       gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1559   }
1560
1561   if (frame_dur)
1562     frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1563   else
1564     return;
1565
1566   GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1567       parse->priv->avg_bitrate);
1568
1569   if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
1570     goto exit;
1571   } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
1572     /* always post all at threshold time */
1573     update_min = update_max = update_avg = TRUE;
1574   }
1575
1576   if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1577     if (frame_bitrate < parse->priv->min_bitrate) {
1578       parse->priv->min_bitrate = frame_bitrate;
1579       update_min = TRUE;
1580     }
1581
1582     if (frame_bitrate > parse->priv->max_bitrate) {
1583       parse->priv->max_bitrate = frame_bitrate;
1584       update_max = TRUE;
1585     }
1586
1587     old_avg_bitrate = parse->priv->posted_avg_bitrate;
1588     if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
1589         || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
1590         update_threshold)
1591       update_avg = TRUE;
1592   }
1593
1594   if ((update_min || update_avg || update_max))
1595     gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1596
1597 exit:
1598   return;
1599 }
1600
1601 /**
1602  * gst_base_parse_add_index_entry:
1603  * @parse: #GstBaseParse.
1604  * @offset: offset of entry
1605  * @ts: timestamp associated with offset
1606  * @key: whether entry refers to keyframe
1607  * @force: add entry disregarding sanity checks
1608  *
1609  * Adds an entry to the index associating @offset to @ts.  It is recommended
1610  * to only add keyframe entries.  @force allows to bypass checks, such as
1611  * whether the stream is (upstream) seekable, another entry is already "close"
1612  * to the new entry, etc.
1613  *
1614  * Returns: #gboolean indicating whether entry was added
1615  */
1616 gboolean
1617 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1618     GstClockTime ts, gboolean key, gboolean force)
1619 {
1620   gboolean ret = FALSE;
1621   GstIndexAssociation associations[2];
1622
1623   GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1624       " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1625
1626   if (G_LIKELY (!force)) {
1627
1628     if (!parse->priv->upstream_seekable) {
1629       GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1630       goto exit;
1631     }
1632
1633     /* FIXME need better helper data structure that handles these issues
1634      * related to ongoing collecting of index entries */
1635     if (parse->priv->index_last_offset + parse->priv->idx_byte_interval >=
1636         (gint64) offset) {
1637       GST_LOG_OBJECT (parse,
1638           "already have entries up to offset 0x%08" G_GINT64_MODIFIER "x",
1639           parse->priv->index_last_offset + parse->priv->idx_byte_interval);
1640       goto exit;
1641     }
1642
1643     if (GST_CLOCK_TIME_IS_VALID (parse->priv->index_last_ts) &&
1644         GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1645         parse->priv->idx_interval) {
1646       GST_LOG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1647           GST_TIME_ARGS (parse->priv->index_last_ts));
1648       goto exit;
1649     }
1650
1651     /* if last is not really the last one */
1652     if (!parse->priv->index_last_valid) {
1653       GstClockTime prev_ts;
1654
1655       gst_base_parse_find_offset (parse, ts, TRUE, &prev_ts);
1656       if (GST_CLOCK_DIFF (prev_ts, ts) < parse->priv->idx_interval) {
1657         GST_LOG_OBJECT (parse,
1658             "entry too close to existing entry %" GST_TIME_FORMAT,
1659             GST_TIME_ARGS (prev_ts));
1660         parse->priv->index_last_offset = offset;
1661         parse->priv->index_last_ts = ts;
1662         goto exit;
1663       }
1664     }
1665   }
1666
1667   associations[0].format = GST_FORMAT_TIME;
1668   associations[0].value = ts;
1669   associations[1].format = GST_FORMAT_BYTES;
1670   associations[1].value = offset;
1671
1672   /* index might change on-the-fly, although that would be nutty app ... */
1673   GST_BASE_PARSE_INDEX_LOCK (parse);
1674   gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1675       (key) ? GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT :
1676       GST_INDEX_ASSOCIATION_FLAG_DELTA_UNIT, 2,
1677       (const GstIndexAssociation *) &associations);
1678   GST_BASE_PARSE_INDEX_UNLOCK (parse);
1679
1680   if (key) {
1681     parse->priv->index_last_offset = offset;
1682     parse->priv->index_last_ts = ts;
1683   }
1684
1685   ret = TRUE;
1686
1687 exit:
1688   return ret;
1689 }
1690
1691 /* check for seekable upstream, above and beyond a mere query */
1692 static void
1693 gst_base_parse_check_seekability (GstBaseParse * parse)
1694 {
1695   GstQuery *query;
1696   gboolean seekable = FALSE;
1697   gint64 start = -1, stop = -1;
1698   guint idx_interval = 0;
1699   guint64 idx_byte_interval = 0;
1700
1701   query = gst_query_new_seeking (GST_FORMAT_BYTES);
1702   if (!gst_pad_peer_query (parse->sinkpad, query)) {
1703     GST_DEBUG_OBJECT (parse, "seeking query failed");
1704     goto done;
1705   }
1706
1707   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1708
1709   /* try harder to query upstream size if we didn't get it the first time */
1710   if (seekable && stop == -1) {
1711     GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1712     gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_BYTES, &stop);
1713   }
1714
1715   /* if upstream doesn't know the size, it's likely that it's not seekable in
1716    * practice even if it technically may be seekable */
1717   if (seekable && (start != 0 || stop <= start)) {
1718     GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1719     seekable = FALSE;
1720   }
1721
1722   /* let's not put every single frame into our index */
1723   if (seekable) {
1724     if (stop < 10 * 1024 * 1024)
1725       idx_interval = 100;
1726     else if (stop < 100 * 1024 * 1024)
1727       idx_interval = 500;
1728     else
1729       idx_interval = 1000;
1730
1731     /* ensure that even for large files (e.g. very long audio files), the index
1732      * stays reasonably-size, with some arbitrary limit to the total number of
1733      * index entries */
1734     idx_byte_interval = (stop - start) / MAX_INDEX_ENTRIES;
1735     GST_DEBUG_OBJECT (parse,
1736         "Limiting index entries to %d, indexing byte interval %"
1737         G_GUINT64_FORMAT " bytes", MAX_INDEX_ENTRIES, idx_byte_interval);
1738   }
1739
1740 done:
1741   gst_query_unref (query);
1742
1743   GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1744       G_GUINT64_FORMAT ")", seekable, start, stop);
1745   parse->priv->upstream_seekable = seekable;
1746   parse->priv->upstream_size = seekable ? stop : 0;
1747
1748   GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1749   parse->priv->idx_interval = idx_interval * GST_MSECOND;
1750   parse->priv->idx_byte_interval = idx_byte_interval;
1751 }
1752
1753 /* some misc checks on upstream */
1754 static void
1755 gst_base_parse_check_upstream (GstBaseParse * parse)
1756 {
1757   gint64 stop;
1758
1759   if (gst_pad_peer_query_duration (parse->sinkpad, GST_FORMAT_TIME, &stop))
1760     if (GST_CLOCK_TIME_IS_VALID (stop) && stop) {
1761       /* upstream has one, accept it also, and no further updates */
1762       gst_base_parse_set_duration (parse, GST_FORMAT_TIME, stop, 0);
1763       parse->priv->upstream_has_duration = TRUE;
1764     }
1765
1766   GST_DEBUG_OBJECT (parse, "upstream_has_duration: %d",
1767       parse->priv->upstream_has_duration);
1768 }
1769
1770 /* checks src caps to determine if dealing with audio or video */
1771 /* TODO maybe forego automagic stuff and let subclass configure it ? */
1772 static void
1773 gst_base_parse_check_media (GstBaseParse * parse)
1774 {
1775   GstCaps *caps;
1776   GstStructure *s;
1777
1778   caps = gst_pad_get_current_caps (parse->srcpad);
1779   if (G_LIKELY (caps) && (s = gst_caps_get_structure (caps, 0))) {
1780     parse->priv->is_video =
1781         g_str_has_prefix (gst_structure_get_name (s), "video");
1782   } else {
1783     /* historical default */
1784     parse->priv->is_video = FALSE;
1785   }
1786   if (caps)
1787     gst_caps_unref (caps);
1788
1789   GST_DEBUG_OBJECT (parse, "media is video: %d", parse->priv->is_video);
1790 }
1791
1792 /* takes ownership of frame */
1793 static void
1794 gst_base_parse_queue_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
1795 {
1796   if (!(frame->_private_flags & GST_BASE_PARSE_FRAME_PRIVATE_FLAG_NOALLOC)) {
1797     /* frame allocated on the heap, we can just take ownership */
1798     g_queue_push_tail (&parse->priv->queued_frames, frame);
1799     GST_TRACE ("queued frame %p", frame);
1800   } else {
1801     GstBaseParseFrame *copy;
1802
1803     /* probably allocated on the stack, must make a proper copy */
1804     copy = gst_base_parse_frame_copy (frame);
1805     g_queue_push_tail (&parse->priv->queued_frames, copy);
1806     GST_TRACE ("queued frame %p (copy of %p)", copy, frame);
1807     gst_base_parse_frame_free (frame);
1808   }
1809 }
1810
1811 /* makes sure that @buf is properly prepared and decorated for passing
1812  * to baseclass, and an equally setup frame is returned setup with @buf.
1813  * Takes ownership of @buf. */
1814 static GstBaseParseFrame *
1815 gst_base_parse_prepare_frame (GstBaseParse * parse, GstBuffer * buffer)
1816 {
1817   GstBaseParseFrame *frame = NULL;
1818
1819   buffer = gst_buffer_make_writable (buffer);
1820
1821   GST_LOG_OBJECT (parse,
1822       "preparing frame at offset %" G_GUINT64_FORMAT
1823       " (%#" G_GINT64_MODIFIER "x) of size %" G_GSIZE_FORMAT,
1824       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1825       gst_buffer_get_size (buffer));
1826
1827   if (parse->priv->discont) {
1828     GST_DEBUG_OBJECT (parse, "marking DISCONT");
1829     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1830     parse->priv->discont = FALSE;
1831   }
1832
1833   GST_BUFFER_OFFSET (buffer) = parse->priv->offset;
1834
1835   frame = gst_base_parse_frame_new (buffer, 0, 0);
1836
1837   /* also ensure to update state flags */
1838   gst_base_parse_frame_update (parse, frame, buffer);
1839   gst_buffer_unref (buffer);
1840
1841   if (parse->priv->prev_offset != parse->priv->offset || parse->priv->new_frame) {
1842     GST_LOG_OBJECT (parse, "marking as new frame");
1843     parse->priv->new_frame = FALSE;
1844     frame->flags |= GST_BASE_PARSE_FRAME_FLAG_NEW_FRAME;
1845   }
1846
1847   frame->offset = parse->priv->prev_offset = parse->priv->offset;
1848
1849   /* use default handler to provide initial (upstream) metadata */
1850   gst_base_parse_parse_frame (parse, frame);
1851
1852   return frame;
1853 }
1854
1855 /* Wraps buffer in a frame and dispatches to subclass.
1856  * Also manages data skipping and offset handling (including adapter flushing).
1857  * Takes ownership of @buffer */
1858 static GstFlowReturn
1859 gst_base_parse_handle_buffer (GstBaseParse * parse, GstBuffer * buffer,
1860     gint * skip, gint * flushed)
1861 {
1862   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1863   GstBaseParseFrame *frame;
1864   GstFlowReturn ret;
1865
1866   g_return_val_if_fail (skip != NULL || flushed != NULL, GST_FLOW_ERROR);
1867
1868   GST_LOG_OBJECT (parse,
1869       "handling buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
1870       ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
1871       gst_buffer_get_size (buffer), GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
1872       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1873       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1874
1875   /* track what is being flushed during this single round of frame processing */
1876   parse->priv->flushed = 0;
1877   *skip = 0;
1878
1879   /* make it easy for _finish_frame to pick up input data */
1880   if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1881     gst_buffer_ref (buffer);
1882     gst_adapter_push (parse->priv->adapter, buffer);
1883   }
1884
1885   frame = gst_base_parse_prepare_frame (parse, buffer);
1886   ret = klass->handle_frame (parse, frame, skip);
1887
1888   *flushed = parse->priv->flushed;
1889
1890   GST_LOG_OBJECT (parse, "handle_frame skipped %d, flushed %d",
1891       *skip, *flushed);
1892
1893   /* subclass can only do one of these, or semantics are too unclear */
1894   g_assert (*skip == 0 || *flushed == 0);
1895
1896   /* track skipping */
1897   if (*skip > 0) {
1898     GstClockTime pts, dts;
1899     GstBuffer *outbuf;
1900
1901     GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", *skip);
1902     if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
1903       /* reverse playback, and no frames found yet, so we are skipping
1904        * the leading part of a fragment, which may form the tail of
1905        * fragment coming later, hopefully subclass skips efficiently ... */
1906       pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
1907       dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
1908       outbuf = gst_adapter_take_buffer (parse->priv->adapter, *skip);
1909       outbuf = gst_buffer_make_writable (outbuf);
1910       GST_BUFFER_PTS (outbuf) = pts;
1911       GST_BUFFER_DTS (outbuf) = dts;
1912       parse->priv->buffers_head =
1913           g_slist_prepend (parse->priv->buffers_head, outbuf);
1914       outbuf = NULL;
1915     } else {
1916       gst_adapter_flush (parse->priv->adapter, *skip);
1917     }
1918     if (!parse->priv->discont)
1919       parse->priv->sync_offset = parse->priv->offset;
1920     parse->priv->offset += *skip;
1921     parse->priv->discont = TRUE;
1922     /* check for indefinite skipping */
1923     if (ret == GST_FLOW_OK)
1924       ret = gst_base_parse_check_sync (parse);
1925   }
1926
1927   parse->priv->offset += *flushed;
1928
1929   if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1930     gst_adapter_clear (parse->priv->adapter);
1931   }
1932
1933   gst_base_parse_frame_free (frame);
1934
1935   return ret;
1936 }
1937
1938 /* gst_base_parse_handle_and_push_frame:
1939  * @parse: #GstBaseParse.
1940  * @klass: #GstBaseParseClass.
1941  * @frame: (transfer full): a #GstBaseParseFrame
1942  *
1943  * Parses the frame from given buffer and pushes it forward. Also performs
1944  * timestamp handling and checks the segment limits.
1945  *
1946  * This is called with srcpad STREAM_LOCK held.
1947  *
1948  * Returns: #GstFlowReturn
1949  */
1950 static GstFlowReturn
1951 gst_base_parse_handle_and_push_frame (GstBaseParse * parse,
1952     GstBaseParseFrame * frame)
1953 {
1954   gint64 offset;
1955   GstBuffer *buffer;
1956
1957   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
1958
1959   buffer = frame->buffer;
1960   offset = frame->offset;
1961
1962   /* check if subclass/format can provide ts.
1963    * If so, that allows and enables extra seek and duration determining options */
1964   if (G_UNLIKELY (parse->priv->first_frame_offset < 0)) {
1965     if (GST_BUFFER_PTS_IS_VALID (buffer) && parse->priv->has_timing_info
1966         && parse->priv->pad_mode == GST_PAD_MODE_PULL) {
1967       parse->priv->first_frame_offset = offset;
1968       parse->priv->first_frame_pts = GST_BUFFER_PTS (buffer);
1969       parse->priv->first_frame_dts = GST_BUFFER_DTS (buffer);
1970       GST_DEBUG_OBJECT (parse, "subclass provided dts %" GST_TIME_FORMAT
1971           ", pts %" GST_TIME_FORMAT " for first frame at offset %"
1972           G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->first_frame_dts),
1973           GST_TIME_ARGS (parse->priv->first_frame_pts),
1974           parse->priv->first_frame_offset);
1975       if (!GST_CLOCK_TIME_IS_VALID (parse->priv->duration)) {
1976         gint64 off;
1977         GstClockTime last_ts = G_MAXINT64;
1978
1979         GST_DEBUG_OBJECT (parse, "no duration; trying scan to determine");
1980         gst_base_parse_locate_time (parse, &last_ts, &off);
1981         if (GST_CLOCK_TIME_IS_VALID (last_ts))
1982           gst_base_parse_set_duration (parse, GST_FORMAT_TIME, last_ts, 0);
1983       }
1984     } else {
1985       /* disable further checks */
1986       parse->priv->first_frame_offset = 0;
1987     }
1988   }
1989
1990   /* interpolating and no valid pts yet,
1991    * start with dts and carry on from there */
1992   if (parse->priv->infer_ts && !GST_CLOCK_TIME_IS_VALID (parse->priv->next_pts))
1993     parse->priv->next_pts = parse->priv->next_dts;
1994
1995   /* again use default handler to add missing metadata;
1996    * we may have new information on frame properties */
1997   gst_base_parse_parse_frame (parse, frame);
1998
1999   parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2000   if (GST_BUFFER_DTS_IS_VALID (buffer) && GST_BUFFER_DURATION_IS_VALID (buffer)) {
2001     parse->priv->next_dts =
2002         GST_BUFFER_DTS (buffer) + GST_BUFFER_DURATION (buffer);
2003     if (parse->priv->pts_interpolate && GST_BUFFER_PTS_IS_VALID (buffer)) {
2004       GstClockTime next_pts =
2005           GST_BUFFER_PTS (buffer) + GST_BUFFER_DURATION (buffer);
2006       if (next_pts >= parse->priv->next_dts)
2007         parse->priv->next_pts = next_pts;
2008     }
2009   } else {
2010     /* we lost track, do not produce bogus time next time around
2011      * (probably means parser subclass has given up on parsing as well) */
2012     GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
2013     parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2014   }
2015
2016   if (parse->priv->upstream_seekable && parse->priv->exact_position &&
2017       GST_BUFFER_PTS_IS_VALID (buffer))
2018     gst_base_parse_add_index_entry (parse, offset,
2019         GST_BUFFER_PTS (buffer),
2020         !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
2021
2022   /* All OK, push queued frames if there are any */
2023   if (G_UNLIKELY (!g_queue_is_empty (&parse->priv->queued_frames))) {
2024     GstBaseParseFrame *queued_frame;
2025
2026     while ((queued_frame = g_queue_pop_head (&parse->priv->queued_frames))) {
2027       gst_base_parse_push_frame (parse, queued_frame);
2028     }
2029   }
2030
2031   return gst_base_parse_push_frame (parse, frame);
2032 }
2033
2034 /**
2035  * gst_base_parse_push_frame:
2036  * @parse: #GstBaseParse.
2037  * @frame: (transfer none): a #GstBaseParseFrame
2038  *
2039  * Pushes the frame's buffer downstream, sends any pending events and
2040  * does some timestamp and segment handling. Takes ownership of
2041  * frame's buffer, though caller retains ownership of @frame.
2042  *
2043  * This must be called with sinkpad STREAM_LOCK held.
2044  *
2045  * Returns: #GstFlowReturn
2046  */
2047 GstFlowReturn
2048 gst_base_parse_push_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
2049 {
2050   GstFlowReturn ret = GST_FLOW_OK;
2051   GstClockTime last_start = GST_CLOCK_TIME_NONE;
2052   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
2053   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
2054   GstBuffer *buffer;
2055   gsize size;
2056
2057   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2058   g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2059
2060   GST_TRACE_OBJECT (parse, "pushing frame %p", frame);
2061
2062   buffer = frame->buffer;
2063
2064   GST_LOG_OBJECT (parse,
2065       "processing buffer of size %" G_GSIZE_FORMAT " with dts %" GST_TIME_FORMAT
2066       ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT,
2067       gst_buffer_get_size (buffer),
2068       GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2069       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
2070       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
2071
2072   /* update stats */
2073   parse->priv->bytecount += frame->size;
2074   if (G_LIKELY (!(frame->flags & GST_BASE_PARSE_FRAME_FLAG_NO_FRAME))) {
2075     parse->priv->framecount++;
2076     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
2077       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
2078     }
2079   }
2080   /* 0 means disabled */
2081   if (parse->priv->update_interval < 0)
2082     parse->priv->update_interval = 50;
2083   else if (parse->priv->update_interval > 0 &&
2084       (parse->priv->framecount % parse->priv->update_interval) == 0)
2085     gst_base_parse_update_duration (parse);
2086
2087   if (GST_BUFFER_PTS_IS_VALID (buffer))
2088     last_start = last_stop = GST_BUFFER_PTS (buffer);
2089   if (last_start != GST_CLOCK_TIME_NONE
2090       && GST_BUFFER_DURATION_IS_VALID (buffer))
2091     last_stop = last_start + GST_BUFFER_DURATION (buffer);
2092
2093   /* should have caps by now */
2094   if (!gst_pad_has_current_caps (parse->srcpad))
2095     goto no_caps;
2096
2097   if (G_UNLIKELY (parse->priv->pending_segment)) {
2098     /* have caps; check identity */
2099     gst_base_parse_check_media (parse);
2100   }
2101
2102   /* Push pending events, including SEGMENT events */
2103   if (G_UNLIKELY (parse->priv->pending_events)) {
2104     GList *r = g_list_reverse (parse->priv->pending_events);
2105     GList *l;
2106
2107     parse->priv->pending_events = NULL;
2108     for (l = r; l != NULL; l = l->next) {
2109       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
2110     }
2111     g_list_free (r);
2112     parse->priv->pending_segment = FALSE;
2113   }
2114
2115   /* segment adjustment magic; only if we are running the whole show */
2116   if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
2117       (parse->priv->pad_mode == GST_PAD_MODE_PULL ||
2118           parse->priv->upstream_seekable)) {
2119     /* handle gaps */
2120     if (GST_CLOCK_TIME_IS_VALID (parse->segment.position) &&
2121         GST_CLOCK_TIME_IS_VALID (last_start)) {
2122       GstClockTimeDiff diff;
2123
2124       /* only send newsegments with increasing start times,
2125        * otherwise if these go back and forth downstream (sinks) increase
2126        * accumulated time and running_time */
2127       diff = GST_CLOCK_DIFF (parse->segment.position, last_start);
2128       if (G_UNLIKELY (diff > 2 * GST_SECOND
2129               && last_start > parse->segment.start
2130               && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop)
2131                   || last_start < parse->segment.stop))) {
2132
2133         GST_DEBUG_OBJECT (parse,
2134             "Gap of %" G_GINT64_FORMAT " ns detected in stream " "(%"
2135             GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
2136             "Sending updated SEGMENT events", diff,
2137             GST_TIME_ARGS (parse->segment.position),
2138             GST_TIME_ARGS (last_start));
2139
2140         /* skip gap FIXME */
2141         gst_pad_push_event (parse->srcpad,
2142             gst_event_new_segment (&parse->segment));
2143
2144         parse->segment.position = last_start;
2145       }
2146     }
2147   }
2148
2149   /* update bitrates and optionally post corresponding tags
2150    * (following newsegment) */
2151   gst_base_parse_update_bitrates (parse, frame);
2152
2153   if (klass->pre_push_frame) {
2154     ret = klass->pre_push_frame (parse, frame);
2155   } else {
2156     frame->flags |= GST_BASE_PARSE_FRAME_FLAG_CLIP;
2157   }
2158
2159   /* take final ownership of frame buffer */
2160   if (frame->out_buffer) {
2161     buffer = frame->out_buffer;
2162     frame->out_buffer = NULL;
2163     gst_buffer_replace (&frame->buffer, NULL);
2164   } else {
2165     buffer = frame->buffer;
2166     frame->buffer = NULL;
2167   }
2168
2169   /* subclass must play nice */
2170   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2171
2172   size = gst_buffer_get_size (buffer);
2173
2174   parse->priv->seen_keyframe |= parse->priv->is_video &&
2175       !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT);
2176
2177   if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_CLIP) {
2178     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2179         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
2180         GST_BUFFER_TIMESTAMP (buffer) >
2181         parse->segment.stop + parse->priv->lead_out_ts) {
2182       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
2183       ret = GST_FLOW_EOS;
2184     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
2185         GST_BUFFER_DURATION_IS_VALID (buffer) &&
2186         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
2187         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
2188         parse->priv->lead_in_ts < parse->segment.start) {
2189       if (parse->priv->seen_keyframe) {
2190         GST_LOG_OBJECT (parse, "Frame before segment, after keyframe");
2191         ret = GST_FLOW_OK;
2192       } else {
2193         GST_LOG_OBJECT (parse, "Dropped frame, before segment");
2194         ret = GST_BASE_PARSE_FLOW_DROPPED;
2195       }
2196     } else {
2197       ret = GST_FLOW_OK;
2198     }
2199   }
2200
2201   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
2202     GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) dropped", size);
2203     gst_buffer_unref (buffer);
2204     ret = GST_FLOW_OK;
2205   } else if (ret == GST_FLOW_OK) {
2206     if (parse->segment.rate > 0.0) {
2207       GST_LOG_OBJECT (parse, "pushing frame (%" G_GSIZE_FORMAT " bytes) now..",
2208           size);
2209       ret = gst_pad_push (parse->srcpad, buffer);
2210       GST_LOG_OBJECT (parse, "frame pushed, flow %s", gst_flow_get_name (ret));
2211     } else {
2212       GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) queued for now",
2213           size);
2214       parse->priv->buffers_queued =
2215           g_slist_prepend (parse->priv->buffers_queued, buffer);
2216       ret = GST_FLOW_OK;
2217     }
2218   } else {
2219     GST_LOG_OBJECT (parse, "frame (%" G_GSIZE_FORMAT " bytes) not pushed: %s",
2220         size, gst_flow_get_name (ret));
2221     gst_buffer_unref (buffer);
2222     /* if we are not sufficiently in control, let upstream decide on EOS */
2223     if (ret == GST_FLOW_EOS &&
2224         (parse->priv->passthrough ||
2225             (parse->priv->pad_mode == GST_PAD_MODE_PUSH &&
2226                 !parse->priv->upstream_seekable)))
2227       ret = GST_FLOW_OK;
2228   }
2229
2230   /* Update current running segment position */
2231   if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
2232       parse->segment.position < last_stop)
2233     parse->segment.position = last_stop;
2234
2235   return ret;
2236
2237   /* ERRORS */
2238 no_caps:
2239   {
2240     GST_ELEMENT_ERROR (parse, STREAM, DECODE, ("No caps set"), (NULL));
2241     return GST_FLOW_ERROR;
2242   }
2243 }
2244
2245 /**
2246  * gst_base_parse_finish_frame:
2247  * @parse: a #GstBaseParse
2248  * @frame: a #GstBaseParseFrame
2249  * @size: consumed input data represented by frame
2250  *
2251  * Collects parsed data and pushes this downstream.
2252  * Source pad caps must be set when this is called.
2253  *
2254  * If @frame's out_buffer is set, that will be used as subsequent frame data.
2255  * Otherwise, @size samples will be taken from the input and used for output,
2256  * and the output's metadata (timestamps etc) will be taken as (optionally)
2257  * set by the subclass on @frame's (input) buffer (which is otherwise
2258  * ignored for any but the above purpose/information).
2259  *
2260  * Note that the latter buffer is invalidated by this call, whereas the
2261  * caller retains ownership of @frame.
2262  *
2263  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
2264  */
2265 GstFlowReturn
2266 gst_base_parse_finish_frame (GstBaseParse * parse, GstBaseParseFrame * frame,
2267     gint size)
2268 {
2269   GstFlowReturn ret = GST_FLOW_OK;
2270
2271   g_return_val_if_fail (frame != NULL, GST_FLOW_ERROR);
2272   g_return_val_if_fail (frame->buffer != NULL, GST_FLOW_ERROR);
2273   g_return_val_if_fail (size > 0 || frame->out_buffer, GST_FLOW_ERROR);
2274   g_return_val_if_fail (gst_adapter_available (parse->priv->adapter) >= size,
2275       GST_FLOW_ERROR);
2276
2277   GST_LOG_OBJECT (parse, "finished frame at offset %" G_GUINT64_FORMAT ", "
2278       "flushing size %d", frame->offset, size);
2279
2280   /* some one-time start-up */
2281   if (G_UNLIKELY (parse->priv->framecount == 0)) {
2282     gst_base_parse_check_seekability (parse);
2283     gst_base_parse_check_upstream (parse);
2284   }
2285
2286   parse->priv->flushed += size;
2287
2288   if (parse->priv->scanning && frame->buffer) {
2289     if (!parse->priv->scanned_frame) {
2290       parse->priv->scanned_frame = gst_base_parse_frame_copy (frame);
2291     }
2292     goto exit;
2293   }
2294
2295   /* either PUSH or PULL mode arranges for adapter data */
2296   /* ensure output buffer */
2297   if (!frame->out_buffer) {
2298     GstBuffer *src, *dest;
2299
2300     frame->out_buffer = gst_adapter_take_buffer (parse->priv->adapter, size);
2301     dest = frame->out_buffer;
2302     src = frame->buffer;
2303     GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
2304     GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
2305     GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
2306     GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
2307     GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
2308     GST_MINI_OBJECT_FLAGS (dest) = GST_MINI_OBJECT_FLAGS (src);
2309   } else {
2310     gst_adapter_flush (parse->priv->adapter, size);
2311   }
2312
2313   /* use as input for subsequent processing */
2314   gst_buffer_replace (&frame->buffer, frame->out_buffer);
2315   gst_buffer_unref (frame->out_buffer);
2316   frame->out_buffer = NULL;
2317
2318   /* mark input size consumed */
2319   frame->size = size;
2320
2321   /* subclass might queue frames/data internally if it needs more
2322    * frames to decide on the format, or might request us to queue here. */
2323   if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_DROP) {
2324     gst_buffer_replace (&frame->buffer, NULL);
2325     goto exit;
2326   } else if (frame->flags & GST_BASE_PARSE_FRAME_FLAG_QUEUE) {
2327     GstBaseParseFrame *copy;
2328
2329     copy = gst_base_parse_frame_copy (frame);
2330     copy->flags &= ~GST_BASE_PARSE_FRAME_FLAG_QUEUE;
2331     gst_base_parse_queue_frame (parse, copy);
2332     goto exit;
2333   }
2334
2335   ret = gst_base_parse_handle_and_push_frame (parse, frame);
2336
2337 exit:
2338   return ret;
2339 }
2340
2341 /* gst_base_parse_drain:
2342  *
2343  * Drains the adapter until it is empty. It decreases the min_frame_size to
2344  * match the current adapter size and calls chain method until the adapter
2345  * is emptied or chain returns with error.
2346  */
2347 static void
2348 gst_base_parse_drain (GstBaseParse * parse)
2349 {
2350   guint avail;
2351
2352   GST_DEBUG_OBJECT (parse, "draining");
2353   parse->priv->drain = TRUE;
2354
2355   for (;;) {
2356     avail = gst_adapter_available (parse->priv->adapter);
2357     if (!avail)
2358       break;
2359
2360     if (gst_base_parse_chain (parse->sinkpad, GST_OBJECT_CAST (parse),
2361             NULL) != GST_FLOW_OK) {
2362       break;
2363     }
2364
2365     /* nothing changed, maybe due to truncated frame; break infinite loop */
2366     if (avail == gst_adapter_available (parse->priv->adapter)) {
2367       GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
2368       gst_adapter_clear (parse->priv->adapter);
2369     }
2370   }
2371
2372   parse->priv->drain = FALSE;
2373 }
2374
2375 /* gst_base_parse_send_buffers
2376  *
2377  * Sends buffers collected in send_buffers downstream, and ensures that list
2378  * is empty at the end (errors or not).
2379  */
2380 static GstFlowReturn
2381 gst_base_parse_send_buffers (GstBaseParse * parse)
2382 {
2383   GSList *send = NULL;
2384   GstBuffer *buf;
2385   GstFlowReturn ret = GST_FLOW_OK;
2386
2387   send = parse->priv->buffers_send;
2388
2389   /* send buffers */
2390   while (send) {
2391     buf = GST_BUFFER_CAST (send->data);
2392     GST_LOG_OBJECT (parse, "pushing buffer %p, dts %"
2393         GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
2394         ", offset %" G_GINT64_FORMAT, buf,
2395         GST_TIME_ARGS (GST_BUFFER_DTS (buf)),
2396         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
2397         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
2398
2399     /* iterate output queue an push downstream */
2400     ret = gst_pad_push (parse->srcpad, buf);
2401     send = g_slist_delete_link (send, send);
2402
2403     /* clear any leftover if error */
2404     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
2405       while (send) {
2406         buf = GST_BUFFER_CAST (send->data);
2407         gst_buffer_unref (buf);
2408         send = g_slist_delete_link (send, send);
2409       }
2410     }
2411   }
2412
2413   parse->priv->buffers_send = send;
2414
2415   return ret;
2416 }
2417
2418 /* gst_base_parse_start_fragment:
2419  *
2420  * Prepares for processing a reverse playback (forward) fragment
2421  * by (re)setting proper state variables.
2422  */
2423 static GstFlowReturn
2424 gst_base_parse_start_fragment (GstBaseParse * parse)
2425 {
2426   GST_LOG_OBJECT (parse, "starting fragment");
2427
2428   /* invalidate so no fall-back timestamping is performed;
2429    * ok if taken from subclass or upstream */
2430   parse->priv->next_pts = GST_CLOCK_TIME_NONE;
2431   parse->priv->prev_pts = GST_CLOCK_TIME_NONE;
2432   parse->priv->next_dts = GST_CLOCK_TIME_NONE;
2433   parse->priv->prev_dts = GST_CLOCK_TIME_NONE;
2434   /* prevent it hanging around stop all the time */
2435   parse->segment.position = GST_CLOCK_TIME_NONE;
2436   /* mark next run */
2437   parse->priv->discont = TRUE;
2438
2439   /* head of previous fragment is now pending tail of current fragment */
2440   parse->priv->buffers_pending = parse->priv->buffers_head;
2441   parse->priv->buffers_head = NULL;
2442
2443   return GST_FLOW_OK;
2444 }
2445
2446
2447 /* gst_base_parse_finish_fragment:
2448  *
2449  * Processes a reverse playback (forward) fragment:
2450  * - append head of last fragment that was skipped to current fragment data
2451  * - drain the resulting current fragment data (i.e. repeated chain)
2452  * - add time/duration (if needed) to frames queued by chain
2453  * - push queued data
2454  */
2455 static GstFlowReturn
2456 gst_base_parse_finish_fragment (GstBaseParse * parse, gboolean prev_head)
2457 {
2458   GstBuffer *buf;
2459   GstFlowReturn ret = GST_FLOW_OK;
2460   gboolean seen_key = FALSE, seen_delta = FALSE;
2461
2462   GST_LOG_OBJECT (parse, "finishing fragment");
2463
2464   /* restore order */
2465   parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
2466   while (parse->priv->buffers_pending) {
2467     buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
2468     if (prev_head) {
2469       GST_LOG_OBJECT (parse, "adding pending buffer (size %" G_GSIZE_FORMAT ")",
2470           gst_buffer_get_size (buf));
2471       gst_adapter_push (parse->priv->adapter, buf);
2472     } else {
2473       GST_LOG_OBJECT (parse, "discarding head buffer");
2474       gst_buffer_unref (buf);
2475     }
2476     parse->priv->buffers_pending =
2477         g_slist_delete_link (parse->priv->buffers_pending,
2478         parse->priv->buffers_pending);
2479   }
2480
2481   /* chain looks for frames and queues resulting ones (in stead of pushing) */
2482   /* initial skipped data is added to buffers_pending */
2483   gst_base_parse_drain (parse);
2484
2485   if (parse->priv->buffers_send) {
2486     buf = GST_BUFFER_CAST (parse->priv->buffers_send->data);
2487     seen_key |= !GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT);
2488   }
2489
2490   /* add metadata (if needed to queued buffers */
2491   GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
2492       GST_TIME_ARGS (parse->priv->last_pts));
2493   while (parse->priv->buffers_queued) {
2494     buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
2495
2496     /* no touching if upstream or parsing provided time */
2497     if (GST_BUFFER_PTS_IS_VALID (buf)) {
2498       GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
2499           GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2500     } else if (GST_BUFFER_DURATION_IS_VALID (buf)) {
2501       if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_pts)) {
2502         if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_pts))
2503           parse->priv->last_pts -= GST_BUFFER_DURATION (buf);
2504         else
2505           parse->priv->last_pts = 0;
2506         GST_BUFFER_PTS (buf) = parse->priv->last_pts;
2507         GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
2508             GST_TIME_ARGS (GST_BUFFER_PTS (buf)));
2509       }
2510       if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_dts)) {
2511         if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_dts))
2512           parse->priv->last_dts -= GST_BUFFER_DURATION (buf);
2513         else
2514           parse->priv->last_dts = 0;
2515         GST_BUFFER_DTS (buf) = parse->priv->last_dts;
2516         GST_LOG_OBJECT (parse, "applied dts %" GST_TIME_FORMAT,
2517             GST_TIME_ARGS (GST_BUFFER_DTS (buf)));
2518       }
2519     } else {
2520       /* no idea, very bad */
2521       GST_WARNING_OBJECT (parse, "could not determine time for buffer");
2522     }
2523
2524     parse->priv->last_pts = GST_BUFFER_PTS (buf);
2525     parse->priv->last_dts = GST_BUFFER_DTS (buf);
2526
2527     /* reverse order for ascending sending */
2528     /* send downstream at keyframe not preceded by a keyframe
2529      * (e.g. that should identify start of collection of IDR nals) */
2530     if (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DELTA_UNIT)) {
2531       if (seen_key) {
2532         ret = gst_base_parse_send_buffers (parse);
2533         /* if a problem, throw all to sending */
2534         if (ret != GST_FLOW_OK) {
2535           parse->priv->buffers_send =
2536               g_slist_reverse (parse->priv->buffers_queued);
2537           parse->priv->buffers_queued = NULL;
2538           break;
2539         }
2540         seen_key = FALSE;
2541       }
2542       seen_delta = TRUE;
2543     } else {
2544       seen_key = TRUE;
2545     }
2546
2547     parse->priv->buffers_send =
2548         g_slist_prepend (parse->priv->buffers_send, buf);
2549     parse->priv->buffers_queued =
2550         g_slist_delete_link (parse->priv->buffers_queued,
2551         parse->priv->buffers_queued);
2552   }
2553
2554   /* audio may have all marked as keyframe, so arrange to send here */
2555   if (!seen_delta)
2556     ret = gst_base_parse_send_buffers (parse);
2557
2558   /* any trailing unused no longer usable (ideally none) */
2559   if (G_UNLIKELY (gst_adapter_available (parse->priv->adapter))) {
2560     GST_DEBUG_OBJECT (parse, "discarding %" G_GSIZE_FORMAT " trailing bytes",
2561         gst_adapter_available (parse->priv->adapter));
2562     gst_adapter_clear (parse->priv->adapter);
2563   }
2564
2565   return ret;
2566 }
2567
2568 /* small helper that checks whether we have been trying to resync too long */
2569 static inline GstFlowReturn
2570 gst_base_parse_check_sync (GstBaseParse * parse)
2571 {
2572   if (G_UNLIKELY (parse->priv->discont &&
2573           parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
2574     GST_ELEMENT_ERROR (parse, STREAM, DECODE,
2575         ("Failed to parse stream"), (NULL));
2576     return GST_FLOW_ERROR;
2577   }
2578
2579   return GST_FLOW_OK;
2580 }
2581
2582 static GstFlowReturn
2583 gst_base_parse_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
2584 {
2585   GstBaseParseClass *bclass;
2586   GstBaseParse *parse;
2587   GstFlowReturn ret = GST_FLOW_OK;
2588   GstBuffer *tmpbuf = NULL;
2589   guint fsize = 1;
2590   gint skip = -1;
2591   const guint8 *data;
2592   guint min_size, av;
2593   GstClockTime pts, dts;
2594
2595   parse = GST_BASE_PARSE (parent);
2596   bclass = GST_BASE_PARSE_GET_CLASS (parse);
2597
2598   if (parse->priv->detecting) {
2599     GstBuffer *detect_buf;
2600
2601     if (parse->priv->detect_buffers_size == 0) {
2602       detect_buf = gst_buffer_ref (buffer);
2603     } else {
2604       GList *l;
2605       guint offset = 0;
2606
2607       detect_buf = gst_buffer_new ();
2608
2609       for (l = parse->priv->detect_buffers; l; l = l->next) {
2610         gsize tmpsize = gst_buffer_get_size (l->data);
2611
2612         gst_buffer_copy_into (detect_buf, GST_BUFFER_CAST (l->data),
2613             GST_BUFFER_COPY_MEMORY, offset, tmpsize);
2614         offset += tmpsize;
2615       }
2616       if (buffer)
2617         gst_buffer_copy_into (detect_buf, buffer, GST_BUFFER_COPY_MEMORY,
2618             offset, gst_buffer_get_size (buffer));
2619     }
2620
2621     ret = bclass->detect (parse, detect_buf);
2622     gst_buffer_unref (detect_buf);
2623
2624     if (ret == GST_FLOW_OK) {
2625       GList *l;
2626
2627       /* Detected something */
2628       parse->priv->detecting = FALSE;
2629
2630       for (l = parse->priv->detect_buffers; l; l = l->next) {
2631         if (ret == GST_FLOW_OK && !parse->priv->flushing)
2632           ret =
2633               gst_base_parse_chain (GST_BASE_PARSE_SINK_PAD (parse),
2634               parent, GST_BUFFER_CAST (l->data));
2635         else
2636           gst_buffer_unref (GST_BUFFER_CAST (l->data));
2637       }
2638       g_list_free (parse->priv->detect_buffers);
2639       parse->priv->detect_buffers = NULL;
2640       parse->priv->detect_buffers_size = 0;
2641
2642       if (ret != GST_FLOW_OK) {
2643         return ret;
2644       }
2645
2646       /* Handle the current buffer */
2647     } else if (ret == GST_FLOW_NOT_NEGOTIATED) {
2648       /* Still detecting, append buffer or error out if draining */
2649
2650       if (parse->priv->drain) {
2651         GST_DEBUG_OBJECT (parse, "Draining but did not detect format yet");
2652         return GST_FLOW_ERROR;
2653       } else if (parse->priv->flushing) {
2654         g_list_foreach (parse->priv->detect_buffers, (GFunc) gst_buffer_unref,
2655             NULL);
2656         g_list_free (parse->priv->detect_buffers);
2657         parse->priv->detect_buffers = NULL;
2658         parse->priv->detect_buffers_size = 0;
2659       } else {
2660         parse->priv->detect_buffers =
2661             g_list_append (parse->priv->detect_buffers, buffer);
2662         parse->priv->detect_buffers_size += gst_buffer_get_size (buffer);
2663         return GST_FLOW_OK;
2664       }
2665     } else {
2666       /* Something went wrong, subclass responsible for error reporting */
2667       return ret;
2668     }
2669
2670     /* And now handle the current buffer if detection worked */
2671   }
2672
2673   if (G_LIKELY (buffer)) {
2674     GST_LOG_OBJECT (parse,
2675         "buffer size: %" G_GSIZE_FORMAT ", offset = %" G_GINT64_FORMAT
2676         ", dts %" GST_TIME_FORMAT ", pts %" GST_TIME_FORMAT,
2677         gst_buffer_get_size (buffer), GST_BUFFER_OFFSET (buffer),
2678         GST_TIME_ARGS (GST_BUFFER_DTS (buffer)),
2679         GST_TIME_ARGS (GST_BUFFER_PTS (buffer)));
2680
2681     if (G_UNLIKELY (parse->priv->passthrough)) {
2682       GstBaseParseFrame frame;
2683
2684       gst_base_parse_frame_init (&frame);
2685       frame.buffer = gst_buffer_make_writable (buffer);
2686       ret = gst_base_parse_push_frame (parse, &frame);
2687       gst_base_parse_frame_free (&frame);
2688       return ret;
2689     }
2690     /* upstream feeding us in reverse playback;
2691      * finish previous fragment and start new upon DISCONT */
2692     if (parse->segment.rate < 0.0) {
2693       if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
2694         GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
2695         ret = gst_base_parse_finish_fragment (parse, TRUE);
2696         gst_base_parse_start_fragment (parse);
2697       }
2698     }
2699     gst_adapter_push (parse->priv->adapter, buffer);
2700   }
2701
2702   /* Parse and push as many frames as possible */
2703   /* Stop either when adapter is empty or we are flushing */
2704   while (!parse->priv->flushing) {
2705     gint flush = 0;
2706
2707     /* note: if subclass indicates MAX fsize,
2708      * this will not likely be available anyway ... */
2709     min_size = MAX (parse->priv->min_frame_size, fsize);
2710     av = gst_adapter_available (parse->priv->adapter);
2711
2712     if (G_UNLIKELY (parse->priv->drain)) {
2713       min_size = av;
2714       GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
2715       if (G_UNLIKELY (!min_size)) {
2716         goto done;
2717       }
2718     }
2719
2720     /* Collect at least min_frame_size bytes */
2721     if (av < min_size) {
2722       GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)", av);
2723       goto done;
2724     }
2725
2726     /* move along with upstream timestamp (if any),
2727      * but interpolate in between */
2728     pts = gst_adapter_prev_pts (parse->priv->adapter, NULL);
2729     dts = gst_adapter_prev_dts (parse->priv->adapter, NULL);
2730     if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
2731       parse->priv->prev_pts = parse->priv->next_pts = pts;
2732
2733     if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
2734       parse->priv->prev_dts = parse->priv->next_dts = dts;
2735
2736     /* we can mess with, erm interpolate, timestamps,
2737      * and incoming stuff has PTS but no DTS seen so far,
2738      * then pick up DTS from PTS and hope for the best ... */
2739     if (parse->priv->infer_ts &&
2740         !GST_CLOCK_TIME_IS_VALID (dts) &&
2741         !GST_CLOCK_TIME_IS_VALID (parse->priv->prev_dts) &&
2742         GST_CLOCK_TIME_IS_VALID (pts))
2743       parse->priv->next_dts = pts;
2744
2745     /* always pass all available data */
2746     data = gst_adapter_map (parse->priv->adapter, av);
2747     /* arrange for actual data to be copied if subclass tries to,
2748      * since what is passed is tied to the adapter */
2749     tmpbuf = gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY |
2750         GST_MEMORY_FLAG_NO_SHARE, (gpointer) data, av, 0, av, NULL, NULL);
2751
2752     /* keep the adapter mapped, so keep track of what has to be flushed */
2753     ret = gst_base_parse_handle_buffer (parse, tmpbuf, &skip, &flush);
2754     tmpbuf = NULL;
2755
2756     /* probably already implicitly unmapped due to adapter operation,
2757      * but for good measure ... */
2758     gst_adapter_unmap (parse->priv->adapter);
2759     if (ret != GST_FLOW_OK && ret != GST_FLOW_NOT_LINKED) {
2760       goto done;
2761     }
2762     if (skip == 0 && flush == 0) {
2763       GST_LOG_OBJECT (parse, "nothing skipped and no frames finished, "
2764           "breaking to get more data");
2765       goto done;
2766     }
2767   }
2768
2769 done:
2770   GST_LOG_OBJECT (parse, "chain leaving");
2771   return ret;
2772 }
2773
2774 /* pull @size bytes at current offset,
2775  * i.e. at least try to and possibly return a shorter buffer if near the end */
2776 static GstFlowReturn
2777 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
2778     GstBuffer ** buffer)
2779 {
2780   GstFlowReturn ret = GST_FLOW_OK;
2781
2782   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
2783
2784   /* Caching here actually makes much less difference than one would expect.
2785    * We do it mainly to avoid pulling buffers of 1 byte all the time */
2786   if (parse->priv->cache) {
2787     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
2788     gint cache_size = gst_buffer_get_size (parse->priv->cache);
2789
2790     if (cache_offset <= parse->priv->offset &&
2791         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
2792       *buffer = gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL,
2793           parse->priv->offset - cache_offset, size);
2794       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2795       return GST_FLOW_OK;
2796     }
2797     /* not enough data in the cache, free cache and get a new one */
2798     gst_buffer_unref (parse->priv->cache);
2799     parse->priv->cache = NULL;
2800   }
2801
2802   /* refill the cache */
2803   ret =
2804       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
2805           64 * 1024), &parse->priv->cache);
2806   if (ret != GST_FLOW_OK) {
2807     parse->priv->cache = NULL;
2808     return ret;
2809   }
2810
2811   if (gst_buffer_get_size (parse->priv->cache) >= size) {
2812     *buffer =
2813         gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0,
2814         size);
2815     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2816     return GST_FLOW_OK;
2817   }
2818
2819   /* Not possible to get enough data, try a last time with
2820    * requesting exactly the size we need */
2821   gst_buffer_unref (parse->priv->cache);
2822   parse->priv->cache = NULL;
2823
2824   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
2825       &parse->priv->cache);
2826
2827   if (ret != GST_FLOW_OK) {
2828     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
2829     *buffer = NULL;
2830     return ret;
2831   }
2832
2833   if (gst_buffer_get_size (parse->priv->cache) < size) {
2834     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
2835         G_GUINT64_FORMAT ": wanted %u bytes, got %" G_GSIZE_FORMAT " bytes",
2836         parse->priv->offset, size, gst_buffer_get_size (parse->priv->cache));
2837
2838     *buffer = parse->priv->cache;
2839     parse->priv->cache = NULL;
2840
2841     return GST_FLOW_OK;
2842   }
2843
2844   *buffer =
2845       gst_buffer_copy_region (parse->priv->cache, GST_BUFFER_COPY_ALL, 0, size);
2846   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
2847
2848   return GST_FLOW_OK;
2849 }
2850
2851 static GstFlowReturn
2852 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
2853 {
2854   gint64 offset = 0;
2855   GstClockTime ts = 0;
2856   GstBuffer *buffer;
2857   GstFlowReturn ret;
2858
2859   GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
2860       ", last_offset = %" G_GINT64_FORMAT,
2861       GST_TIME_ARGS (parse->priv->last_pts), parse->priv->last_offset);
2862
2863   if (!parse->priv->last_offset
2864       || parse->priv->last_pts <= parse->segment.start) {
2865     GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2866         GST_TIME_ARGS (parse->segment.start));
2867     ret = GST_FLOW_EOS;
2868     goto exit;
2869   }
2870
2871   /* last fragment started at last_offset / last_ts;
2872    * seek back 10s capped at 1MB */
2873   if (parse->priv->last_pts >= 10 * GST_SECOND)
2874     ts = parse->priv->last_pts - 10 * GST_SECOND;
2875   /* if we are exact now, we will be more so going backwards */
2876   if (parse->priv->exact_position) {
2877     offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2878   } else {
2879     if (!gst_base_parse_convert (parse, GST_FORMAT_TIME, ts,
2880             GST_FORMAT_BYTES, &offset)) {
2881       GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2882     }
2883   }
2884   offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2885       parse->priv->last_offset - 1024);
2886   offset = MAX (0, offset);
2887
2888   GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2889       offset);
2890   parse->priv->offset = offset;
2891
2892   ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2893       &buffer);
2894   if (ret != GST_FLOW_OK)
2895     goto exit;
2896
2897   /* offset will increase again as fragment is processed/parsed */
2898   parse->priv->last_offset = offset;
2899
2900   gst_base_parse_start_fragment (parse);
2901   gst_adapter_push (parse->priv->adapter, buffer);
2902   ret = gst_base_parse_finish_fragment (parse, TRUE);
2903   if (ret != GST_FLOW_OK)
2904     goto exit;
2905
2906   /* force previous fragment */
2907   parse->priv->offset = -1;
2908
2909 exit:
2910   return ret;
2911 }
2912
2913 /* PULL mode:
2914  * pull and scan for next frame starting from current offset
2915  * ajusts sync, drain and offset going along */
2916 static GstFlowReturn
2917 gst_base_parse_scan_frame (GstBaseParse * parse, GstBaseParseClass * klass)
2918 {
2919   GstBuffer *buffer;
2920   GstFlowReturn ret = GST_FLOW_OK;
2921   guint fsize, min_size;
2922   gint flushed = 0;
2923   gint skip = 0;
2924
2925   GST_LOG_OBJECT (parse, "scanning for frame at offset %" G_GUINT64_FORMAT
2926       " (%#" G_GINT64_MODIFIER "x)", parse->priv->offset, parse->priv->offset);
2927
2928   /* let's make this efficient for all subclass once and for all;
2929    * maybe it does not need this much, but in the latter case, we know we are
2930    * in pull mode here and might as well try to read and supply more anyway
2931    * (so does the buffer caching mechanism) */
2932   fsize = 64 * 1024;
2933
2934   while (TRUE) {
2935     min_size = MAX (parse->priv->min_frame_size, fsize);
2936
2937     GST_LOG_OBJECT (parse, "reading buffer size %u", min_size);
2938
2939     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2940     if (ret != GST_FLOW_OK)
2941       goto done;
2942
2943     /* if we got a short read, inform subclass we are draining leftover
2944      * and no more is to be expected */
2945     if (gst_buffer_get_size (buffer) < min_size) {
2946       GST_LOG_OBJECT (parse, "... but did not get that; marked draining");
2947       parse->priv->drain = TRUE;
2948     }
2949
2950     if (parse->priv->detecting) {
2951       ret = klass->detect (parse, buffer);
2952       if (ret == GST_FLOW_NOT_NEGOTIATED) {
2953         /* If draining we error out, otherwise request a buffer
2954          * with 64kb more */
2955         if (parse->priv->drain) {
2956           gst_buffer_unref (buffer);
2957           GST_ERROR_OBJECT (parse, "Failed to detect format but draining");
2958           return GST_FLOW_ERROR;
2959         } else {
2960           fsize += 64 * 1024;
2961           gst_buffer_unref (buffer);
2962           continue;
2963         }
2964       } else if (ret != GST_FLOW_OK) {
2965         gst_buffer_unref (buffer);
2966         GST_ERROR_OBJECT (parse, "detect() returned %s",
2967             gst_flow_get_name (ret));
2968         return ret;
2969       }
2970
2971       /* Else handle this buffer normally */
2972     }
2973
2974     ret = gst_base_parse_handle_buffer (parse, buffer, &skip, &flushed);
2975     if (ret != GST_FLOW_OK)
2976       break;
2977
2978     /* something flushed means something happened,
2979      * and we should bail out of this loop so as not to occupy
2980      * the task thread indefinitely */
2981     if (flushed) {
2982       GST_LOG_OBJECT (parse, "frame finished, breaking loop");
2983       break;
2984     }
2985     /* nothing flushed, no skip and draining, so nothing left to do */
2986     if (!skip && parse->priv->drain) {
2987       GST_LOG_OBJECT (parse, "no activity or result when draining; "
2988           "breaking loop and marking EOS");
2989       ret = GST_FLOW_EOS;
2990       break;
2991     }
2992     /* otherwise, get some more data
2993      * note that is checked this does not happen indefinitely */
2994     if (!skip) {
2995       GST_LOG_OBJECT (parse, "getting some more data");
2996       fsize += 64 * 1024;
2997     }
2998     parse->priv->drain = FALSE;
2999   }
3000
3001 done:
3002   return ret;
3003 }
3004
3005 /* Loop that is used in pull mode to retrieve data from upstream */
3006 static void
3007 gst_base_parse_loop (GstPad * pad)
3008 {
3009   GstBaseParse *parse;
3010   GstBaseParseClass *klass;
3011   GstFlowReturn ret = GST_FLOW_OK;
3012
3013   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
3014   klass = GST_BASE_PARSE_GET_CLASS (parse);
3015
3016   GST_LOG_OBJECT (parse, "Entering parse loop");
3017
3018   if (G_UNLIKELY (parse->priv->push_stream_start)) {
3019     gchar *stream_id;
3020
3021     stream_id =
3022         gst_pad_create_stream_id (parse->srcpad, GST_ELEMENT_CAST (parse),
3023         NULL);
3024
3025     GST_DEBUG_OBJECT (parse, "Pushing STREAM_START");
3026     gst_pad_push_event (parse->srcpad, gst_event_new_stream_start (stream_id));
3027     parse->priv->push_stream_start = FALSE;
3028     g_free (stream_id);
3029   }
3030
3031   /* reverse playback:
3032    * first fragment (closest to stop time) is handled normally below,
3033    * then we pull in fragments going backwards */
3034   if (parse->segment.rate < 0.0) {
3035     /* check if we jumped back to a previous fragment,
3036      * which is a post-first fragment */
3037     if (parse->priv->offset < 0) {
3038       ret = gst_base_parse_handle_previous_fragment (parse);
3039       goto done;
3040     }
3041   }
3042
3043   ret = gst_base_parse_scan_frame (parse, klass);
3044   if (ret != GST_FLOW_OK)
3045     goto done;
3046
3047   /* eat expected eos signalling past segment in reverse playback */
3048   if (parse->segment.rate < 0.0 && ret == GST_FLOW_EOS &&
3049       parse->segment.position >= parse->segment.stop) {
3050     GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
3051     /* push what was accumulated during loop run */
3052     gst_base_parse_finish_fragment (parse, FALSE);
3053     /* force previous fragment */
3054     parse->priv->offset = -1;
3055     ret = GST_FLOW_OK;
3056   }
3057
3058 done:
3059   if (ret == GST_FLOW_EOS)
3060     goto eos;
3061   else if (ret != GST_FLOW_OK)
3062     goto pause;
3063
3064   gst_object_unref (parse);
3065   return;
3066
3067   /* ERRORS */
3068 eos:
3069   {
3070     ret = GST_FLOW_EOS;
3071     GST_DEBUG_OBJECT (parse, "eos");
3072     /* fall-through */
3073   }
3074 pause:
3075   {
3076     gboolean push_eos = FALSE;
3077
3078     GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
3079         gst_flow_get_name (ret));
3080     gst_pad_pause_task (parse->sinkpad);
3081
3082     if (ret == GST_FLOW_EOS) {
3083       /* handle end-of-stream/segment */
3084       if (parse->segment.flags & GST_SEGMENT_FLAG_SEGMENT) {
3085         gint64 stop;
3086
3087         if ((stop = parse->segment.stop) == -1)
3088           stop = parse->segment.duration;
3089
3090         GST_DEBUG_OBJECT (parse, "sending segment_done");
3091
3092         gst_element_post_message
3093             (GST_ELEMENT_CAST (parse),
3094             gst_message_new_segment_done (GST_OBJECT_CAST (parse),
3095                 GST_FORMAT_TIME, stop));
3096         gst_pad_push_event (parse->srcpad,
3097             gst_event_new_segment_done (GST_FORMAT_TIME, stop));
3098       } else {
3099         /* If we STILL have zero frames processed, fire an error */
3100         if (parse->priv->framecount == 0) {
3101           GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
3102               ("No valid frames found before end of stream"), (NULL));
3103         }
3104         push_eos = TRUE;
3105       }
3106     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_EOS) {
3107       /* for fatal errors we post an error message, wrong-state is
3108        * not fatal because it happens due to flushes and only means
3109        * that we should stop now. */
3110       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
3111           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
3112       push_eos = TRUE;
3113     }
3114     if (push_eos) {
3115       /* Push pending events, including SEGMENT events */
3116       if (G_UNLIKELY (parse->priv->pending_events)) {
3117         GList *r = g_list_reverse (parse->priv->pending_events);
3118         GList *l;
3119
3120         parse->priv->pending_events = NULL;
3121         for (l = r; l != NULL; l = l->next) {
3122           gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
3123         }
3124         g_list_free (r);
3125         parse->priv->pending_segment = FALSE;
3126       }
3127
3128       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
3129     }
3130     gst_object_unref (parse);
3131   }
3132 }
3133
3134 static gboolean
3135 gst_base_parse_sink_activate (GstPad * sinkpad, GstObject * parent)
3136 {
3137   GstSchedulingFlags sched_flags;
3138   GstBaseParse *parse;
3139   GstQuery *query;
3140   gboolean pull_mode;
3141
3142   parse = GST_BASE_PARSE (parent);
3143
3144   GST_DEBUG_OBJECT (parse, "sink activate");
3145
3146   query = gst_query_new_scheduling ();
3147   if (!gst_pad_peer_query (sinkpad, query)) {
3148     gst_query_unref (query);
3149     goto baseparse_push;
3150   }
3151
3152   gst_query_parse_scheduling (query, &sched_flags, NULL, NULL, NULL);
3153
3154   pull_mode = gst_query_has_scheduling_mode (query, GST_PAD_MODE_PULL)
3155       && ((sched_flags & GST_SCHEDULING_FLAG_SEEKABLE) != 0);
3156
3157   gst_query_unref (query);
3158
3159   if (!pull_mode)
3160     goto baseparse_push;
3161
3162   GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
3163   if (!gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PULL, TRUE))
3164     goto baseparse_push;
3165
3166   parse->priv->push_stream_start = TRUE;
3167
3168   return gst_pad_start_task (sinkpad, (GstTaskFunction) gst_base_parse_loop,
3169       sinkpad, NULL);
3170   /* fallback */
3171 baseparse_push:
3172   {
3173     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
3174     return gst_pad_activate_mode (sinkpad, GST_PAD_MODE_PUSH, TRUE);
3175   }
3176 }
3177
3178 static gboolean
3179 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
3180 {
3181   GstBaseParseClass *klass;
3182   gboolean result = TRUE;
3183
3184   GST_DEBUG_OBJECT (parse, "activate %d", active);
3185
3186   klass = GST_BASE_PARSE_GET_CLASS (parse);
3187
3188   if (active) {
3189     if (parse->priv->pad_mode == GST_PAD_MODE_NONE && klass->start)
3190       result = klass->start (parse);
3191
3192     /* If the subclass implements ::detect we want to
3193      * call it for the first buffers now */
3194     parse->priv->detecting = (klass->detect != NULL);
3195   } else {
3196     /* We must make sure streaming has finished before resetting things
3197      * and calling the ::stop vfunc */
3198     GST_PAD_STREAM_LOCK (parse->sinkpad);
3199     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
3200
3201     if (parse->priv->pad_mode != GST_PAD_MODE_NONE && klass->stop)
3202       result = klass->stop (parse);
3203
3204     parse->priv->pad_mode = GST_PAD_MODE_NONE;
3205   }
3206   GST_DEBUG_OBJECT (parse, "activate return: %d", result);
3207   return result;
3208 }
3209
3210 static gboolean
3211 gst_base_parse_sink_activate_mode (GstPad * pad, GstObject * parent,
3212     GstPadMode mode, gboolean active)
3213 {
3214   gboolean result;
3215   GstBaseParse *parse;
3216
3217   parse = GST_BASE_PARSE (parent);
3218
3219   GST_DEBUG_OBJECT (parse, "sink %sactivate in %s mode",
3220       (active) ? "" : "de", gst_pad_mode_get_name (mode));
3221
3222   if (!gst_base_parse_activate (parse, active))
3223     goto activate_failed;
3224
3225   switch (mode) {
3226     case GST_PAD_MODE_PULL:
3227       if (active) {
3228         parse->priv->pending_events =
3229             g_list_prepend (parse->priv->pending_events,
3230             gst_event_new_segment (&parse->segment));
3231         parse->priv->pending_segment = TRUE;
3232         result = TRUE;
3233       } else {
3234         result = gst_pad_stop_task (pad);
3235       }
3236       break;
3237     default:
3238       result = TRUE;
3239       break;
3240   }
3241   if (result)
3242     parse->priv->pad_mode = active ? mode : GST_PAD_MODE_NONE;
3243
3244   GST_DEBUG_OBJECT (parse, "sink activate return: %d", result);
3245
3246   return result;
3247
3248   /* ERRORS */
3249 activate_failed:
3250   {
3251     GST_DEBUG_OBJECT (parse, "activate failed");
3252     return FALSE;
3253   }
3254 }
3255
3256 /**
3257  * gst_base_parse_set_duration:
3258  * @parse: #GstBaseParse.
3259  * @fmt: #GstFormat.
3260  * @duration: duration value.
3261  * @interval: how often to update the duration estimate based on bitrate, or 0.
3262  *
3263  * Sets the duration of the currently playing media. Subclass can use this
3264  * when it is able to determine duration and/or notices a change in the media
3265  * duration.  Alternatively, if @interval is non-zero (default), then stream
3266  * duration is determined based on estimated bitrate, and updated every @interval
3267  * frames.
3268  */
3269 void
3270 gst_base_parse_set_duration (GstBaseParse * parse,
3271     GstFormat fmt, gint64 duration, gint interval)
3272 {
3273   g_return_if_fail (parse != NULL);
3274
3275   if (parse->priv->upstream_has_duration) {
3276     GST_DEBUG_OBJECT (parse, "using upstream duration; discarding update");
3277     goto exit;
3278   }
3279
3280   if (duration != parse->priv->duration) {
3281     GstMessage *m;
3282
3283     m = gst_message_new_duration_changed (GST_OBJECT (parse));
3284     gst_element_post_message (GST_ELEMENT (parse), m);
3285
3286     /* TODO: what about duration tag? */
3287   }
3288   parse->priv->duration = duration;
3289   parse->priv->duration_fmt = fmt;
3290   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
3291   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
3292     if (interval != 0) {
3293       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
3294       interval = 0;
3295     }
3296   }
3297   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
3298   parse->priv->update_interval = interval;
3299 exit:
3300   return;
3301 }
3302
3303 /**
3304  * gst_base_parse_set_average_bitrate:
3305  * @parse: #GstBaseParse.
3306  * @bitrate: average bitrate in bits/second
3307  *
3308  * Optionally sets the average bitrate detected in media (if non-zero),
3309  * e.g. based on metadata, as it will be posted to the application.
3310  *
3311  * By default, announced average bitrate is estimated. The average bitrate
3312  * is used to estimate the total duration of the stream and to estimate
3313  * a seek position, if there's no index and the format is syncable
3314  * (see gst_base_parse_set_syncable()).
3315  */
3316 void
3317 gst_base_parse_set_average_bitrate (GstBaseParse * parse, guint bitrate)
3318 {
3319   parse->priv->bitrate = bitrate;
3320   GST_DEBUG_OBJECT (parse, "bitrate %u", bitrate);
3321 }
3322
3323 /**
3324  * gst_base_parse_set_min_frame_size:
3325  * @parse: #GstBaseParse.
3326  * @min_size: Minimum size of the data that this base class should give to
3327  *            subclass.
3328  *
3329  * Subclass can use this function to tell the base class that it needs to
3330  * give at least #min_size buffers.
3331  */
3332 void
3333 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
3334 {
3335   g_return_if_fail (parse != NULL);
3336
3337   parse->priv->min_frame_size = min_size;
3338   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
3339 }
3340
3341 /**
3342  * gst_base_parse_set_frame_rate:
3343  * @parse: the #GstBaseParse to set
3344  * @fps_num: frames per second (numerator).
3345  * @fps_den: frames per second (denominator).
3346  * @lead_in: frames needed before a segment for subsequent decode
3347  * @lead_out: frames needed after a segment
3348  *
3349  * If frames per second is configured, parser can take care of buffer duration
3350  * and timestamping.  When performing segment clipping, or seeking to a specific
3351  * location, a corresponding decoder might need an initial @lead_in and a
3352  * following @lead_out number of frames to ensure the desired segment is
3353  * entirely filled upon decoding.
3354  */
3355 void
3356 gst_base_parse_set_frame_rate (GstBaseParse * parse, guint fps_num,
3357     guint fps_den, guint lead_in, guint lead_out)
3358 {
3359   g_return_if_fail (parse != NULL);
3360
3361   parse->priv->fps_num = fps_num;
3362   parse->priv->fps_den = fps_den;
3363   if (!fps_num || !fps_den) {
3364     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
3365         fps_num, fps_den);
3366     fps_num = fps_den = 0;
3367     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
3368     parse->priv->lead_in = parse->priv->lead_out = 0;
3369     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
3370   } else {
3371     parse->priv->frame_duration =
3372         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
3373     parse->priv->lead_in = lead_in;
3374     parse->priv->lead_out = lead_out;
3375     parse->priv->lead_in_ts =
3376         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
3377     parse->priv->lead_out_ts =
3378         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
3379     /* aim for about 1.5s to estimate duration */
3380     if (parse->priv->update_interval < 0) {
3381       parse->priv->update_interval = fps_num * 3 / (fps_den * 2);
3382       GST_LOG_OBJECT (parse, "estimated update interval to %d frames",
3383           parse->priv->update_interval);
3384     }
3385   }
3386   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
3387       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
3388   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
3389       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
3390       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
3391       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
3392 }
3393
3394 /**
3395  * gst_base_parse_set_has_timing_info:
3396  * @parse: a #GstBaseParse
3397  * @has_timing: whether frames carry timing information
3398  *
3399  * Set if frames carry timing information which the subclass can (generally)
3400  * parse and provide.  In particular, intrinsic (rather than estimated) time
3401  * can be obtained following a seek.
3402  */
3403 void
3404 gst_base_parse_set_has_timing_info (GstBaseParse * parse, gboolean has_timing)
3405 {
3406   parse->priv->has_timing_info = has_timing;
3407   GST_INFO_OBJECT (parse, "has_timing: %s", (has_timing) ? "yes" : "no");
3408 }
3409
3410 /**
3411  * gst_base_parse_set_syncable:
3412  * @parse: a #GstBaseParse
3413  * @syncable: set if frame starts can be identified
3414  *
3415  * Set if frame starts can be identified. This is set by default and
3416  * determines whether seeking based on bitrate averages
3417  * is possible for a format/stream.
3418  */
3419 void
3420 gst_base_parse_set_syncable (GstBaseParse * parse, gboolean syncable)
3421 {
3422   parse->priv->syncable = syncable;
3423   GST_INFO_OBJECT (parse, "syncable: %s", (syncable) ? "yes" : "no");
3424 }
3425
3426 /**
3427  * gst_base_parse_set_passthrough:
3428  * @parse: a #GstBaseParse
3429  * @passthrough: %TRUE if parser should run in passthrough mode
3430  *
3431  * Set if the nature of the format or configuration does not allow (much)
3432  * parsing, and the parser should operate in passthrough mode (which only
3433  * applies when operating in push mode). That is, incoming buffers are
3434  * pushed through unmodified, i.e. no @check_valid_frame or @parse_frame
3435  * callbacks will be invoked, but @pre_push_frame will still be invoked,
3436  * so subclass can perform as much or as little is appropriate for
3437  * passthrough semantics in @pre_push_frame.
3438  */
3439 void
3440 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
3441 {
3442   parse->priv->passthrough = passthrough;
3443   GST_INFO_OBJECT (parse, "passthrough: %s", (passthrough) ? "yes" : "no");
3444 }
3445
3446 /**
3447  * gst_base_parse_set_pts_interpolation:
3448  * @parse: a #GstBaseParse
3449  * @pts_interpolate: %TRUE if parser should interpolate PTS timestamps
3450  *
3451  * By default, the base class will guess PTS timestamps using a simple
3452  * interpolation (previous timestamp + duration), which is incorrect for
3453  * data streams with reordering, where PTS can go backward. Sub-classes
3454  * implementing such formats should disable PTS interpolation.
3455  */
3456 void
3457 gst_base_parse_set_pts_interpolation (GstBaseParse * parse,
3458     gboolean pts_interpolate)
3459 {
3460   parse->priv->pts_interpolate = pts_interpolate;
3461   GST_INFO_OBJECT (parse, "PTS interpolation: %s",
3462       (pts_interpolate) ? "yes" : "no");
3463 }
3464
3465 /**
3466  * gst_base_parse_set_infer_ts:
3467  * @parse: a #GstBaseParse
3468  * @infer_ts: %TRUE if parser should infer DTS/PTS from each other
3469  *
3470  * By default, the base class might try to infer PTS from DTS and vice
3471  * versa.  While this is generally correct for audio data, it may not
3472  * be otherwise. Sub-classes implementing such formats should disable
3473  * timestamp infering.
3474  */
3475 void
3476 gst_base_parse_set_infer_ts (GstBaseParse * parse, gboolean infer_ts)
3477 {
3478   parse->priv->infer_ts = infer_ts;
3479   GST_INFO_OBJECT (parse, "TS infering: %s", (infer_ts) ? "yes" : "no");
3480 }
3481
3482 /**
3483  * gst_base_parse_set_latency:
3484  * @parse: a #GstBaseParse
3485  * @min_latency: minimum parse latency
3486  * @max_latency: maximum parse latency
3487  *
3488  * Sets the minimum and maximum (which may likely be equal) latency introduced
3489  * by the parsing process.  If there is such a latency, which depends on the
3490  * particular parsing of the format, it typically corresponds to 1 frame duration.
3491  */
3492 void
3493 gst_base_parse_set_latency (GstBaseParse * parse, GstClockTime min_latency,
3494     GstClockTime max_latency)
3495 {
3496   GST_OBJECT_LOCK (parse);
3497   parse->priv->min_latency = min_latency;
3498   parse->priv->max_latency = max_latency;
3499   GST_OBJECT_UNLOCK (parse);
3500   GST_INFO_OBJECT (parse, "min/max latency %" GST_TIME_FORMAT ", %"
3501       GST_TIME_FORMAT, GST_TIME_ARGS (min_latency),
3502       GST_TIME_ARGS (max_latency));
3503 }
3504
3505 static gboolean
3506 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
3507     GstClockTime * duration)
3508 {
3509   gboolean res = FALSE;
3510
3511   g_return_val_if_fail (duration != NULL, FALSE);
3512
3513   *duration = GST_CLOCK_TIME_NONE;
3514   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
3515     GST_LOG_OBJECT (parse, "using provided duration");
3516     *duration = parse->priv->duration;
3517     res = TRUE;
3518   } else if (parse->priv->duration != -1) {
3519     GST_LOG_OBJECT (parse, "converting provided duration");
3520     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
3521         parse->priv->duration, format, (gint64 *) duration);
3522   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
3523     GST_LOG_OBJECT (parse, "using estimated duration");
3524     *duration = parse->priv->estimated_duration;
3525     res = TRUE;
3526   } else {
3527     GST_LOG_OBJECT (parse, "cannot estimate duration");
3528   }
3529
3530   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
3531       GST_TIME_ARGS (*duration));
3532   return res;
3533 }
3534
3535 static gboolean
3536 gst_base_parse_src_query_default (GstBaseParse * parse, GstQuery * query)
3537 {
3538   gboolean res = FALSE;
3539   GstPad *pad;
3540
3541   pad = GST_BASE_PARSE_SRC_PAD (parse);
3542
3543   switch (GST_QUERY_TYPE (query)) {
3544     case GST_QUERY_POSITION:
3545     {
3546       gint64 dest_value;
3547       GstFormat format;
3548
3549       GST_DEBUG_OBJECT (parse, "position query");
3550       gst_query_parse_position (query, &format, NULL);
3551
3552       /* try upstream first */
3553       res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3554       if (!res) {
3555         /* Fall back on interpreting segment */
3556         GST_OBJECT_LOCK (parse);
3557         if (format == GST_FORMAT_BYTES) {
3558           dest_value = parse->priv->offset;
3559           res = TRUE;
3560         } else if (format == parse->segment.format &&
3561             GST_CLOCK_TIME_IS_VALID (parse->segment.position)) {
3562           dest_value = gst_segment_to_stream_time (&parse->segment,
3563               parse->segment.format, parse->segment.position);
3564           res = TRUE;
3565         }
3566         GST_OBJECT_UNLOCK (parse);
3567         if (!res) {
3568           /* no precise result, upstream no idea either, then best estimate */
3569           /* priv->offset is updated in both PUSH/PULL modes */
3570           res = gst_base_parse_convert (parse,
3571               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
3572         }
3573         if (res)
3574           gst_query_set_position (query, format, dest_value);
3575       }
3576       break;
3577     }
3578     case GST_QUERY_DURATION:
3579     {
3580       GstFormat format;
3581       GstClockTime duration;
3582
3583       GST_DEBUG_OBJECT (parse, "duration query");
3584       gst_query_parse_duration (query, &format, NULL);
3585
3586       /* consult upstream */
3587       res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3588
3589       /* otherwise best estimate from us */
3590       if (!res) {
3591         res = gst_base_parse_get_duration (parse, format, &duration);
3592         if (res)
3593           gst_query_set_duration (query, format, duration);
3594       }
3595       break;
3596     }
3597     case GST_QUERY_SEEKING:
3598     {
3599       GstFormat fmt;
3600       GstClockTime duration = GST_CLOCK_TIME_NONE;
3601       gboolean seekable = FALSE;
3602
3603       GST_DEBUG_OBJECT (parse, "seeking query");
3604       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
3605
3606       /* consult upstream */
3607       res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3608
3609       /* we may be able to help if in TIME */
3610       if (fmt == GST_FORMAT_TIME && gst_base_parse_is_seekable (parse)) {
3611         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
3612         /* already OK if upstream takes care */
3613         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
3614             res, seekable);
3615         if (!(res && seekable)) {
3616           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
3617               || duration == -1) {
3618             /* seekable if we still have a chance to get duration later on */
3619             seekable =
3620                 parse->priv->upstream_seekable && parse->priv->update_interval;
3621           } else {
3622             seekable = parse->priv->upstream_seekable;
3623             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
3624                 seekable);
3625           }
3626           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
3627           res = TRUE;
3628         }
3629       }
3630       break;
3631     }
3632     case GST_QUERY_FORMATS:
3633       gst_query_set_formatsv (query, 3, fmtlist);
3634       res = TRUE;
3635       break;
3636     case GST_QUERY_CONVERT:
3637     {
3638       GstFormat src_format, dest_format;
3639       gint64 src_value, dest_value;
3640
3641       gst_query_parse_convert (query, &src_format, &src_value,
3642           &dest_format, &dest_value);
3643
3644       res = gst_base_parse_convert (parse, src_format, src_value,
3645           dest_format, &dest_value);
3646       if (res) {
3647         gst_query_set_convert (query, src_format, src_value,
3648             dest_format, dest_value);
3649       }
3650       break;
3651     }
3652     case GST_QUERY_LATENCY:
3653     {
3654       if ((res = gst_pad_peer_query (parse->sinkpad, query))) {
3655         gboolean live;
3656         GstClockTime min_latency, max_latency;
3657
3658         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
3659         GST_DEBUG_OBJECT (parse, "Peer latency: live %d, min %"
3660             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
3661             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
3662
3663         GST_OBJECT_LOCK (parse);
3664         /* add our latency */
3665         if (min_latency != -1)
3666           min_latency += parse->priv->min_latency;
3667         if (max_latency != -1)
3668           max_latency += parse->priv->max_latency;
3669         GST_OBJECT_UNLOCK (parse);
3670
3671         gst_query_set_latency (query, live, min_latency, max_latency);
3672       }
3673       break;
3674     }
3675     default:
3676       res = gst_pad_query_default (pad, GST_OBJECT_CAST (parse), query);
3677       break;
3678   }
3679   return res;
3680 }
3681
3682 /* scans for a cluster start from @pos,
3683  * return GST_FLOW_OK and frame position/time in @pos/@time if found */
3684 static GstFlowReturn
3685 gst_base_parse_find_frame (GstBaseParse * parse, gint64 * pos,
3686     GstClockTime * time, GstClockTime * duration)
3687 {
3688   GstBaseParseClass *klass;
3689   gint64 orig_offset;
3690   gboolean orig_drain, orig_discont;
3691   GstFlowReturn ret = GST_FLOW_OK;
3692   GstBuffer *buf = NULL;
3693   GstBaseParseFrame *sframe = NULL;
3694
3695   g_return_val_if_fail (pos != NULL, GST_FLOW_ERROR);
3696   g_return_val_if_fail (time != NULL, GST_FLOW_ERROR);
3697   g_return_val_if_fail (duration != NULL, GST_FLOW_ERROR);
3698
3699   klass = GST_BASE_PARSE_GET_CLASS (parse);
3700
3701   *time = GST_CLOCK_TIME_NONE;
3702   *duration = GST_CLOCK_TIME_NONE;
3703
3704   /* save state */
3705   orig_offset = parse->priv->offset;
3706   orig_discont = parse->priv->discont;
3707   orig_drain = parse->priv->drain;
3708
3709   GST_DEBUG_OBJECT (parse, "scanning for frame starting at %" G_GINT64_FORMAT
3710       " (%#" G_GINT64_MODIFIER "x)", *pos, *pos);
3711
3712   /* jump elsewhere and locate next frame */
3713   parse->priv->offset = *pos;
3714   /* mark as scanning so frames don't get processed all the way */
3715   parse->priv->scanning = TRUE;
3716   ret = gst_base_parse_scan_frame (parse, klass);
3717   parse->priv->scanning = FALSE;
3718   /* retrieve frame found during scan */
3719   sframe = parse->priv->scanned_frame;
3720   parse->priv->scanned_frame = NULL;
3721
3722   if (ret != GST_FLOW_OK || !sframe)
3723     goto done;
3724
3725   /* get offset first, subclass parsing might dump other stuff in there */
3726   *pos = sframe->offset;
3727   buf = sframe->buffer;
3728   g_assert (buf);
3729
3730   /* but it should provide proper time */
3731   *time = GST_BUFFER_TIMESTAMP (buf);
3732   *duration = GST_BUFFER_DURATION (buf);
3733
3734   GST_LOG_OBJECT (parse,
3735       "frame with time %" GST_TIME_FORMAT " at offset %" G_GINT64_FORMAT,
3736       GST_TIME_ARGS (*time), *pos);
3737
3738 done:
3739   if (sframe)
3740     gst_base_parse_frame_free (sframe);
3741
3742   /* restore state */
3743   parse->priv->offset = orig_offset;
3744   parse->priv->discont = orig_discont;
3745   parse->priv->drain = orig_drain;
3746
3747   return ret;
3748 }
3749
3750 /* bisect and scan through file for frame starting before @time,
3751  * returns OK and @time/@offset if found, NONE and/or error otherwise
3752  * If @time == G_MAXINT64, scan for duration ( == last frame) */
3753 static GstFlowReturn
3754 gst_base_parse_locate_time (GstBaseParse * parse, GstClockTime * _time,
3755     gint64 * _offset)
3756 {
3757   GstFlowReturn ret = GST_FLOW_OK;
3758   gint64 lpos, hpos, newpos;
3759   GstClockTime time, ltime, htime, newtime, dur;
3760   gboolean cont = TRUE;
3761   const GstClockTime tolerance = TARGET_DIFFERENCE;
3762   const guint chunk = 4 * 1024;
3763
3764   g_return_val_if_fail (_time != NULL, GST_FLOW_ERROR);
3765   g_return_val_if_fail (_offset != NULL, GST_FLOW_ERROR);
3766
3767   GST_DEBUG_OBJECT (parse, "Bisecting for time %" GST_TIME_FORMAT,
3768       GST_TIME_ARGS (*_time));
3769
3770   /* TODO also make keyframe aware if useful some day */
3771
3772   time = *_time;
3773
3774   /* basic cases */
3775   if (time == 0) {
3776     *_offset = 0;
3777     return GST_FLOW_OK;
3778   }
3779
3780   if (time == -1) {
3781     *_offset = -1;
3782     return GST_FLOW_OK;
3783   }
3784
3785   /* do not know at first */
3786   *_offset = -1;
3787   *_time = GST_CLOCK_TIME_NONE;
3788
3789   /* need initial positions; start and end */
3790   lpos = parse->priv->first_frame_offset;
3791   ltime = parse->priv->first_frame_pts;
3792   if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &htime)) {
3793     GST_DEBUG_OBJECT (parse, "Unknown time duration, cannot bisect");
3794     return GST_FLOW_ERROR;
3795   }
3796   hpos = parse->priv->upstream_size;
3797
3798   GST_DEBUG_OBJECT (parse,
3799       "Bisection initial bounds: bytes %" G_GINT64_FORMAT " %" G_GINT64_FORMAT
3800       ", times %" GST_TIME_FORMAT " %" GST_TIME_FORMAT, lpos, htime,
3801       GST_TIME_ARGS (ltime), GST_TIME_ARGS (htime));
3802
3803   /* check preconditions are satisfied;
3804    * start and end are needed, except for special case where we scan for
3805    * last frame to determine duration */
3806   if (parse->priv->pad_mode != GST_PAD_MODE_PULL || !hpos ||
3807       !GST_CLOCK_TIME_IS_VALID (ltime) ||
3808       (!GST_CLOCK_TIME_IS_VALID (htime) && time != G_MAXINT64)) {
3809     return GST_FLOW_OK;
3810   }
3811
3812   /* shortcut cases */
3813   if (time < ltime) {
3814     goto exit;
3815   } else if (time < ltime + tolerance) {
3816     *_offset = lpos;
3817     *_time = ltime;
3818     goto exit;
3819   } else if (time >= htime) {
3820     *_offset = hpos;
3821     *_time = htime;
3822     goto exit;
3823   }
3824
3825   while (htime > ltime && cont) {
3826     GST_LOG_OBJECT (parse,
3827         "lpos: %" G_GUINT64_FORMAT ", ltime: %" GST_TIME_FORMAT, lpos,
3828         GST_TIME_ARGS (ltime));
3829     GST_LOG_OBJECT (parse,
3830         "hpos: %" G_GUINT64_FORMAT ", htime: %" GST_TIME_FORMAT, hpos,
3831         GST_TIME_ARGS (htime));
3832     if (G_UNLIKELY (time == G_MAXINT64)) {
3833       newpos = hpos;
3834     } else if (G_LIKELY (hpos > lpos)) {
3835       newpos =
3836           gst_util_uint64_scale (hpos - lpos, time - ltime, htime - ltime) +
3837           lpos - chunk;
3838     } else {
3839       /* should mean lpos == hpos, since lpos <= hpos is invariant */
3840       newpos = lpos;
3841       /* we check this case once, but not forever, so break loop */
3842       cont = FALSE;
3843     }
3844
3845     /* ensure */
3846     newpos = CLAMP (newpos, lpos, hpos);
3847     GST_LOG_OBJECT (parse,
3848         "estimated _offset for %" GST_TIME_FORMAT ": %" G_GINT64_FORMAT,
3849         GST_TIME_ARGS (time), newpos);
3850
3851     ret = gst_base_parse_find_frame (parse, &newpos, &newtime, &dur);
3852     if (ret == GST_FLOW_EOS) {
3853       /* heuristic HACK */
3854       hpos = MAX (lpos, hpos - chunk);
3855       continue;
3856     } else if (ret != GST_FLOW_OK) {
3857       goto exit;
3858     }
3859
3860     if (newtime == -1 || newpos == -1) {
3861       GST_DEBUG_OBJECT (parse, "subclass did not provide metadata; aborting");
3862       break;
3863     }
3864
3865     if (G_UNLIKELY (time == G_MAXINT64)) {
3866       *_offset = newpos;
3867       *_time = newtime;
3868       if (GST_CLOCK_TIME_IS_VALID (dur))
3869         *_time += dur;
3870       break;
3871     } else if (newtime > time) {
3872       /* overshoot */
3873       hpos = (newpos >= hpos) ? MAX (lpos, hpos - chunk) : MAX (lpos, newpos);
3874       htime = newtime;
3875     } else if (newtime + tolerance > time) {
3876       /* close enough undershoot */
3877       *_offset = newpos;
3878       *_time = newtime;
3879       break;
3880     } else if (newtime < ltime) {
3881       /* so a position beyond lpos resulted in earlier time than ltime ... */
3882       GST_DEBUG_OBJECT (parse, "non-ascending time; aborting");
3883       break;
3884     } else {
3885       /* undershoot too far */
3886       newpos += newpos == lpos ? chunk : 0;
3887       lpos = CLAMP (newpos, lpos, hpos);
3888       ltime = newtime;
3889     }
3890   }
3891
3892 exit:
3893   GST_LOG_OBJECT (parse, "return offset %" G_GINT64_FORMAT ", time %"
3894       GST_TIME_FORMAT, *_offset, GST_TIME_ARGS (*_time));
3895   return ret;
3896 }
3897
3898 static gint64
3899 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
3900     gboolean before, GstClockTime * _ts)
3901 {
3902   gint64 bytes = 0, ts = 0;
3903   GstIndexEntry *entry = NULL;
3904
3905   if (time == GST_CLOCK_TIME_NONE) {
3906     ts = time;
3907     bytes = -1;
3908     goto exit;
3909   }
3910
3911   GST_BASE_PARSE_INDEX_LOCK (parse);
3912   if (parse->priv->index) {
3913     /* Let's check if we have an index entry for that time */
3914     entry = gst_index_get_assoc_entry (parse->priv->index,
3915         parse->priv->index_id,
3916         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
3917         GST_INDEX_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
3918   }
3919
3920   if (entry) {
3921     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
3922     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
3923
3924     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
3925         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
3926         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
3927   } else {
3928     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
3929         GST_TIME_ARGS (time));
3930     if (!before) {
3931       bytes = -1;
3932       ts = GST_CLOCK_TIME_NONE;
3933     }
3934   }
3935   GST_BASE_PARSE_INDEX_UNLOCK (parse);
3936
3937 exit:
3938   if (_ts)
3939     *_ts = ts;
3940
3941   return bytes;
3942 }
3943
3944 /* returns TRUE if seek succeeded */
3945 static gboolean
3946 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
3947 {
3948   gdouble rate;
3949   GstFormat format;
3950   GstSeekFlags flags;
3951   GstSeekType start_type = GST_SEEK_TYPE_NONE, stop_type;
3952   gboolean flush, update, res = TRUE, accurate;
3953   gint64 start, stop, seekpos, seekstop;
3954   GstSegment seeksegment = { 0, };
3955   GstClockTime start_ts;
3956
3957   /* try upstream first, unless we're driving the streaming thread ourselves */
3958   if (parse->priv->pad_mode != GST_PAD_MODE_PULL) {
3959     res = gst_pad_push_event (parse->sinkpad, gst_event_ref (event));
3960     if (res)
3961       goto done;
3962   }
3963
3964   gst_event_parse_seek (event, &rate, &format, &flags,
3965       &start_type, &start, &stop_type, &stop);
3966
3967   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
3968       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
3969       GST_TIME_FORMAT, gst_format_get_name (format), rate,
3970       start_type, GST_TIME_ARGS (start), stop_type, GST_TIME_ARGS (stop));
3971
3972   /* we can only handle TIME, so check if subclass can convert
3973    * to TIME format if it's some other format (such as DEFAULT) */
3974   if (format != GST_FORMAT_TIME) {
3975     if (!gst_base_parse_convert (parse, format, start, GST_FORMAT_TIME, &start)
3976         || !gst_base_parse_convert (parse, format, stop, GST_FORMAT_TIME,
3977             &stop))
3978       goto no_convert_to_time;
3979
3980     GST_INFO_OBJECT (parse, "converted %s format to start time "
3981         "%" GST_TIME_FORMAT " and stop time %" GST_TIME_FORMAT,
3982         gst_format_get_name (format), GST_TIME_ARGS (start),
3983         GST_TIME_ARGS (stop));
3984
3985     format = GST_FORMAT_TIME;
3986   }
3987
3988   /* no negative rates in push mode (unless upstream takes care of that, but
3989    * we've already tried upstream and it didn't handle the seek request) */
3990   if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PUSH)
3991     goto negative_rate;
3992
3993   if (rate < 0.0 && parse->priv->pad_mode == GST_PAD_MODE_PULL)
3994     goto negative_rate_pull_mode;
3995
3996   if (start_type != GST_SEEK_TYPE_SET ||
3997       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
3998     goto wrong_type;
3999
4000   /* get flush flag */
4001   flush = flags & GST_SEEK_FLAG_FLUSH;
4002
4003   /* copy segment, we need this because we still need the old
4004    * segment when we close the current segment. */
4005   gst_segment_copy_into (&parse->segment, &seeksegment);
4006
4007   GST_DEBUG_OBJECT (parse, "configuring seek");
4008   gst_segment_do_seek (&seeksegment, rate, format, flags,
4009       start_type, start, stop_type, stop, &update);
4010
4011   /* accurate seeking implies seek tables are used to obtain position,
4012    * and the requested segment is maintained exactly, not adjusted any way */
4013   accurate = flags & GST_SEEK_FLAG_ACCURATE;
4014
4015   /* maybe we can be accurate for (almost) free */
4016   gst_base_parse_find_offset (parse, seeksegment.position, TRUE, &start_ts);
4017   if (seeksegment.position <= start_ts + TARGET_DIFFERENCE) {
4018     GST_DEBUG_OBJECT (parse, "accurate seek possible");
4019     accurate = TRUE;
4020   }
4021   if (accurate) {
4022     GstClockTime startpos = seeksegment.position;
4023
4024     /* accurate requested, so ... seek a bit before target */
4025     if (startpos < parse->priv->lead_in_ts)
4026       startpos = 0;
4027     else
4028       startpos -= parse->priv->lead_in_ts;
4029     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
4030     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
4031         NULL);
4032   } else {
4033     start_ts = seeksegment.position;
4034     if (!gst_base_parse_convert (parse, format, seeksegment.position,
4035             GST_FORMAT_BYTES, &seekpos))
4036       goto convert_failed;
4037     if (!gst_base_parse_convert (parse, format, seeksegment.stop,
4038             GST_FORMAT_BYTES, &seekstop))
4039       goto convert_failed;
4040   }
4041
4042   GST_DEBUG_OBJECT (parse,
4043       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4044       start_ts, seekpos);
4045   GST_DEBUG_OBJECT (parse,
4046       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
4047       seeksegment.stop, seekstop);
4048
4049   if (parse->priv->pad_mode == GST_PAD_MODE_PULL) {
4050     gint64 last_stop;
4051
4052     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
4053
4054     if (flush) {
4055       if (parse->srcpad) {
4056         GST_DEBUG_OBJECT (parse, "sending flush start");
4057         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
4058         /* unlock upstream pull_range */
4059         gst_pad_push_event (parse->sinkpad, gst_event_new_flush_start ());
4060       }
4061     } else {
4062       gst_pad_pause_task (parse->sinkpad);
4063     }
4064
4065     /* we should now be able to grab the streaming thread because we stopped it
4066      * with the above flush/pause code */
4067     GST_PAD_STREAM_LOCK (parse->sinkpad);
4068
4069     /* save current position */
4070     last_stop = parse->segment.position;
4071     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
4072         last_stop);
4073
4074     /* now commit to new position */
4075
4076     /* prepare for streaming again */
4077     if (flush) {
4078       GST_DEBUG_OBJECT (parse, "sending flush stop");
4079       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop (TRUE));
4080       gst_pad_push_event (parse->sinkpad, gst_event_new_flush_stop (TRUE));
4081       gst_base_parse_clear_queues (parse);
4082     } else {
4083       /* keep track of our position */
4084       seeksegment.base = gst_segment_to_running_time (&seeksegment,
4085           seeksegment.format, parse->segment.position);
4086     }
4087
4088     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
4089
4090     /* store the newsegment event so it can be sent from the streaming thread. */
4091     /* This will be sent later in _loop() */
4092     parse->priv->pending_segment = TRUE;
4093     parse->priv->pending_events =
4094         g_list_prepend (parse->priv->pending_events,
4095         gst_event_new_segment (&parse->segment));
4096
4097     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
4098         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
4099         ", time = %" GST_TIME_FORMAT, format,
4100         GST_TIME_ARGS (parse->segment.start),
4101         GST_TIME_ARGS (parse->segment.stop),
4102         GST_TIME_ARGS (parse->segment.time));
4103
4104     /* one last chance in pull mode to stay accurate;
4105      * maybe scan and subclass can find where to go */
4106     if (!accurate) {
4107       gint64 scanpos;
4108       GstClockTime ts = seeksegment.position;
4109
4110       gst_base_parse_locate_time (parse, &ts, &scanpos);
4111       if (scanpos >= 0) {
4112         accurate = TRUE;
4113         seekpos = scanpos;
4114         /* running collected index now consists of several intervals,
4115          * so optimized check no longer possible */
4116         parse->priv->index_last_valid = FALSE;
4117         parse->priv->index_last_offset = 0;
4118         parse->priv->index_last_ts = 0;
4119       }
4120     }
4121
4122     /* mark discont if we are going to stream from another position. */
4123     if (seekpos != parse->priv->offset) {
4124       GST_DEBUG_OBJECT (parse,
4125           "mark DISCONT, we did a seek to another position");
4126       parse->priv->offset = seekpos;
4127       parse->priv->last_offset = seekpos;
4128       parse->priv->seen_keyframe = FALSE;
4129       parse->priv->discont = TRUE;
4130       parse->priv->next_dts = start_ts;
4131       parse->priv->last_dts = GST_CLOCK_TIME_NONE;
4132       parse->priv->last_pts = GST_CLOCK_TIME_NONE;
4133       parse->priv->sync_offset = seekpos;
4134       parse->priv->exact_position = accurate;
4135     }
4136
4137     /* Start streaming thread if paused */
4138     gst_pad_start_task (parse->sinkpad,
4139         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad, NULL);
4140
4141     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
4142
4143     /* handled seek */
4144     res = TRUE;
4145   } else {
4146     GstEvent *new_event;
4147     GstBaseParseSeek *seek;
4148     GstSeekFlags flags = (flush ? GST_SEEK_FLAG_FLUSH : GST_SEEK_FLAG_NONE);
4149
4150     /* The only thing we need to do in PUSH-mode is to send the
4151        seek event (in bytes) to upstream. Segment / flush handling happens
4152        in corresponding src event handlers */
4153     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
4154     if (seekstop >= 0 && seekstop <= seekpos)
4155       seekstop = seekpos;
4156     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flags,
4157         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
4158
4159     /* store segment info so its precise details can be reconstructed when
4160      * receiving newsegment;
4161      * this matters for all details when accurate seeking,
4162      * is most useful to preserve NONE stop time otherwise */
4163     seek = g_new0 (GstBaseParseSeek, 1);
4164     seek->segment = seeksegment;
4165     seek->accurate = accurate;
4166     seek->offset = seekpos;
4167     seek->start_ts = start_ts;
4168     GST_OBJECT_LOCK (parse);
4169     /* less optimal, but preserves order */
4170     parse->priv->pending_seeks =
4171         g_slist_append (parse->priv->pending_seeks, seek);
4172     GST_OBJECT_UNLOCK (parse);
4173
4174     res = gst_pad_push_event (parse->sinkpad, new_event);
4175
4176     if (!res) {
4177       GST_OBJECT_LOCK (parse);
4178       parse->priv->pending_seeks =
4179           g_slist_remove (parse->priv->pending_seeks, seek);
4180       GST_OBJECT_UNLOCK (parse);
4181       g_free (seek);
4182     }
4183   }
4184
4185 done:
4186   gst_event_unref (event);
4187   return res;
4188
4189   /* ERRORS */
4190 negative_rate_pull_mode:
4191   {
4192     GST_FIXME_OBJECT (parse, "negative playback in pull mode needs fixing");
4193     res = FALSE;
4194     goto done;
4195   }
4196 negative_rate:
4197   {
4198     GST_DEBUG_OBJECT (parse, "negative playback rates delegated upstream.");
4199     res = FALSE;
4200     goto done;
4201   }
4202 wrong_type:
4203   {
4204     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
4205     res = FALSE;
4206     goto done;
4207   }
4208 no_convert_to_time:
4209   {
4210     GST_DEBUG_OBJECT (parse, "seek in %s format was requested, but subclass "
4211         "couldn't convert that into TIME format", gst_format_get_name (format));
4212     res = FALSE;
4213     goto done;
4214   }
4215 convert_failed:
4216   {
4217     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
4218     res = FALSE;
4219     goto done;
4220   }
4221 }
4222
4223 /* Checks if bitrates are available from upstream tags so that we don't
4224  * override them later
4225  */
4226 static void
4227 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
4228 {
4229   GstTagList *taglist = NULL;
4230   guint tmp;
4231
4232   gst_event_parse_tag (event, &taglist);
4233
4234   /* We only care about stream tags here */
4235   if (gst_tag_list_get_scope (taglist) != GST_TAG_SCOPE_STREAM)
4236     return;
4237
4238   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp)) {
4239     GST_DEBUG_OBJECT (parse, "upstream min bitrate %d", tmp);
4240     parse->priv->post_min_bitrate = FALSE;
4241   }
4242   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp)) {
4243     GST_DEBUG_OBJECT (parse, "upstream avg bitrate %d", tmp);
4244     parse->priv->post_avg_bitrate = FALSE;
4245   }
4246   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp)) {
4247     GST_DEBUG_OBJECT (parse, "upstream max bitrate %d", tmp);
4248     parse->priv->post_max_bitrate = FALSE;
4249   }
4250 }
4251
4252 #if 0
4253 static void
4254 gst_base_parse_set_index (GstElement * element, GstIndex * index)
4255 {
4256   GstBaseParse *parse = GST_BASE_PARSE (element);
4257
4258   GST_BASE_PARSE_INDEX_LOCK (parse);
4259   if (parse->priv->index)
4260     gst_object_unref (parse->priv->index);
4261   if (index) {
4262     parse->priv->index = gst_object_ref (index);
4263     gst_index_get_writer_id (index, GST_OBJECT_CAST (element),
4264         &parse->priv->index_id);
4265     parse->priv->own_index = FALSE;
4266   } else {
4267     parse->priv->index = NULL;
4268   }
4269   GST_BASE_PARSE_INDEX_UNLOCK (parse);
4270 }
4271
4272 static GstIndex *
4273 gst_base_parse_get_index (GstElement * element)
4274 {
4275   GstBaseParse *parse = GST_BASE_PARSE (element);
4276   GstIndex *result = NULL;
4277
4278   GST_BASE_PARSE_INDEX_LOCK (parse);
4279   if (parse->priv->index)
4280     result = gst_object_ref (parse->priv->index);
4281   GST_BASE_PARSE_INDEX_UNLOCK (parse);
4282
4283   return result;
4284 }
4285 #endif
4286
4287 static GstStateChangeReturn
4288 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
4289 {
4290   GstBaseParse *parse;
4291   GstStateChangeReturn result;
4292
4293   parse = GST_BASE_PARSE (element);
4294
4295   switch (transition) {
4296     case GST_STATE_CHANGE_READY_TO_PAUSED:
4297       /* If this is our own index destroy it as the
4298        * old entries might be wrong for the new stream */
4299       GST_BASE_PARSE_INDEX_LOCK (parse);
4300       if (parse->priv->own_index) {
4301         gst_object_unref (parse->priv->index);
4302         parse->priv->index = NULL;
4303         parse->priv->own_index = FALSE;
4304       }
4305
4306       /* If no index was created, generate one */
4307       if (G_UNLIKELY (!parse->priv->index)) {
4308         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
4309
4310         parse->priv->index = g_object_new (gst_mem_index_get_type (), NULL);
4311         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
4312             &parse->priv->index_id);
4313         parse->priv->own_index = TRUE;
4314       }
4315       GST_BASE_PARSE_INDEX_UNLOCK (parse);
4316       break;
4317     default:
4318       break;
4319   }
4320
4321   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
4322
4323   switch (transition) {
4324     case GST_STATE_CHANGE_PAUSED_TO_READY:
4325       gst_base_parse_reset (parse);
4326       break;
4327     default:
4328       break;
4329   }
4330
4331   return result;
4332 }
4333
4334 /**
4335  * gst_base_parse_set_ts_at_offset:
4336  * @parse: a #GstBaseParse
4337  * @offset: offset into current buffer
4338  *
4339  * This function should only be called from a @handle_frame implementation.
4340  *
4341  * GstBaseParse creates initial timestamps for frames by using the last
4342  * timestamp seen in the stream before the frame starts.  In certain
4343  * cases, the correct timestamps will occur in the stream after the
4344  * start of the frame, but before the start of the actual picture data.
4345  * This function can be used to set the timestamps based on the offset
4346  * into the frame data that the picture starts.
4347  *
4348  * Since: 1.2
4349  */
4350 void
4351 gst_base_parse_set_ts_at_offset (GstBaseParse * parse, gsize offset)
4352 {
4353   GstClockTime pts, dts;
4354
4355   g_return_if_fail (GST_IS_BASE_PARSE (parse));
4356   g_return_if_fail (offset >= 0);
4357
4358   pts = gst_adapter_prev_pts_at_offset (parse->priv->adapter, offset, NULL);
4359   dts = gst_adapter_prev_dts_at_offset (parse->priv->adapter, offset, NULL);
4360
4361   if (!GST_CLOCK_TIME_IS_VALID (pts) || !GST_CLOCK_TIME_IS_VALID (dts)) {
4362     GST_DEBUG_OBJECT (parse,
4363         "offset adapter timestamps dts=%" GST_TIME_FORMAT " pts=%"
4364         GST_TIME_FORMAT, GST_TIME_ARGS (dts), GST_TIME_ARGS (pts));
4365   }
4366   if (GST_CLOCK_TIME_IS_VALID (pts) && (parse->priv->prev_pts != pts))
4367     parse->priv->prev_pts = parse->priv->next_pts = pts;
4368
4369   if (GST_CLOCK_TIME_IS_VALID (dts) && (parse->priv->prev_dts != dts))
4370     parse->priv->prev_dts = parse->priv->next_dts = dts;
4371 }