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