Revert "baseparse: add skip property"
[platform/upstream/gstreamer.git] / gst / audioparsers / 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  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gstbaseparse
24  * @short_description: Base class for stream parsers
25  * @see_also: #GstBaseTransform
26  *
27  * This base class is for parser elements that process data and splits it 
28  * into separate audio/video/whatever frames.
29  *
30  * It provides for:
31  * <itemizedlist>
32  *   <listitem><para>One sinkpad and one srcpad</para></listitem>
33  *   <listitem><para>Handles state changes</para></listitem>
34  *   <listitem><para>Does flushing</para></listitem>
35  *   <listitem><para>Push mode</para></listitem>
36  *   <listitem><para>Pull mode</para></listitem>
37  *   <listitem><para>Handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
38  *   <listitem><para>Handles seeking in both modes</para></listitem>
39  *   <listitem><para>
40  *        Handles POSITION/DURATION/SEEKING/FORMAT/CONVERT queries
41  *   </para></listitem>
42  * </itemizedlist>
43  *
44  * The purpose of this base class is to provide a basic functionality of
45  * a parser and share a lot of rather complex code.
46  *
47  * Description of the parsing mechanism:
48  * <orderedlist>
49  * <listitem>
50  *   <itemizedlist><title>Set-up phase</title>
51  *   <listitem><para>
52  *     GstBaseParse class calls @set_sink_caps to inform the subclass about
53  *     incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
54  *   </para></listitem>
55  *   <listitem><para>
56  *     GstBaseParse calls @start to inform subclass that data processing is
57  *     about to start now.
58  *   </para></listitem>
59  *   <listitem><para>
60  *      At least in this point subclass needs to tell the GstBaseParse class
61  *      how big data chunks it wants to receive (min_frame_size). It can do 
62  *      this with @gst_base_parse_set_min_frame_size.
63  *   </para></listitem>
64  *   <listitem><para>
65  *      GstBaseParse class sets up appropriate data passing mode (pull/push)
66  *      and starts to process the data.
67  *   </para></listitem>
68  *   </itemizedlist>
69  * </listitem>
70  * <listitem>
71  *   <itemizedlist>
72  *   <title>Parsing phase</title>
73  *     <listitem><para>
74  *       GstBaseParse gathers at least min_frame_size bytes of data either 
75  *       by pulling it from upstream or collecting buffers into internal
76  *       #GstAdapter.
77  *     </para></listitem>
78  *     <listitem><para>
79  *       A buffer of min_frame_size bytes is passed to subclass with
80  *       @check_valid_frame. Subclass checks the contents and returns TRUE
81  *       if the buffer contains a valid frame. It also needs to set the
82  *       @framesize according to the detected frame size. If buffer didn't
83  *       contain a valid frame, this call must return FALSE and optionally
84  *       set the @skipsize value to inform base class that how many bytes
85  *       it needs to skip in order to find a valid frame. The passed buffer
86  *       is read-only.  Note that @check_valid_frame might receive any small
87  *       amount of input data when leftover data is being drained (e.g. at EOS).
88  *     </para></listitem>
89  *     <listitem><para>
90  *       After valid frame is found, it will be passed again to subclass with
91  *       @parse_frame call. Now subclass is responsible for parsing the
92  *       frame contents and setting the caps, buffer timestamp and duration
93  *       (although the latter can also be done by GstBaseParse if it is
94  *       appropriately configured, see below).
95  *     </para></listitem>
96  *     <listitem><para>
97  *       Finally the buffer can be pushed downstream and parsing loop starts
98  *       over again.  Just prior to actually pushing the buffer in question,
99  *       it is passed to @pre_push_buffer which gives subclass yet one
100  *       last chance to examine buffer metadata, or to send some custom (tag)
101  *       events, or to perform custom (segment) filtering.
102  *     </para></listitem>
103  *     <listitem><para>
104  *       During the parsing process GstBaseParseClass will handle both srcpad and
105  *       sinkpad events. They will be passed to subclass if @event or
106  *       @src_event callbacks have been provided.
107  *     </para></listitem>
108  *   </itemizedlist>
109  * </listitem>
110  * <listitem>
111  *   <itemizedlist><title>Shutdown phase</title>
112  *   <listitem><para>
113  *     GstBaseParse class calls @stop to inform the subclass that data
114  *     parsing will be stopped.
115  *   </para></listitem>
116  *   </itemizedlist>
117  * </listitem>
118  * </orderedlist>
119  *
120  * Subclass is responsible for providing pad template caps for
121  * source and sink pads. The pads need to be named "sink" and "src". It also 
122  * needs to set the fixed caps on srcpad, when the format is ensured (e.g. 
123  * when base class calls subclass' @set_sink_caps function).
124  *
125  * This base class uses GST_FORMAT_DEFAULT as a meaning of frames. So,
126  * subclass conversion routine needs to know that conversion from
127  * GST_FORMAT_TIME to GST_FORMAT_DEFAULT must return the
128  * frame number that can be found from the given byte position.
129  *
130  * GstBaseParse uses subclasses conversion methods also for seeking (or otherwise
131  * uses its own default one, see also below).
132  *
133  * Subclass @start and @stop functions will be called to inform the beginning
134  * and end of data processing.
135  *
136  * Things that subclass need to take care of:
137  * <itemizedlist>
138  *   <listitem><para>Provide pad templates</para></listitem>
139  *   <listitem><para>
140  *      Fixate the source pad caps when appropriate
141  *   </para></listitem>
142  *   <listitem><para>
143  *      Inform base class how big data chunks should be retrieved. This is
144  *      done with @gst_base_parse_set_min_frame_size function.
145  *   </para></listitem>
146  *   <listitem><para>
147  *      Examine data chunks passed to subclass with @check_valid_frame
148  *      and tell if they contain a valid frame
149  *   </para></listitem>
150  *   <listitem><para>
151  *      Set the caps and timestamp to frame that is passed to subclass with
152  *      @parse_frame function.
153  *   </para></listitem>
154  *   <listitem><para>Provide conversion functions</para></listitem>
155  *   <listitem><para>
156  *      Update the duration information with @gst_base_parse_set_duration
157  *   </para></listitem>
158  *   <listitem><para>
159  *      Optionally passthrough using @gst_base_parse_set_passthrough
160  *   </para></listitem>
161  *   <listitem><para>
162  *      Configure various baseparse parameters using @gst_base_parse_set_seek and
163  *      @gst_base_parse_set_frame_props.
164  *   </para></listitem>
165  *   <listitem><para>
166  *      In particular, if subclass is unable to determine a duration, but
167  *      parsing (or specs) yields a frames per seconds rate, then this can be
168  *      provided to GstBaseParse to enable it to cater for
169  *      buffer time metadata (which will be taken from upstream as much as possible).
170  *      Internally keeping track of frame durations and respective
171  *      sizes that have been pushed provides GstBaseParse with an estimated bitrate.
172  *      A default @convert (used if not overriden) will then use these
173  *      rates to perform obvious conversions.  These rates are also used to update
174  *      (estimated) duration at regular frame intervals.
175  *   </para></listitem>
176  * </itemizedlist>
177  *
178  */
179
180 /* TODO:
181  *  - In push mode provide a queue of adapter-"queued" buffers for upstream
182  *    buffer metadata
183  *  - Queue buffers/events until caps are set
184  */
185
186 #ifdef HAVE_CONFIG_H
187 #  include "config.h"
188 #endif
189
190 #include <stdlib.h>
191 #include <string.h>
192
193 #include "gstbaseparse.h"
194
195 #define MIN_FRAMES_TO_POST_BITRATE 10
196
197 GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
198 #define GST_CAT_DEFAULT gst_base_parse_debug
199
200 /* Supported formats */
201 static GstFormat fmtlist[] = {
202   GST_FORMAT_DEFAULT,
203   GST_FORMAT_BYTES,
204   GST_FORMAT_TIME,
205   0
206 };
207
208 #define GST_BASE_PARSE_GET_PRIVATE(obj)  \
209     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))
210
211 struct _GstBaseParsePrivate
212 {
213   GstActivateMode pad_mode;
214
215   gint64 duration;
216   GstFormat duration_fmt;
217   gint64 estimated_duration;
218
219   guint min_frame_size;
220   gboolean passthrough;
221   guint fps_num, fps_den;
222   guint update_interval;
223   guint bitrate;
224   guint lead_in, lead_out;
225   GstClockTime lead_in_ts, lead_out_ts;
226   GstBaseParseSeekable seekable;
227
228   gboolean discont;
229   gboolean flushing;
230   gboolean drain;
231
232   gint64 offset;
233   gint64 sync_offset;
234   GstClockTime next_ts;
235   GstClockTime prev_ts;
236   GstClockTime frame_duration;
237
238   guint64 framecount;
239   guint64 bytecount;
240   guint64 data_bytecount;
241   guint64 acc_duration;
242
243   gboolean post_min_bitrate;
244   gboolean post_avg_bitrate;
245   gboolean post_max_bitrate;
246   guint min_bitrate;
247   guint avg_bitrate;
248   guint max_bitrate;
249   guint posted_avg_bitrate;
250
251   GList *pending_events;
252
253   GstBuffer *cache;
254
255   /* index entry storage, either ours or provided */
256   GstIndex *index;
257   gint index_id;
258   gboolean own_index;
259   /* seek table entries only maintained if upstream is BYTE seekable */
260   gboolean upstream_seekable;
261   /* minimum distance between two index entries */
262   GstClockTimeDiff idx_interval;
263   /* ts and offset of last entry added */
264   GstClockTime index_last_ts;
265   guint64 index_last_offset;
266
267   /* timestamps currently produced are accurate, e.g. started from 0 onwards */
268   gboolean exact_position;
269   /* seek events are temporarily kept to match them with newsegments */
270   GSList *pending_seeks;
271
272   /* reverse playback */
273   GSList *buffers_pending;
274   GSList *buffers_queued;
275   GstClockTime last_ts;
276   gint64 last_offset;
277 };
278
279 typedef struct _GstBaseParseSeek
280 {
281   GstSegment segment;
282   gboolean accurate;
283   gint64 offset;
284   GstClockTime start_ts;
285 } GstBaseParseSeek;
286
287 static GstElementClass *parent_class = NULL;
288
289 static void gst_base_parse_class_init (GstBaseParseClass * klass);
290 static void gst_base_parse_init (GstBaseParse * parse,
291     GstBaseParseClass * klass);
292
293 GType
294 gst_base_parse_get_type (void)
295 {
296   static GType base_parse_type = 0;
297
298   if (!base_parse_type) {
299     static const GTypeInfo base_parse_info = {
300       sizeof (GstBaseParseClass),
301       (GBaseInitFunc) NULL,
302       (GBaseFinalizeFunc) NULL,
303       (GClassInitFunc) gst_base_parse_class_init,
304       NULL,
305       NULL,
306       sizeof (GstBaseParse),
307       0,
308       (GInstanceInitFunc) gst_base_parse_init,
309     };
310
311     base_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
312         "GstAudioBaseParseBad", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
313   }
314   return base_parse_type;
315 }
316
317 static void gst_base_parse_finalize (GObject * object);
318
319 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
320     GstStateChange transition);
321 static void gst_base_parse_reset (GstBaseParse * parse);
322
323 static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
324 static GstIndex *gst_base_parse_get_index (GstElement * element);
325
326 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
327 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
328     gboolean active);
329 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
330     gboolean active);
331 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
332     GstEvent * event);
333 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
334
335 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
336 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
337 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
338 static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
339 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
340
341 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
342 static void gst_base_parse_loop (GstPad * pad);
343
344 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
345     GstBuffer * buffer, guint * framesize, gint * skipsize);
346
347 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
348     GstBuffer * buffer);
349
350 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
351     GstEvent * event);
352
353 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
354     GstEvent * event);
355
356 static void gst_base_parse_drain (GstBaseParse * parse);
357
358 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
359     gboolean post_min, gboolean post_avg, gboolean post_max);
360
361 static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
362     GstClockTime time, gboolean before, GstClockTime * _ts);
363
364 static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
365     gboolean push_only);
366
367 static void
368 gst_base_parse_clear_queues (GstBaseParse * parse)
369 {
370   g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
371   g_slist_free (parse->priv->buffers_queued);
372   parse->priv->buffers_queued = NULL;
373   g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
374       NULL);
375   g_slist_free (parse->priv->buffers_pending);
376   parse->priv->buffers_pending = NULL;
377 }
378
379 static void
380 gst_base_parse_finalize (GObject * object)
381 {
382   GstBaseParse *parse = GST_BASE_PARSE (object);
383   GstEvent **p_ev;
384
385   g_mutex_free (parse->parse_lock);
386   g_object_unref (parse->adapter);
387
388   if (parse->pending_segment) {
389     p_ev = &parse->pending_segment;
390     gst_event_replace (p_ev, NULL);
391   }
392   if (parse->close_segment) {
393     p_ev = &parse->close_segment;
394     gst_event_replace (p_ev, NULL);
395   }
396
397   if (parse->priv->cache) {
398     gst_buffer_unref (parse->priv->cache);
399     parse->priv->cache = NULL;
400   }
401
402   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
403       NULL);
404   g_list_free (parse->priv->pending_events);
405   parse->priv->pending_events = NULL;
406
407   if (parse->priv->index) {
408     gst_object_unref (parse->priv->index);
409     parse->priv->index = NULL;
410   }
411
412   gst_base_parse_clear_queues (parse);
413
414   G_OBJECT_CLASS (parent_class)->finalize (object);
415 }
416
417 static void
418 gst_base_parse_class_init (GstBaseParseClass * klass)
419 {
420   GObjectClass *gobject_class;
421   GstElementClass *gstelement_class;
422
423   gobject_class = G_OBJECT_CLASS (klass);
424   g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
425   parent_class = g_type_class_peek_parent (klass);
426   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
427
428   gstelement_class = (GstElementClass *) klass;
429   gstelement_class->change_state =
430       GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
431   gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
432   gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
433
434   /* Default handlers */
435   klass->check_valid_frame = gst_base_parse_check_frame;
436   klass->parse_frame = gst_base_parse_parse_frame;
437   klass->src_event = gst_base_parse_src_eventfunc;
438   klass->convert = gst_base_parse_convert_default;
439
440   GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
441       "baseparse element");
442 }
443
444 static void
445 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
446 {
447   GstPadTemplate *pad_template;
448
449   GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
450
451   parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
452
453   pad_template =
454       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
455   g_return_if_fail (pad_template != NULL);
456   parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
457   gst_pad_set_event_function (parse->sinkpad,
458       GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
459   gst_pad_set_setcaps_function (parse->sinkpad,
460       GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
461   gst_pad_set_chain_function (parse->sinkpad,
462       GST_DEBUG_FUNCPTR (gst_base_parse_chain));
463   gst_pad_set_activate_function (parse->sinkpad,
464       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
465   gst_pad_set_activatepush_function (parse->sinkpad,
466       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
467   gst_pad_set_activatepull_function (parse->sinkpad,
468       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
469   gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
470
471   GST_DEBUG_OBJECT (parse, "sinkpad created");
472
473   pad_template =
474       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
475   g_return_if_fail (pad_template != NULL);
476   parse->srcpad = gst_pad_new_from_template (pad_template, "src");
477   gst_pad_set_event_function (parse->srcpad,
478       GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
479   gst_pad_set_query_type_function (parse->srcpad,
480       GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
481   gst_pad_set_query_function (parse->srcpad,
482       GST_DEBUG_FUNCPTR (gst_base_parse_query));
483   gst_pad_use_fixed_caps (parse->srcpad);
484   gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
485   GST_DEBUG_OBJECT (parse, "src created");
486
487   parse->parse_lock = g_mutex_new ();
488   parse->adapter = gst_adapter_new ();
489
490   parse->priv->pad_mode = GST_ACTIVATE_NONE;
491
492   /* init state */
493   gst_base_parse_reset (parse);
494   GST_DEBUG_OBJECT (parse, "init ok");
495 }
496
497 static void
498 gst_base_parse_reset (GstBaseParse * parse)
499 {
500   GST_OBJECT_LOCK (parse);
501   gst_segment_init (&parse->segment, GST_FORMAT_TIME);
502   parse->priv->duration = -1;
503   parse->priv->min_frame_size = 1;
504   parse->priv->discont = TRUE;
505   parse->priv->flushing = FALSE;
506   parse->priv->offset = 0;
507   parse->priv->sync_offset = 0;
508   parse->priv->update_interval = 50;
509   parse->priv->fps_num = parse->priv->fps_den = 0;
510   parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
511   parse->priv->lead_in = parse->priv->lead_out = 0;
512   parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
513   parse->priv->seekable = GST_BASE_PARSE_SEEK_DEFAULT;
514   parse->priv->bitrate = 0;
515   parse->priv->framecount = 0;
516   parse->priv->bytecount = 0;
517   parse->priv->acc_duration = 0;
518   parse->priv->estimated_duration = -1;
519   parse->priv->next_ts = 0;
520   parse->priv->passthrough = FALSE;
521   parse->priv->post_min_bitrate = TRUE;
522   parse->priv->post_avg_bitrate = TRUE;
523   parse->priv->post_max_bitrate = TRUE;
524   parse->priv->min_bitrate = G_MAXUINT;
525   parse->priv->max_bitrate = 0;
526   parse->priv->avg_bitrate = 0;
527   parse->priv->posted_avg_bitrate = 0;
528
529   parse->priv->index_last_ts = 0;
530   parse->priv->index_last_offset = 0;
531   parse->priv->upstream_seekable = FALSE;
532   parse->priv->idx_interval = 0;
533   parse->priv->exact_position = TRUE;
534
535   parse->priv->last_ts = GST_CLOCK_TIME_NONE;
536   parse->priv->last_offset = 0;
537
538   if (parse->pending_segment)
539     gst_event_unref (parse->pending_segment);
540
541   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
542       NULL);
543   g_list_free (parse->priv->pending_events);
544   parse->priv->pending_events = NULL;
545
546   if (parse->priv->cache) {
547     gst_buffer_unref (parse->priv->cache);
548     parse->priv->cache = NULL;
549   }
550
551   g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
552   g_slist_free (parse->priv->pending_seeks);
553   parse->priv->pending_seeks = NULL;
554
555   GST_OBJECT_UNLOCK (parse);
556 }
557
558 /**
559  * gst_base_parse_check_frame:
560  * @parse: #GstBaseParse.
561  * @buffer: GstBuffer.
562  * @framesize: This will be set to tell the found frame size in bytes.
563  * @skipsize: Output parameter that tells how much data needs to be skipped
564  *            in order to find the following frame header.
565  *
566  * Default callback for check_valid_frame.
567  * 
568  * Returns: Always TRUE.
569  */
570 static gboolean
571 gst_base_parse_check_frame (GstBaseParse * parse,
572     GstBuffer * buffer, guint * framesize, gint * skipsize)
573 {
574   *framesize = GST_BUFFER_SIZE (buffer);
575   *skipsize = 0;
576   return TRUE;
577 }
578
579
580 /**
581  * gst_base_parse_parse_frame:
582  * @parse: #GstBaseParse.
583  * @buffer: #GstBuffer.
584  *
585  * Default callback for parse_frame.
586  */
587 static GstFlowReturn
588 gst_base_parse_parse_frame (GstBaseParse * parse, GstBuffer * buffer)
589 {
590   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
591       GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
592     GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
593   }
594   if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
595       GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
596     GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
597   }
598   return GST_FLOW_OK;
599 }
600
601 /**
602  * gst_base_parse_convert:
603  * @parse: #GstBaseParse.
604  * @src_format: #GstFormat describing the source format.
605  * @src_value: Source value to be converted.
606  * @dest_format: #GstFormat defining the converted format.
607  * @dest_value: Pointer where the conversion result will be put.
608  *
609  * Converts using configured "convert" vmethod in #GstBaseParse class.
610  *
611  * Returns: TRUE if conversion was successful.
612  */
613 static gboolean
614 gst_base_parse_convert (GstBaseParse * parse,
615     GstFormat src_format,
616     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
617 {
618   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
619   gboolean ret;
620
621   g_return_val_if_fail (dest_value != NULL, FALSE);
622
623   if (!klass->convert)
624     return FALSE;
625
626   ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
627
628 #ifndef GST_DISABLE_GST_DEBUG
629   {
630     if (ret) {
631       if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
632         GST_LOG_OBJECT (parse,
633             "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
634             GST_TIME_ARGS (src_value), *dest_value);
635       } else if (dest_format == GST_FORMAT_TIME &&
636           src_format == GST_FORMAT_BYTES) {
637         GST_LOG_OBJECT (parse,
638             "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
639             src_value, GST_TIME_ARGS (*dest_value));
640       } else {
641         GST_LOG_OBJECT (parse,
642             "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
643             GST_STR_NULL (gst_format_get_name (src_format)),
644             GST_STR_NULL (gst_format_get_name (dest_format)),
645             src_value, *dest_value);
646       }
647     } else {
648       GST_DEBUG_OBJECT (parse, "conversion failed");
649     }
650   }
651 #endif
652
653   return ret;
654 }
655
656 /**
657  * gst_base_parse_sink_event:
658  * @pad: #GstPad that received the event.
659  * @event: #GstEvent to be handled.
660  *
661  * Handler for sink pad events.
662  *
663  * Returns: TRUE if the event was handled.
664  */
665 static gboolean
666 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
667 {
668   GstBaseParse *parse;
669   GstBaseParseClass *bclass;
670   gboolean handled = FALSE;
671   gboolean ret = TRUE;
672
673
674   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
675   bclass = GST_BASE_PARSE_GET_CLASS (parse);
676
677   GST_DEBUG_OBJECT (parse, "handling event %d", GST_EVENT_TYPE (event));
678
679   /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
680    * pending segment */
681   if (parse->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
682       && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
683       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
684       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
685
686     if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
687       /* See if any bitrate tags were posted */
688       gst_base_parse_handle_tag (parse, event);
689
690     parse->priv->pending_events =
691         g_list_append (parse->priv->pending_events, event);
692     ret = TRUE;
693   } else {
694
695     if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
696         parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
697       /* We've not posted bitrate tags yet - do so now */
698       gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
699
700     if (bclass->event)
701       handled = bclass->event (parse, event);
702
703     if (!handled)
704       handled = gst_base_parse_sink_eventfunc (parse, event);
705
706     if (!handled)
707       ret = gst_pad_event_default (pad, event);
708   }
709
710   gst_object_unref (parse);
711   GST_DEBUG_OBJECT (parse, "event handled");
712   return ret;
713 }
714
715
716 /**
717  * gst_base_parse_sink_eventfunc:
718  * @parse: #GstBaseParse.
719  * @event: #GstEvent to be handled.
720  *
721  * Element-level event handler function.
722  *
723  * Returns: TRUE if the event was handled and not need forwarding.
724  */
725 static gboolean
726 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
727 {
728   gboolean handled = FALSE;
729   GstEvent **eventp;
730
731   switch (GST_EVENT_TYPE (event)) {
732     case GST_EVENT_NEWSEGMENT:
733     {
734       gdouble rate, applied_rate;
735       GstFormat format;
736       gint64 start, stop, pos, next_ts, offset = 0;
737       gboolean update;
738
739       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
740           &format, &start, &stop, &pos);
741
742       GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
743           "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
744           ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
745           GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
746
747       if (format == GST_FORMAT_BYTES) {
748         GstClockTime seg_start, seg_stop;
749         GstBaseParseSeek *seek = NULL;
750         GSList *node;
751
752         /* stop time is allowed to be open-ended, but not start & pos */
753         seg_stop = GST_CLOCK_TIME_NONE;
754         seg_start = 0;
755         offset = pos;
756
757         GST_OBJECT_LOCK (parse);
758         for (node = parse->priv->pending_seeks; node; node = node->next) {
759           GstBaseParseSeek *tmp = node->data;
760
761           if (tmp->offset == pos) {
762             seek = tmp;
763             break;
764           }
765         }
766         parse->priv->pending_seeks =
767             g_slist_remove (parse->priv->pending_seeks, seek);
768         GST_OBJECT_UNLOCK (parse);
769
770         if (seek) {
771           GST_DEBUG_OBJECT (parse,
772               "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
773               seek->accurate ? " accurate" : "", &seek->segment);
774           seg_start = seek->segment.start;
775           seg_stop = seek->segment.stop;
776           next_ts = seek->start_ts;
777           parse->priv->exact_position = seek->accurate;
778           g_free (seek);
779         } else {
780           /* best attempt convert */
781           /* as these are only estimates, stop is kept open-ended to avoid
782            * premature cutting */
783           gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
784               GST_FORMAT_TIME, (gint64 *) & seg_start);
785           parse->priv->exact_position = (start == 0);
786           next_ts = seg_start;
787         }
788
789         gst_event_unref (event);
790         event = gst_event_new_new_segment_full (update, rate, applied_rate,
791             GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
792         format = GST_FORMAT_TIME;
793         start = seg_start;
794         stop = seg_stop;
795         GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
796             "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
797             GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
798       } else if (format != GST_FORMAT_TIME) {
799         /* Unknown incoming segment format. Output a default open-ended 
800          * TIME segment */
801         gst_event_unref (event);
802         event = gst_event_new_new_segment_full (update, rate, applied_rate,
803             GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
804         format = GST_FORMAT_TIME;
805         next_ts = start = 0;
806         stop = GST_CLOCK_TIME_NONE;
807       } else {
808         /* not considered BYTE seekable if it is talking to us in TIME,
809          * whatever else it might claim */
810         parse->priv->upstream_seekable = FALSE;
811         next_ts = start;
812       }
813
814       gst_segment_set_newsegment_full (&parse->segment, update, rate,
815           applied_rate, format, start, stop, start);
816
817       /* save the segment for later, right before we push a new buffer so that
818        * the caps are fixed and the next linked element can receive
819        * the segment. */
820       eventp = &parse->pending_segment;
821       gst_event_replace (eventp, event);
822       gst_event_unref (event);
823       handled = TRUE;
824
825       /* but finish the current segment */
826       GST_DEBUG_OBJECT (parse, "draining current segment");
827       if (parse->segment.rate > 0.0)
828         gst_base_parse_drain (parse);
829       else
830         gst_base_parse_process_fragment (parse, FALSE);
831       gst_adapter_clear (parse->adapter);
832       parse->priv->offset = offset;
833       parse->priv->sync_offset = offset;
834       parse->priv->next_ts = next_ts;
835       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
836       parse->priv->discont = TRUE;
837       break;
838     }
839
840     case GST_EVENT_FLUSH_START:
841       parse->priv->flushing = TRUE;
842       handled = gst_pad_push_event (parse->srcpad, event);
843       /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
844       GST_PAD_STREAM_LOCK (parse->srcpad);
845       GST_PAD_STREAM_UNLOCK (parse->srcpad);
846
847       break;
848
849     case GST_EVENT_FLUSH_STOP:
850       gst_adapter_clear (parse->adapter);
851       gst_base_parse_clear_queues (parse);
852       parse->priv->flushing = FALSE;
853       parse->priv->discont = TRUE;
854       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
855       break;
856
857     case GST_EVENT_EOS:
858       if (parse->segment.rate > 0.0)
859         gst_base_parse_drain (parse);
860       else
861         gst_base_parse_process_fragment (parse, FALSE);
862
863       /* If we STILL have zero frames processed, fire an error */
864       if (parse->priv->framecount == 0) {
865         GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
866             ("No valid frames found before end of stream"), (NULL));
867       }
868       /* newsegment before eos */
869       if (parse->pending_segment) {
870         gst_pad_push_event (parse->srcpad, parse->pending_segment);
871         parse->pending_segment = NULL;
872       }
873       break;
874
875     default:
876       break;
877   }
878
879   return handled;
880 }
881
882
883 /**
884  * gst_base_parse_src_event:
885  * @pad: #GstPad that received the event.
886  * @event: #GstEvent that was received.
887  *
888  * Handler for source pad events.
889  *
890  * Returns: TRUE if the event was handled.
891  */
892 static gboolean
893 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
894 {
895   GstBaseParse *parse;
896   GstBaseParseClass *bclass;
897   gboolean handled = FALSE;
898   gboolean ret = TRUE;
899
900   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
901   bclass = GST_BASE_PARSE_GET_CLASS (parse);
902
903   GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
904       GST_EVENT_TYPE_NAME (event));
905
906   if (bclass->src_event)
907     handled = bclass->src_event (parse, event);
908
909   if (!handled)
910     ret = gst_pad_event_default (pad, event);
911   else
912     gst_event_unref (event);
913
914   gst_object_unref (parse);
915   return ret;
916 }
917
918
919 /**
920  * gst_base_parse_src_eventfunc:
921  * @parse: #GstBaseParse.
922  * @event: #GstEvent that was received.
923  *
924  * Default srcpad event handler.
925  *
926  * Returns: TRUE if the event was handled and can be dropped.
927  */
928 static gboolean
929 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
930 {
931   gboolean handled = FALSE;
932   GstBaseParseClass *bclass;
933
934   bclass = GST_BASE_PARSE_GET_CLASS (parse);
935
936   switch (GST_EVENT_TYPE (event)) {
937     case GST_EVENT_SEEK:
938     {
939       if (parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
940         handled = gst_base_parse_handle_seek (parse, event);
941       }
942       break;
943     }
944     default:
945       break;
946   }
947   return handled;
948 }
949
950
951 /**
952  * gst_base_parse_convert_default:
953  * @parse: #GstBaseParse.
954  * @src_format: #GstFormat describing the source format.
955  * @src_value: Source value to be converted.
956  * @dest_format: #GstFormat defining the converted format.
957  * @dest_value: Pointer where the conversion result will be put.
958  *
959  * Default implementation of "convert" vmethod in #GstBaseParse class.
960  *
961  * Returns: TRUE if conversion was successful.
962  */
963 gboolean
964 gst_base_parse_convert_default (GstBaseParse * parse,
965     GstFormat src_format,
966     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
967 {
968   gboolean ret = FALSE;
969   guint64 bytes, duration;
970
971   if (G_UNLIKELY (src_format == dest_format)) {
972     *dest_value = src_value;
973     return TRUE;
974   }
975
976   if (G_UNLIKELY (src_value == -1)) {
977     *dest_value = -1;
978     return TRUE;
979   }
980
981   if (G_UNLIKELY (src_value == 0)) {
982     *dest_value = 0;
983     return TRUE;
984   }
985
986   /* need at least some frames */
987   if (!parse->priv->framecount)
988     return FALSE;
989
990   duration = parse->priv->acc_duration / GST_MSECOND;
991   bytes = parse->priv->bytecount;
992
993   if (G_UNLIKELY (!duration || !bytes))
994     return FALSE;
995
996   if (src_format == GST_FORMAT_BYTES) {
997     if (dest_format == GST_FORMAT_TIME) {
998       /* BYTES -> TIME conversion */
999       GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1000       *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1001       *dest_value *= GST_MSECOND;
1002       GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
1003           *dest_value / GST_MSECOND);
1004       ret = TRUE;
1005     }
1006   } else if (src_format == GST_FORMAT_TIME) {
1007     if (dest_format == GST_FORMAT_BYTES) {
1008       GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1009       *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
1010           duration);
1011       GST_DEBUG_OBJECT (parse,
1012           "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
1013           src_value / GST_MSECOND, *dest_value);
1014       ret = TRUE;
1015     }
1016   } else if (src_format == GST_FORMAT_DEFAULT) {
1017     /* DEFAULT == frame-based */
1018     if (dest_format == GST_FORMAT_TIME) {
1019       if (parse->priv->fps_den) {
1020         *dest_value = gst_util_uint64_scale (src_value,
1021             GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
1022         ret = TRUE;
1023       }
1024     } else if (dest_format == GST_FORMAT_BYTES) {
1025     }
1026   }
1027
1028   return ret;
1029 }
1030
1031 /**
1032  * gst_base_parse_update_duration:
1033  * @parse: #GstBaseParse.
1034  *
1035  */
1036 static void
1037 gst_base_parse_update_duration (GstBaseParse * aacparse)
1038 {
1039   GstPad *peer;
1040   GstBaseParse *parse;
1041
1042   parse = GST_BASE_PARSE (aacparse);
1043
1044   peer = gst_pad_get_peer (parse->sinkpad);
1045   if (peer) {
1046     GstFormat pformat = GST_FORMAT_BYTES;
1047     gboolean qres = FALSE;
1048     gint64 ptot, dest_value;
1049
1050     qres = gst_pad_query_duration (peer, &pformat, &ptot);
1051     gst_object_unref (GST_OBJECT (peer));
1052     if (qres) {
1053       if (gst_base_parse_convert (parse, pformat, ptot,
1054               GST_FORMAT_TIME, &dest_value))
1055         parse->priv->estimated_duration = dest_value;
1056     }
1057   }
1058 }
1059
1060 static void
1061 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
1062     gboolean post_avg, gboolean post_max)
1063 {
1064   GstTagList *taglist = gst_tag_list_new ();
1065
1066   if (post_min && parse->priv->post_min_bitrate)
1067     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1068         GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
1069
1070   if (post_avg && parse->priv->post_avg_bitrate) {
1071     parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1072     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
1073         parse->priv->avg_bitrate, NULL);
1074   }
1075
1076   if (post_max && parse->priv->post_max_bitrate)
1077     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
1078         GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
1079
1080   GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
1081       parse->priv->min_bitrate, parse->priv->avg_bitrate,
1082       parse->priv->max_bitrate);
1083
1084   gst_element_found_tags_for_pad (GST_ELEMENT (parse), parse->srcpad, taglist);
1085 }
1086
1087 /**
1088  * gst_base_parse_update_bitrates:
1089  * @parse: #GstBaseParse.
1090  * @buffer: Current frame as a #GstBuffer
1091  *
1092  * Keeps track of the minimum and maximum bitrates, and also maintains a
1093  * running average bitrate of the stream so far.
1094  */
1095 static void
1096 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
1097 {
1098   /* Only update the tag on a 10 kbps delta */
1099   static const gint update_threshold = 10000;
1100
1101   GstBaseParseClass *klass;
1102   guint64 data_len, frame_dur;
1103   gint overhead = 0, frame_bitrate, old_avg_bitrate;
1104   gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1105
1106   klass = GST_BASE_PARSE_GET_CLASS (parse);
1107
1108   if (klass->get_frame_overhead) {
1109     overhead = klass->get_frame_overhead (parse, buffer);
1110     if (overhead == -1)
1111       return;
1112   }
1113
1114   data_len = GST_BUFFER_SIZE (buffer) - overhead;
1115   parse->priv->data_bytecount += data_len;
1116
1117   /* duration should be valid by now,
1118    * either set by subclass or maybe based on fps settings */
1119   if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1120     /* Calculate duration of a frame from buffer properties */
1121     frame_dur = GST_BUFFER_DURATION (buffer);
1122     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1123         parse->priv->acc_duration;
1124
1125   } else {
1126     /* No way to figure out frame duration (is this even possible?) */
1127     return;
1128   }
1129
1130   /* override if subclass provided bitrate, e.g. metadata based */
1131   if (parse->priv->bitrate) {
1132     parse->priv->avg_bitrate = parse->priv->bitrate;
1133   }
1134
1135   frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1136
1137   GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1138       parse->priv->avg_bitrate);
1139
1140   if (frame_bitrate < parse->priv->min_bitrate) {
1141     parse->priv->min_bitrate = frame_bitrate;
1142     update_min = TRUE;
1143   }
1144
1145   if (frame_bitrate > parse->priv->max_bitrate) {
1146     parse->priv->max_bitrate = frame_bitrate;
1147     update_max = TRUE;
1148   }
1149
1150   old_avg_bitrate = parse->priv->posted_avg_bitrate;
1151   if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold ||
1152       (gint) (parse->priv->avg_bitrate - old_avg_bitrate) > update_threshold)
1153     update_avg = TRUE;
1154
1155   /* always post all at threshold time */
1156   if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE)
1157     gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
1158
1159   if (parse->priv->framecount > MIN_FRAMES_TO_POST_BITRATE &&
1160       (update_min || update_avg || update_max))
1161     gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1162
1163   /* If average bitrate changes that much and no valid (time) duration provided,
1164    * then post a new duration message so applications can update their cached
1165    * values */
1166   if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1167           GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1168     gst_element_post_message (GST_ELEMENT (parse),
1169         gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1170 }
1171
1172 /**
1173  * gst_base_parse_add_index_entry:
1174  * @parse: #GstBaseParse.
1175  * @offset: offset of entry
1176  * @ts: timestamp associated with offset
1177  * @key: whether entry refers to keyframe
1178  * @force: add entry disregarding sanity checks
1179  *
1180  * Adds an entry to the index associating @offset to @ts.  It is recommended
1181  * to only add keyframe entries.  @force allows to bypass checks, such as
1182  * whether the stream is (upstream) seekable, another entry is already "close"
1183  * to the new entry, etc.
1184  *
1185  * Returns: #gboolean indicating whether entry was added
1186  */
1187 gboolean
1188 gst_base_parse_add_index_entry (GstBaseParse * parse, guint64 offset,
1189     GstClockTime ts, gboolean key, gboolean force)
1190 {
1191   gboolean ret = FALSE;
1192   GstIndexAssociation associations[2];
1193
1194   GST_LOG_OBJECT (parse, "Adding key=%d index entry %" GST_TIME_FORMAT
1195       " @ offset 0x%08" G_GINT64_MODIFIER "x", key, GST_TIME_ARGS (ts), offset);
1196
1197   if (G_LIKELY (!force)) {
1198
1199     if (!parse->priv->upstream_seekable) {
1200       GST_DEBUG_OBJECT (parse, "upstream not seekable; discarding");
1201       goto exit;
1202     }
1203
1204     if (parse->priv->index_last_offset >= offset) {
1205       GST_DEBUG_OBJECT (parse, "already have entries up to offset "
1206           "0x%08" G_GINT64_MODIFIER "x", parse->priv->index_last_offset);
1207       goto exit;
1208     }
1209
1210     if (GST_CLOCK_DIFF (parse->priv->index_last_ts, ts) <
1211         parse->priv->idx_interval) {
1212       GST_DEBUG_OBJECT (parse, "entry too close to last time %" GST_TIME_FORMAT,
1213           GST_TIME_ARGS (parse->priv->index_last_ts));
1214       goto exit;
1215     }
1216   }
1217
1218   associations[0].format = GST_FORMAT_TIME;
1219   associations[0].value = ts;
1220   associations[1].format = GST_FORMAT_BYTES;
1221   associations[1].value = offset;
1222
1223   /* index might change on-the-fly, although that would be nutty app ... */
1224   GST_OBJECT_LOCK (parse);
1225   gst_index_add_associationv (parse->priv->index, parse->priv->index_id,
1226       (key) ? GST_ASSOCIATION_FLAG_KEY_UNIT : GST_ASSOCIATION_FLAG_NONE,
1227       2, (const GstIndexAssociation *) &associations);
1228   GST_OBJECT_UNLOCK (parse);
1229
1230   parse->priv->index_last_offset = offset;
1231   parse->priv->index_last_ts = ts;
1232
1233   ret = TRUE;
1234
1235 exit:
1236   return ret;
1237 }
1238
1239 /* check for seekable upstream, above and beyond a mere query */
1240 static void
1241 gst_base_parse_check_seekability (GstBaseParse * parse)
1242 {
1243   GstQuery *query;
1244   gboolean seekable = FALSE;
1245   gint64 start = -1, stop = -1;
1246   guint idx_interval = 0;
1247
1248   query = gst_query_new_seeking (GST_FORMAT_BYTES);
1249   if (!gst_pad_peer_query (parse->sinkpad, query)) {
1250     GST_DEBUG_OBJECT (parse, "seeking query failed");
1251     goto done;
1252   }
1253
1254   gst_query_parse_seeking (query, NULL, &seekable, &start, &stop);
1255
1256   /* try harder to query upstream size if we didn't get it the first time */
1257   if (seekable && stop == -1) {
1258     GstFormat fmt = GST_FORMAT_BYTES;
1259
1260     GST_DEBUG_OBJECT (parse, "doing duration query to fix up unset stop");
1261     gst_pad_query_peer_duration (parse->sinkpad, &fmt, &stop);
1262   }
1263
1264   /* if upstream doesn't know the size, it's likely that it's not seekable in
1265    * practice even if it technically may be seekable */
1266   if (seekable && (start != 0 || stop <= start)) {
1267     GST_DEBUG_OBJECT (parse, "seekable but unknown start/stop -> disable");
1268     seekable = FALSE;
1269   }
1270
1271   /* let's not put every single frame into our index */
1272   if (seekable) {
1273     if (stop < 10 * 1024 * 1024)
1274       idx_interval = 100;
1275     else if (stop < 100 * 1024 * 1024)
1276       idx_interval = 500;
1277     else
1278       idx_interval = 1000;
1279   }
1280
1281 done:
1282   gst_query_unref (query);
1283
1284   GST_DEBUG_OBJECT (parse, "seekable: %d (%" G_GUINT64_FORMAT " - %"
1285       G_GUINT64_FORMAT ")", seekable, start, stop);
1286   parse->priv->upstream_seekable = seekable;
1287
1288   GST_DEBUG_OBJECT (parse, "idx_interval: %ums", idx_interval);
1289   parse->priv->idx_interval = idx_interval * GST_MSECOND;
1290 }
1291
1292 /**
1293  * gst_base_parse_handle_and_push_buffer:
1294  * @parse: #GstBaseParse.
1295  * @klass: #GstBaseParseClass.
1296  * @buffer: #GstBuffer.
1297  *
1298  * Parses the frame from given buffer and pushes it forward. Also performs
1299  * timestamp handling and checks the segment limits.
1300  *
1301  * This is called with srcpad STREAM_LOCK held.
1302  *
1303  * Returns: #GstFlowReturn
1304  */
1305 static GstFlowReturn
1306 gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
1307     GstBaseParseClass * klass, GstBuffer * buffer)
1308 {
1309   GstFlowReturn ret;
1310
1311   if (parse->priv->discont) {
1312     GST_DEBUG_OBJECT (parse, "marking DISCONT");
1313     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1314     parse->priv->discont = FALSE;
1315   }
1316
1317   GST_LOG_OBJECT (parse,
1318       "parsing frame at offset %" G_GUINT64_FORMAT
1319       " (%#" G_GINT64_MODIFIER "x) of size %d",
1320       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1321       GST_BUFFER_SIZE (buffer));
1322
1323   ret = klass->parse_frame (parse, buffer);
1324
1325   /* re-use default handler to add missing metadata as-much-as-possible */
1326   gst_base_parse_parse_frame (parse, buffer);
1327   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1328       GST_BUFFER_DURATION_IS_VALID (buffer)) {
1329     parse->priv->next_ts =
1330         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1331   } else {
1332     /* we lost track, do not produce bogus time next time around
1333      * (probably means parser subclass has given up on parsing as well) */
1334     GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1335     parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1336   }
1337
1338   /* First buffers are dropped, this means that the subclass needs more
1339    * frames to decide on the format and queues them internally */
1340   /* convert internal flow to OK and mark discont for the next buffer. */
1341   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1342     gst_buffer_unref (buffer);
1343     return GST_FLOW_OK;
1344   } else if (ret != GST_FLOW_OK) {
1345     return ret;
1346   }
1347
1348   return gst_base_parse_push_buffer (parse, buffer);
1349 }
1350
1351 /**
1352  * gst_base_parse_push_buffer:
1353  * @parse: #GstBaseParse.
1354  * @buffer: #GstBuffer.
1355  *
1356  * Pushes the buffer downstream, sends any pending events and
1357  * does some timestamp and segment handling.
1358  *
1359  * This must be called with srcpad STREAM_LOCK held.
1360  *
1361  * Returns: #GstFlowReturn
1362  */
1363 GstFlowReturn
1364 gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
1365 {
1366   GstFlowReturn ret = GST_FLOW_OK;
1367   GstClockTime last_start = GST_CLOCK_TIME_NONE;
1368   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1369   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1370
1371   GST_LOG_OBJECT (parse,
1372       "processing buffer of size %d with ts %" GST_TIME_FORMAT
1373       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1374       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1375       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1376
1377   /* some one-time start-up */
1378   if (G_UNLIKELY (!parse->priv->framecount)) {
1379     gst_base_parse_check_seekability (parse);
1380   }
1381
1382   /* update stats */
1383   parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1384   if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME)) {
1385     parse->priv->framecount++;
1386     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1387       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1388     }
1389   }
1390   GST_BUFFER_FLAG_UNSET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME);
1391   if (parse->priv->update_interval &&
1392       (parse->priv->framecount % parse->priv->update_interval) == 0)
1393     gst_base_parse_update_duration (parse);
1394
1395   gst_base_parse_update_bitrates (parse, buffer);
1396
1397   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1398     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1399   if (last_start != GST_CLOCK_TIME_NONE
1400       && GST_BUFFER_DURATION_IS_VALID (buffer))
1401     last_stop = last_start + GST_BUFFER_DURATION (buffer);
1402
1403   /* should have caps by now */
1404   g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1405
1406   gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1407
1408   /* segment adjustment magic; only if we are running the whole show */
1409   if (!parse->priv->passthrough && parse->segment.rate > 0.0 &&
1410       (parse->priv->pad_mode == GST_ACTIVATE_PULL ||
1411           parse->priv->upstream_seekable)) {
1412     /* segment times are typically estimates,
1413      * actual frame data might lead subclass to different timestamps,
1414      * so override segment start from what is supplied there */
1415     if (G_UNLIKELY (parse->pending_segment && !parse->priv->exact_position &&
1416             GST_CLOCK_TIME_IS_VALID (last_start))) {
1417       gst_event_unref (parse->pending_segment);
1418       parse->segment.start =
1419           MIN ((guint64) last_start, (guint64) parse->segment.stop);
1420       GST_DEBUG_OBJECT (parse,
1421           "adjusting pending segment start to %" GST_TIME_FORMAT,
1422           GST_TIME_ARGS (parse->segment.start));
1423       parse->pending_segment =
1424           gst_event_new_new_segment (FALSE, parse->segment.rate,
1425           parse->segment.format, parse->segment.start, parse->segment.stop,
1426           parse->segment.start);
1427     }
1428     /* handle gaps, e.g. non-zero start-time, in as much not handled by above */
1429     if (GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop) &&
1430         GST_CLOCK_TIME_IS_VALID (last_start)) {
1431       GstClockTimeDiff diff;
1432
1433       /* only send newsegments with increasing start times,
1434        * otherwise if these go back and forth downstream (sinks) increase
1435        * accumulated time and running_time */
1436       diff = GST_CLOCK_DIFF (parse->segment.last_stop, last_start);
1437       if (G_UNLIKELY (diff > 2 * GST_SECOND && last_start > parse->segment.start
1438               && (!GST_CLOCK_TIME_IS_VALID (parse->segment.stop) ||
1439                   last_start < parse->segment.stop))) {
1440         GST_DEBUG_OBJECT (parse,
1441             "Gap of %" G_GINT64_FORMAT " ns detected in stream "
1442             "(%" GST_TIME_FORMAT " -> %" GST_TIME_FORMAT "). "
1443             "Sending updated NEWSEGMENT events", diff,
1444             GST_TIME_ARGS (parse->segment.last_stop),
1445             GST_TIME_ARGS (last_start));
1446         if (G_UNLIKELY (parse->pending_segment)) {
1447           gst_event_unref (parse->pending_segment);
1448           parse->segment.start = last_start;
1449           parse->pending_segment =
1450               gst_event_new_new_segment (FALSE, parse->segment.rate,
1451               parse->segment.format, parse->segment.start, parse->segment.stop,
1452               parse->segment.start);
1453         } else {
1454           /* send newsegment events such that the gap is not accounted in
1455            * accum time, hence running_time */
1456           /* close ahead of gap */
1457           gst_pad_push_event (parse->srcpad,
1458               gst_event_new_new_segment (TRUE, parse->segment.rate,
1459                   parse->segment.format, parse->segment.last_stop,
1460                   parse->segment.last_stop, parse->segment.last_stop));
1461           /* skip gap */
1462           gst_pad_push_event (parse->srcpad,
1463               gst_event_new_new_segment (FALSE, parse->segment.rate,
1464                   parse->segment.format, last_start, parse->segment.stop,
1465                   last_start));
1466         }
1467         /* align segment view with downstream,
1468          * prevents double-counting accum when closing segment */
1469         gst_segment_set_newsegment (&parse->segment, FALSE,
1470             parse->segment.rate, parse->segment.format, last_start,
1471             parse->segment.stop, last_start);
1472         parse->segment.last_stop = last_start;
1473       }
1474     }
1475   }
1476
1477   /* and should then also be linked downstream, so safe to send some events */
1478   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1479     if (G_UNLIKELY (parse->close_segment)) {
1480       GST_DEBUG_OBJECT (parse, "loop sending close segment");
1481       gst_pad_push_event (parse->srcpad, parse->close_segment);
1482       parse->close_segment = NULL;
1483     }
1484
1485     if (G_UNLIKELY (parse->pending_segment)) {
1486       GST_DEBUG_OBJECT (parse, "loop push pending segment");
1487       gst_pad_push_event (parse->srcpad, parse->pending_segment);
1488       parse->pending_segment = NULL;
1489     }
1490   } else {
1491     if (G_UNLIKELY (parse->pending_segment)) {
1492       GST_DEBUG_OBJECT (parse, "chain pushing a pending segment");
1493       gst_pad_push_event (parse->srcpad, parse->pending_segment);
1494       parse->pending_segment = NULL;
1495     }
1496   }
1497
1498   if (G_UNLIKELY (parse->priv->pending_events)) {
1499     GList *l;
1500
1501     for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1502       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1503     }
1504     g_list_free (parse->priv->pending_events);
1505     parse->priv->pending_events = NULL;
1506   }
1507
1508   if (parse->priv->upstream_seekable && parse->priv->exact_position &&
1509       GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1510     gst_base_parse_add_index_entry (parse, GST_BUFFER_OFFSET (buffer),
1511         GST_BUFFER_TIMESTAMP (buffer),
1512         !GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DELTA_UNIT), FALSE);
1513
1514   if (klass->pre_push_buffer)
1515     ret = klass->pre_push_buffer (parse, buffer);
1516   else
1517     ret = GST_BASE_PARSE_FLOW_CLIP;
1518
1519   if (ret == GST_BASE_PARSE_FLOW_CLIP) {
1520     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1521         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1522         GST_BUFFER_TIMESTAMP (buffer) >
1523         parse->segment.stop + parse->priv->lead_out_ts) {
1524       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1525       ret = GST_FLOW_UNEXPECTED;
1526     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1527         GST_BUFFER_DURATION_IS_VALID (buffer) &&
1528         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1529         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer) +
1530         parse->priv->lead_in_ts < parse->segment.start) {
1531       GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1532       ret = GST_BASE_PARSE_FLOW_DROPPED;
1533     } else {
1534       ret = GST_FLOW_OK;
1535     }
1536   }
1537
1538   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1539     GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1540         GST_BUFFER_SIZE (buffer));
1541     gst_buffer_unref (buffer);
1542     ret = GST_FLOW_OK;
1543   } else if (ret == GST_FLOW_OK) {
1544     if (parse->segment.rate > 0.0) {
1545       GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
1546           GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1547       ret = gst_pad_push (parse->srcpad, buffer);
1548     } else {
1549       GST_LOG_OBJECT (parse, "frame (%d bytes) queued for now",
1550           GST_BUFFER_SIZE (buffer));
1551       parse->priv->buffers_queued =
1552           g_slist_prepend (parse->priv->buffers_queued, buffer);
1553       ret = GST_FLOW_OK;
1554     }
1555   } else {
1556     gst_buffer_unref (buffer);
1557     GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1558         GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1559     /* if we are not sufficiently in control, let upstream decide on EOS */
1560     if (ret == GST_FLOW_UNEXPECTED &&
1561         (parse->priv->passthrough ||
1562             (parse->priv->pad_mode == GST_ACTIVATE_PUSH &&
1563                 !parse->priv->upstream_seekable)))
1564       ret = GST_FLOW_OK;
1565   }
1566
1567   /* Update current running segment position */
1568   if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE &&
1569       parse->segment.last_stop < last_stop)
1570     gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1571
1572   return ret;
1573 }
1574
1575
1576 /**
1577  * gst_base_parse_drain:
1578  * @parse: #GstBaseParse.
1579  *
1580  * Drains the adapter until it is empty. It decreases the min_frame_size to
1581  * match the current adapter size and calls chain method until the adapter
1582  * is emptied or chain returns with error.
1583  */
1584 static void
1585 gst_base_parse_drain (GstBaseParse * parse)
1586 {
1587   guint avail;
1588
1589   GST_DEBUG_OBJECT (parse, "draining");
1590   parse->priv->drain = TRUE;
1591
1592   for (;;) {
1593     avail = gst_adapter_available (parse->adapter);
1594     if (!avail)
1595       break;
1596
1597     if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1598       break;
1599     }
1600
1601     /* nothing changed, maybe due to truncated frame; break infinite loop */
1602     if (avail == gst_adapter_available (parse->adapter)) {
1603       GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1604       gst_adapter_clear (parse->adapter);
1605     }
1606   }
1607
1608   parse->priv->drain = FALSE;
1609 }
1610
1611 /**
1612  * gst_base_parse_process_fragment:
1613  * @parse: #GstBaseParse.
1614  *
1615  * Processes a reverse playback (forward) fragment:
1616  * - append head of last fragment that was skipped to current fragment data
1617  * - drain the resulting current fragment data (i.e. repeated chain)
1618  * - add time/duration (if needed) to frames queued by chain
1619  * - push queued data
1620  */
1621 static GstFlowReturn
1622 gst_base_parse_process_fragment (GstBaseParse * parse, gboolean push_only)
1623 {
1624   GstBuffer *buf;
1625   GstFlowReturn ret = GST_FLOW_OK;
1626   GSList *send = NULL;
1627
1628   if (push_only)
1629     goto push;
1630
1631   /* restore order */
1632   parse->priv->buffers_pending = g_slist_reverse (parse->priv->buffers_pending);
1633   while (parse->priv->buffers_pending) {
1634     buf = GST_BUFFER_CAST (parse->priv->buffers_pending->data);
1635     GST_LOG_OBJECT (parse, "adding pending buffer (size %d)",
1636         GST_BUFFER_SIZE (buf));
1637     gst_adapter_push (parse->adapter, buf);
1638     parse->priv->buffers_pending =
1639         g_slist_delete_link (parse->priv->buffers_pending,
1640         parse->priv->buffers_pending);
1641   }
1642
1643   /* invalidate so no fall-back timestamping is performed;
1644    * ok if taken from subclass or upstream */
1645   parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1646   /* prevent it hanging around stop all the time */
1647   parse->segment.last_stop = GST_CLOCK_TIME_NONE;
1648   /* mark next run */
1649   parse->priv->discont = TRUE;
1650
1651   /* chain looks for frames and queues resulting ones (in stead of pushing) */
1652   /* initial skipped data is added to buffers_pending */
1653   gst_base_parse_drain (parse);
1654
1655 push:
1656   /* add metadata (if needed to queued buffers */
1657   GST_LOG_OBJECT (parse, "last timestamp: %" GST_TIME_FORMAT,
1658       GST_TIME_ARGS (parse->priv->last_ts));
1659   while (parse->priv->buffers_queued) {
1660     buf = GST_BUFFER_CAST (parse->priv->buffers_queued->data);
1661
1662     /* no touching if upstream or parsing provided time */
1663     if (GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1664       GST_LOG_OBJECT (parse, "buffer has time %" GST_TIME_FORMAT,
1665           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1666     } else if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts) &&
1667         GST_BUFFER_DURATION_IS_VALID (buf)) {
1668       if (G_LIKELY (GST_BUFFER_DURATION (buf) <= parse->priv->last_ts))
1669         parse->priv->last_ts -= GST_BUFFER_DURATION (buf);
1670       else
1671         parse->priv->last_ts = 0;
1672       GST_BUFFER_TIMESTAMP (buf) = parse->priv->last_ts;
1673       GST_LOG_OBJECT (parse, "applied time %" GST_TIME_FORMAT,
1674           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1675     } else {
1676       /* no idea, very bad */
1677       GST_WARNING_OBJECT (parse, "could not determine time for buffer");
1678     }
1679
1680     /* reverse order for ascending sending */
1681     send = g_slist_prepend (send, buf);
1682     parse->priv->buffers_queued =
1683         g_slist_delete_link (parse->priv->buffers_queued,
1684         parse->priv->buffers_queued);
1685   }
1686
1687   /* send buffers */
1688   while (send) {
1689     buf = GST_BUFFER_CAST (send->data);
1690     GST_LOG_OBJECT (parse, "pushing buffer %p, timestamp %"
1691         GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT
1692         ", offset %" G_GINT64_FORMAT, buf,
1693         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1694         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)), GST_BUFFER_OFFSET (buf));
1695
1696     if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts)))
1697       parse->priv->last_ts = GST_BUFFER_TIMESTAMP (buf);
1698
1699     /* iterate output queue an push downstream */
1700     ret = gst_pad_push (parse->srcpad, buf);
1701     send = g_slist_delete_link (send, send);
1702
1703     /* clear any leftover if error */
1704     if (G_UNLIKELY (ret != GST_FLOW_OK)) {
1705       while (send) {
1706         buf = GST_BUFFER_CAST (send->data);
1707         gst_buffer_unref (buf);
1708         send = g_slist_delete_link (send, send);
1709       }
1710     }
1711   }
1712
1713   /* any trailing unused no longer usable (ideally none) */
1714   if (G_UNLIKELY (gst_adapter_available (parse->adapter))) {
1715     GST_DEBUG_OBJECT (parse, "discarding %d trailing bytes",
1716         gst_adapter_available (parse->adapter));
1717     gst_adapter_clear (parse->adapter);
1718   }
1719
1720   return ret;
1721 }
1722
1723 /* small helper that checks whether we have been trying to resync too long */
1724 static inline GstFlowReturn
1725 gst_base_parse_check_sync (GstBaseParse * parse)
1726 {
1727   if (G_UNLIKELY (parse->priv->discont &&
1728           parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
1729     GST_ELEMENT_ERROR (parse, STREAM, DECODE,
1730         ("Failed to parse stream"), (NULL));
1731     return GST_FLOW_ERROR;
1732   }
1733
1734   return GST_FLOW_OK;
1735 }
1736
1737
1738 /**
1739  * gst_base_parse_chain:
1740  * @pad: #GstPad.
1741  * @buffer: #GstBuffer.
1742  *
1743  * Returns: #GstFlowReturn.
1744  */
1745 static GstFlowReturn
1746 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
1747 {
1748   GstBaseParseClass *bclass;
1749   GstBaseParse *parse;
1750   GstFlowReturn ret = GST_FLOW_OK;
1751   GstBuffer *outbuf = NULL;
1752   GstBuffer *tmpbuf = NULL;
1753   guint fsize = 0;
1754   gint skip = -1;
1755   const guint8 *data;
1756   guint min_size;
1757   GstClockTime timestamp;
1758
1759   parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
1760   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1761
1762   if (G_LIKELY (buffer)) {
1763     GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
1764         GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
1765     if (G_UNLIKELY (parse->priv->passthrough)) {
1766       buffer = gst_buffer_make_metadata_writable (buffer);
1767       return gst_base_parse_push_buffer (parse, buffer);
1768     }
1769     /* upstream feeding us in reverse playback;
1770      * gather each fragment, then process it in single run */
1771     if (parse->segment.rate < 0.0) {
1772       if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT))) {
1773         GST_DEBUG_OBJECT (parse, "buffer starts new reverse playback fragment");
1774         ret = gst_base_parse_process_fragment (parse, FALSE);
1775       }
1776       gst_adapter_push (parse->adapter, buffer);
1777       return ret;
1778     }
1779     gst_adapter_push (parse->adapter, buffer);
1780   }
1781
1782   /* Parse and push as many frames as possible */
1783   /* Stop either when adapter is empty or we are flushing */
1784   while (!parse->priv->flushing) {
1785     tmpbuf = gst_buffer_new ();
1786
1787     /* Synchronization loop */
1788     for (;;) {
1789       GST_BASE_PARSE_LOCK (parse);
1790       min_size = parse->priv->min_frame_size;
1791       GST_BASE_PARSE_UNLOCK (parse);
1792
1793       if (G_UNLIKELY (parse->priv->drain)) {
1794         min_size = gst_adapter_available (parse->adapter);
1795         GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
1796         if (G_UNLIKELY (!min_size)) {
1797           gst_buffer_unref (tmpbuf);
1798           goto done;
1799         }
1800       }
1801
1802       /* Collect at least min_frame_size bytes */
1803       if (gst_adapter_available (parse->adapter) < min_size) {
1804         GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
1805             gst_adapter_available (parse->adapter));
1806         gst_buffer_unref (tmpbuf);
1807         goto done;
1808       }
1809
1810       data = gst_adapter_peek (parse->adapter, min_size);
1811       GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
1812       GST_BUFFER_SIZE (tmpbuf) = min_size;
1813       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
1814       GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
1815
1816       if (parse->priv->discont) {
1817         GST_DEBUG_OBJECT (parse, "marking DISCONT");
1818         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1819       }
1820
1821       skip = -1;
1822       if (bclass->check_valid_frame (parse, tmpbuf, &fsize, &skip)) {
1823         if (gst_adapter_available (parse->adapter) < fsize) {
1824           GST_DEBUG_OBJECT (parse,
1825               "found valid frame but not enough data available (only %d bytes)",
1826               gst_adapter_available (parse->adapter));
1827           gst_buffer_unref (tmpbuf);
1828           goto done;
1829         }
1830         break;
1831       }
1832       if (skip == -1) {
1833         /* subclass didn't touch this value. By default we skip 1 byte */
1834         skip = 1;
1835       }
1836       if (skip > 0) {
1837         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
1838         if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
1839           /* reverse playback, and no frames found yet, so we are skipping
1840            * the leading part of a fragment, which may form the tail of
1841            * fragment coming later, hopefully subclass skips efficiently ... */
1842           timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
1843           outbuf = gst_adapter_take_buffer (parse->adapter, skip);
1844           outbuf = gst_buffer_make_metadata_writable (outbuf);
1845           GST_BUFFER_TIMESTAMP (outbuf) = timestamp;
1846           parse->priv->buffers_pending =
1847               g_slist_prepend (parse->priv->buffers_pending, outbuf);
1848           outbuf = NULL;
1849         } else {
1850           gst_adapter_flush (parse->adapter, skip);
1851         }
1852         parse->priv->offset += skip;
1853         if (!parse->priv->discont)
1854           parse->priv->sync_offset = parse->priv->offset;
1855         parse->priv->discont = TRUE;
1856       }
1857       /* There is a possibility that subclass set the skip value to zero.
1858          This means that it has probably found a frame but wants to ask
1859          more data (by increasing the min_size) to be sure of this. */
1860       if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
1861         gst_buffer_unref (tmpbuf);
1862         goto done;
1863       }
1864     }
1865     gst_buffer_unref (tmpbuf);
1866     tmpbuf = NULL;
1867
1868     if (skip > 0) {
1869       /* Subclass found the sync, but still wants to skip some data */
1870       GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
1871       gst_adapter_flush (parse->adapter, skip);
1872       parse->priv->offset += skip;
1873     }
1874
1875     /* Grab lock to prevent a race with FLUSH_START handler */
1876     GST_PAD_STREAM_LOCK (parse->srcpad);
1877
1878     /* FLUSH_START event causes the "flushing" flag to be set. In this
1879      * case we can leave the frame pushing loop */
1880     if (parse->priv->flushing) {
1881       GST_PAD_STREAM_UNLOCK (parse->srcpad);
1882       break;
1883     }
1884
1885     /* FIXME: Would it be more efficient to make a subbuffer instead? */
1886     outbuf = gst_adapter_take_buffer (parse->adapter, fsize);
1887     outbuf = gst_buffer_make_metadata_writable (outbuf);
1888
1889     /* Subclass may want to know the data offset */
1890     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
1891     parse->priv->offset += fsize;
1892
1893     /* move along with upstream timestamp (if any),
1894      * but interpolate in between */
1895     timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
1896     if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
1897         (parse->priv->prev_ts != timestamp)) {
1898       parse->priv->prev_ts = parse->priv->next_ts = timestamp;
1899     }
1900
1901     ret = gst_base_parse_handle_and_push_buffer (parse, bclass, outbuf);
1902     GST_PAD_STREAM_UNLOCK (parse->srcpad);
1903
1904     if (ret != GST_FLOW_OK) {
1905       GST_LOG_OBJECT (parse, "push returned %d", ret);
1906       break;
1907     }
1908   }
1909
1910 done:
1911   GST_LOG_OBJECT (parse, "chain leaving");
1912   return ret;
1913 }
1914
1915 /* pull @size bytes at current offset,
1916  * i.e. at least try to and possibly return a shorter buffer if near the end */
1917 static GstFlowReturn
1918 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
1919     GstBuffer ** buffer)
1920 {
1921   GstFlowReturn ret = GST_FLOW_OK;
1922
1923   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1924
1925   /* Caching here actually makes much less difference than one would expect.
1926    * We do it mainly to avoid pulling buffers of 1 byte all the time */
1927   if (parse->priv->cache) {
1928     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
1929     gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
1930
1931     if (cache_offset <= parse->priv->offset &&
1932         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
1933       *buffer = gst_buffer_create_sub (parse->priv->cache,
1934           parse->priv->offset - cache_offset, size);
1935       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1936       return GST_FLOW_OK;
1937     }
1938     /* not enough data in the cache, free cache and get a new one */
1939     gst_buffer_unref (parse->priv->cache);
1940     parse->priv->cache = NULL;
1941   }
1942
1943   /* refill the cache */
1944   ret =
1945       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
1946           64 * 1024), &parse->priv->cache);
1947   if (ret != GST_FLOW_OK) {
1948     parse->priv->cache = NULL;
1949     return ret;
1950   }
1951
1952   if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
1953     *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
1954     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1955     return GST_FLOW_OK;
1956   }
1957
1958   /* Not possible to get enough data, try a last time with
1959    * requesting exactly the size we need */
1960   gst_buffer_unref (parse->priv->cache);
1961   parse->priv->cache = NULL;
1962
1963   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
1964       &parse->priv->cache);
1965
1966   if (ret != GST_FLOW_OK) {
1967     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
1968     *buffer = NULL;
1969     return ret;
1970   }
1971
1972   if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
1973     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
1974         G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
1975         size, GST_BUFFER_SIZE (parse->priv->cache));
1976
1977     *buffer = parse->priv->cache;
1978     parse->priv->cache = NULL;
1979
1980     return GST_FLOW_OK;
1981   }
1982
1983   *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
1984   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1985
1986   return GST_FLOW_OK;
1987 }
1988
1989 static GstFlowReturn
1990 gst_base_parse_handle_previous_fragment (GstBaseParse * parse)
1991 {
1992   gint64 offset = 0;
1993   GstClockTime ts = 0;
1994   GstBuffer *buffer;
1995   GstFlowReturn ret;
1996
1997   GST_DEBUG_OBJECT (parse, "fragment ended; last_ts = %" GST_TIME_FORMAT
1998       ", last_offset = %" G_GINT64_FORMAT, GST_TIME_ARGS (parse->priv->last_ts),
1999       parse->priv->last_offset);
2000
2001   if (!parse->priv->last_offset || parse->priv->last_ts <= parse->segment.start) {
2002     GST_DEBUG_OBJECT (parse, "past start of segment %" GST_TIME_FORMAT,
2003         GST_TIME_ARGS (parse->segment.start));
2004     ret = GST_FLOW_UNEXPECTED;
2005     goto exit;
2006   }
2007
2008   /* last fragment started at last_offset / last_ts;
2009    * seek back 10s capped at 1MB */
2010   if (parse->priv->last_ts >= 10 * GST_SECOND)
2011     ts = parse->priv->last_ts - 10 * GST_SECOND;
2012   /* if we are exact now, we will be more so going backwards */
2013   if (parse->priv->exact_position) {
2014     offset = gst_base_parse_find_offset (parse, ts, TRUE, NULL);
2015   } else {
2016     GstFormat dstformat = GST_FORMAT_BYTES;
2017
2018     if (!gst_pad_query_convert (parse->srcpad, GST_FORMAT_TIME, ts,
2019             &dstformat, &offset)) {
2020       GST_DEBUG_OBJECT (parse, "conversion failed, only BYTE based");
2021     }
2022   }
2023   offset = CLAMP (offset, parse->priv->last_offset - 1024 * 1024,
2024       parse->priv->last_offset - 1024);
2025   offset = MAX (0, offset);
2026
2027   GST_DEBUG_OBJECT (parse, "next fragment from offset %" G_GINT64_FORMAT,
2028       offset);
2029   parse->priv->offset = offset;
2030
2031   ret = gst_base_parse_pull_range (parse, parse->priv->last_offset - offset,
2032       &buffer);
2033   if (ret != GST_FLOW_OK)
2034     goto exit;
2035
2036   gst_adapter_push (parse->adapter, buffer);
2037   ret = gst_base_parse_process_fragment (parse, FALSE);
2038   if (ret != GST_FLOW_OK)
2039     goto exit;
2040
2041 exit:
2042   return ret;
2043 }
2044
2045 /**
2046  * gst_base_parse_loop:
2047  * @pad: GstPad
2048  *
2049  * Loop that is used in pull mode to retrieve data from upstream.
2050  */
2051 static void
2052 gst_base_parse_loop (GstPad * pad)
2053 {
2054   GstBaseParse *parse;
2055   GstBaseParseClass *klass;
2056   GstBuffer *buffer, *outbuf;
2057   GstFlowReturn ret = FALSE;
2058   guint fsize = 0, min_size;
2059   gint skip = 0;
2060
2061   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2062   klass = GST_BASE_PARSE_GET_CLASS (parse);
2063
2064   /* reverse playback:
2065    * first fragment (closest to stop time) is handled normally below,
2066    * then we pull in fragments going backwards */
2067   if (parse->segment.rate < 0.0) {
2068     if (GST_CLOCK_TIME_IS_VALID (parse->priv->last_ts)) {
2069       ret = gst_base_parse_handle_previous_fragment (parse);
2070       goto done;
2071     }
2072   }
2073
2074   while (TRUE) {
2075
2076     GST_BASE_PARSE_LOCK (parse);
2077     min_size = parse->priv->min_frame_size;
2078     GST_BASE_PARSE_UNLOCK (parse);
2079
2080     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
2081     if (ret != GST_FLOW_OK)
2082       goto done;
2083
2084     if (parse->priv->discont) {
2085       GST_DEBUG_OBJECT (parse, "marking DISCONT");
2086       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
2087     }
2088
2089     /* if we got a short read, inform subclass we are draining leftover
2090      * and no more is to be expected */
2091     if (GST_BUFFER_SIZE (buffer) < min_size)
2092       parse->priv->drain = TRUE;
2093
2094     skip = -1;
2095     if (klass->check_valid_frame (parse, buffer, &fsize, &skip)) {
2096       parse->priv->drain = FALSE;
2097       break;
2098     }
2099     parse->priv->drain = FALSE;
2100     if (skip == -1)
2101       skip = 1;
2102     if (skip > 0) {
2103       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
2104       if (parse->segment.rate < 0.0 && !parse->priv->buffers_queued) {
2105         /* reverse playback, and no frames found yet, so we are skipping
2106          * the leading part of a fragment, which may form the tail of
2107          * fragment coming later, hopefully subclass skips efficiently ... */
2108         outbuf = gst_buffer_create_sub (buffer, 0, skip);
2109         parse->priv->buffers_pending =
2110             g_slist_prepend (parse->priv->buffers_pending, outbuf);
2111         outbuf = NULL;
2112       }
2113       parse->priv->offset += skip;
2114       if (!parse->priv->discont)
2115         parse->priv->sync_offset = parse->priv->offset;
2116       parse->priv->discont = TRUE;
2117     }
2118     /* skip == 0 should imply subclass set min_size to need more data ... */
2119     GST_DEBUG_OBJECT (parse, "finding sync...");
2120     gst_buffer_unref (buffer);
2121     if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
2122       goto done;
2123     }
2124   }
2125
2126   if (fsize <= GST_BUFFER_SIZE (buffer)) {
2127     outbuf = gst_buffer_create_sub (buffer, 0, fsize);
2128     GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer);
2129     gst_buffer_unref (buffer);
2130   } else {
2131     gst_buffer_unref (buffer);
2132     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
2133     if (ret != GST_FLOW_OK)
2134       goto done;
2135     if (GST_BUFFER_SIZE (outbuf) < fsize)
2136       goto eos;
2137   }
2138
2139   parse->priv->offset += fsize;
2140
2141   /* Does the subclass want to skip too? */
2142   if (skip > 0)
2143     parse->priv->offset += skip;
2144
2145   /* This always unrefs the outbuf, even if error occurs */
2146   ret = gst_base_parse_handle_and_push_buffer (parse, klass, outbuf);
2147
2148   /* eat expected eos signalling past segment in reverse playback */
2149   if (parse->segment.rate < 0.0 && ret == GST_FLOW_UNEXPECTED &&
2150       parse->segment.last_stop >= parse->segment.stop) {
2151     GST_DEBUG_OBJECT (parse, "downstream has reached end of segment");
2152     /* push what was accumulated during loop run */
2153     gst_base_parse_process_fragment (parse, TRUE);
2154     ret = GST_FLOW_OK;
2155   }
2156
2157 done:
2158   if (ret == GST_FLOW_UNEXPECTED)
2159     goto eos;
2160   else if (ret != GST_FLOW_OK)
2161     goto pause;
2162
2163   gst_object_unref (parse);
2164   return;
2165
2166   /* ERRORS */
2167 eos:
2168   {
2169     ret = GST_FLOW_UNEXPECTED;
2170     GST_DEBUG_OBJECT (parse, "eos");
2171     /* fall-through */
2172   }
2173 pause:
2174   {
2175     gboolean push_eos = FALSE;
2176
2177     GST_DEBUG_OBJECT (parse, "pausing task, reason %s",
2178         gst_flow_get_name (ret));
2179     gst_pad_pause_task (parse->sinkpad);
2180
2181     if (ret == GST_FLOW_UNEXPECTED) {
2182       /* handle end-of-stream/segment */
2183       if (parse->segment.flags & GST_SEEK_FLAG_SEGMENT) {
2184         gint64 stop;
2185
2186         if ((stop = parse->segment.stop) == -1)
2187           stop = parse->segment.duration;
2188
2189         GST_DEBUG_OBJECT (parse, "sending segment_done");
2190
2191         gst_element_post_message
2192             (GST_ELEMENT_CAST (parse),
2193             gst_message_new_segment_done (GST_OBJECT_CAST (parse),
2194                 GST_FORMAT_TIME, stop));
2195       } else {
2196         /* If we STILL have zero frames processed, fire an error */
2197         if (parse->priv->framecount == 0) {
2198           GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
2199               ("No valid frames found before end of stream"), (NULL));
2200         }
2201         push_eos = TRUE;
2202       }
2203     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
2204       /* for fatal errors we post an error message, wrong-state is
2205        * not fatal because it happens due to flushes and only means
2206        * that we should stop now. */
2207       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
2208           ("streaming stopped, reason %s", gst_flow_get_name (ret)));
2209       push_eos = TRUE;
2210     }
2211     if (push_eos) {
2212       /* newsegment before eos */
2213       if (parse->pending_segment) {
2214         gst_pad_push_event (parse->srcpad, parse->pending_segment);
2215         parse->pending_segment = NULL;
2216       }
2217       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
2218     }
2219     gst_object_unref (parse);
2220   }
2221 }
2222
2223
2224 /**
2225  * gst_base_parse_sink_activate:
2226  * @sinkpad: #GstPad to be activated.
2227  *
2228  * Returns: TRUE if activation succeeded.
2229  */
2230 static gboolean
2231 gst_base_parse_sink_activate (GstPad * sinkpad)
2232 {
2233   GstBaseParse *parse;
2234   gboolean result = TRUE;
2235
2236   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2237
2238   GST_DEBUG_OBJECT (parse, "sink activate");
2239
2240   if (gst_pad_check_pull_range (sinkpad)) {
2241     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
2242     result = gst_pad_activate_pull (sinkpad, TRUE);
2243   } else {
2244     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
2245     result = gst_pad_activate_push (sinkpad, TRUE);
2246   }
2247
2248   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
2249   gst_object_unref (parse);
2250   return result;
2251 }
2252
2253
2254 /**
2255  * gst_base_parse_activate:
2256  * @parse: #GstBaseParse.
2257  * @active: TRUE if element will be activated, FALSE if disactivated.
2258  *
2259  * Returns: TRUE if the operation succeeded.
2260  */
2261 static gboolean
2262 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
2263 {
2264   GstBaseParseClass *klass;
2265   gboolean result = FALSE;
2266
2267   GST_DEBUG_OBJECT (parse, "activate");
2268
2269   klass = GST_BASE_PARSE_GET_CLASS (parse);
2270
2271   if (active) {
2272     if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
2273       result = klass->start (parse);
2274   } else {
2275     /* We must make sure streaming has finished before resetting things
2276      * and calling the ::stop vfunc */
2277     GST_PAD_STREAM_LOCK (parse->sinkpad);
2278     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2279
2280     if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
2281       result = klass->stop (parse);
2282
2283     parse->priv->pad_mode = GST_ACTIVATE_NONE;
2284   }
2285   GST_DEBUG_OBJECT (parse, "activate: %d", result);
2286   return result;
2287 }
2288
2289
2290 /**
2291  * gst_base_parse_sink_activate_push:
2292  * @pad: #GstPad to be (de)activated.
2293  * @active: TRUE when activating, FALSE when deactivating.
2294  *
2295  * Returns: TRUE if (de)activation succeeded.
2296  */
2297 static gboolean
2298 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
2299 {
2300   gboolean result = TRUE;
2301   GstBaseParse *parse;
2302
2303   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
2304
2305   GST_DEBUG_OBJECT (parse, "sink activate push");
2306
2307   result = gst_base_parse_activate (parse, active);
2308
2309   if (result)
2310     parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
2311
2312   GST_DEBUG_OBJECT (parse, "sink activate push: %d", result);
2313
2314   gst_object_unref (parse);
2315   return result;
2316 }
2317
2318
2319 /**
2320  * gst_base_parse_sink_activate_pull:
2321  * @sinkpad: #GstPad to be (de)activated.
2322  * @active: TRUE when activating, FALSE when deactivating.
2323  *
2324  * Returns: TRUE if (de)activation succeeded.
2325  */
2326 static gboolean
2327 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
2328 {
2329   gboolean result = FALSE;
2330   GstBaseParse *parse;
2331
2332   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
2333
2334   GST_DEBUG_OBJECT (parse, "activate pull");
2335
2336   result = gst_base_parse_activate (parse, active);
2337
2338   if (result) {
2339     if (active) {
2340       parse->pending_segment = gst_event_new_new_segment (FALSE,
2341           parse->segment.rate, parse->segment.format,
2342           parse->segment.start, parse->segment.stop, parse->segment.last_stop);
2343       result &= gst_pad_start_task (sinkpad,
2344           (GstTaskFunction) gst_base_parse_loop, sinkpad);
2345     } else {
2346       result &= gst_pad_stop_task (sinkpad);
2347     }
2348   }
2349
2350   if (result)
2351     parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
2352
2353   GST_DEBUG_OBJECT (parse, "sink activate pull: %d", result);
2354
2355   gst_object_unref (parse);
2356   return result;
2357 }
2358
2359
2360 /**
2361  * gst_base_parse_set_duration:
2362  * @parse: #GstBaseParse.
2363  * @fmt: #GstFormat.
2364  * @duration: duration value.
2365  *
2366  * Sets the duration of the currently playing media. Subclass can use this
2367  * when it is able to determine duration and/or notices a change in the media
2368  * duration.  Alternatively, if @interval is non-zero (default), then stream
2369  * duration is determined based on estimated bitrate, and updated every @interval
2370  * frames. */
2371 void
2372 gst_base_parse_set_duration (GstBaseParse * parse,
2373     GstFormat fmt, gint64 duration, gint interval)
2374 {
2375   g_return_if_fail (parse != NULL);
2376
2377   GST_BASE_PARSE_LOCK (parse);
2378   if (duration != parse->priv->duration) {
2379     GstMessage *m;
2380
2381     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
2382     gst_element_post_message (GST_ELEMENT (parse), m);
2383
2384     /* TODO: what about duration tag? */
2385   }
2386   parse->priv->duration = duration;
2387   parse->priv->duration_fmt = fmt;
2388   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
2389   if (fmt == GST_FORMAT_TIME && GST_CLOCK_TIME_IS_VALID (duration)) {
2390     if (interval != 0) {
2391       GST_DEBUG_OBJECT (parse, "valid duration provided, disabling estimate");
2392       interval = 0;
2393     }
2394   }
2395   GST_DEBUG_OBJECT (parse, "set update interval: %d", interval);
2396   parse->priv->update_interval = interval;
2397   GST_BASE_PARSE_UNLOCK (parse);
2398 }
2399
2400 /**
2401  * gst_base_parse_set_seek:
2402  * @parse: #GstBaseParse.
2403  * @seek: #GstBaseParseSeekable.
2404  * @abitrate: average bitrate.
2405  *
2406  * Sets whether and how the media is seekable (in time).
2407  * Also optionally provides average bitrate detected in media (if non-zero),
2408  * e.g. based on metadata, as it will be posted to the application.
2409  *
2410  * By default, announced average bitrate is estimated, and seekability is assumed
2411  * possible based on estimated bitrate.
2412  */
2413 void
2414 gst_base_parse_set_seek (GstBaseParse * parse,
2415     GstBaseParseSeekable seek, guint bitrate)
2416 {
2417   parse->priv->seekable = seek;
2418   parse->priv->bitrate = bitrate;
2419 }
2420
2421
2422 /**
2423  * gst_base_parse_set_min_frame_size:
2424  * @parse: #GstBaseParse.
2425  * @min_size: Minimum size of the data that this base class should give to
2426  *            subclass.
2427  *
2428  * Subclass can use this function to tell the base class that it needs to
2429  * give at least #min_size buffers.
2430  */
2431 void
2432 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
2433 {
2434   g_return_if_fail (parse != NULL);
2435
2436   GST_BASE_PARSE_LOCK (parse);
2437   parse->priv->min_frame_size = min_size;
2438   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
2439   GST_BASE_PARSE_UNLOCK (parse);
2440 }
2441
2442 /**
2443  * gst_base_transform_set_passthrough:
2444  * @trans: the #GstBaseParse to set
2445  * @passthrough: boolean indicating passthrough mode.
2446  *
2447  * Set passthrough mode for this parser.  If operating in passthrough,
2448  * incoming buffers are pushed through unmodified.
2449  */
2450 void
2451 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
2452 {
2453   g_return_if_fail (parse != NULL);
2454
2455   GST_BASE_PARSE_LOCK (parse);
2456   parse->priv->passthrough = passthrough;
2457   GST_LOG_OBJECT (parse, "set passthrough: %d", passthrough);
2458   GST_BASE_PARSE_UNLOCK (parse);
2459 }
2460
2461 /**
2462  * gst_base_transform_set_frame_props:
2463  * @parse: the #GstBaseParse to set
2464  * @fps_num: frames per second (numerator).
2465  * @fps_den: frames per second (denominator).
2466  * @lead_in: frames needed before a segment for subsequent decode
2467  * @lead_out: frames needed after a segment
2468  *
2469  * If frames per second is configured, parser can take care of buffer duration
2470  * and timestamping.  When performing segment clipping, or seeking to a specific
2471  * location, a corresponding decoder might need an initial @lead_in and a
2472  * following @lead_out number of frames to ensure the desired segment is
2473  * entirely filled upon decoding.
2474  */
2475 void
2476 gst_base_parse_set_frame_props (GstBaseParse * parse, guint fps_num,
2477     guint fps_den, guint lead_in, guint lead_out)
2478 {
2479   g_return_if_fail (parse != NULL);
2480
2481   GST_BASE_PARSE_LOCK (parse);
2482   parse->priv->fps_num = fps_num;
2483   parse->priv->fps_den = fps_den;
2484   if (!fps_num || !fps_den) {
2485     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
2486         fps_num, fps_den);
2487     fps_num = fps_den = 0;
2488     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
2489     parse->priv->lead_in = parse->priv->lead_out = 0;
2490     parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
2491   } else {
2492     parse->priv->frame_duration =
2493         gst_util_uint64_scale (GST_SECOND, fps_den, fps_num);
2494     parse->priv->lead_in = lead_in;
2495     parse->priv->lead_out = lead_out;
2496     parse->priv->lead_in_ts =
2497         gst_util_uint64_scale (GST_SECOND, fps_den * lead_in, fps_num);
2498     parse->priv->lead_out_ts =
2499         gst_util_uint64_scale (GST_SECOND, fps_den * lead_out, fps_num);
2500   }
2501   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
2502       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
2503   GST_LOG_OBJECT (parse, "set lead in: %d frames = %" G_GUINT64_FORMAT " ms, "
2504       "lead out: %d frames = %" G_GUINT64_FORMAT " ms",
2505       lead_in, parse->priv->lead_in_ts / GST_MSECOND,
2506       lead_out, parse->priv->lead_out_ts / GST_MSECOND);
2507   GST_BASE_PARSE_UNLOCK (parse);
2508 }
2509
2510 /**
2511  * gst_base_transform_get_sync:
2512  * @parse: the #GstBaseParse to query
2513  *
2514  * Returns: TRUE if parser is considered 'in sync'.  That is, frames have been
2515  * continuously successfully parsed and pushed.
2516  */
2517 gboolean
2518 gst_base_parse_get_sync (GstBaseParse * parse)
2519 {
2520   gboolean ret;
2521
2522   g_return_val_if_fail (parse != NULL, FALSE);
2523
2524   GST_BASE_PARSE_LOCK (parse);
2525   /* losing sync is pretty much a discont (and vice versa), no ? */
2526   ret = !parse->priv->discont;
2527   GST_BASE_PARSE_UNLOCK (parse);
2528
2529   GST_DEBUG_OBJECT (parse, "sync: %d", ret);
2530   return ret;
2531 }
2532
2533 /**
2534  * gst_base_transform_get_drain:
2535  * @parse: the #GstBaseParse to query
2536  *
2537  * Returns: TRUE if parser is currently 'draining'.  That is, leftover data
2538  * (e.g. in FLUSH or EOS situation) is being parsed.
2539  */
2540 gboolean
2541 gst_base_parse_get_drain (GstBaseParse * parse)
2542 {
2543   gboolean ret;
2544
2545   g_return_val_if_fail (parse != NULL, FALSE);
2546
2547   GST_BASE_PARSE_LOCK (parse);
2548   /* losing sync is pretty much a discont (and vice versa), no ? */
2549   ret = parse->priv->drain;
2550   GST_BASE_PARSE_UNLOCK (parse);
2551
2552   GST_DEBUG_OBJECT (parse, "drain: %d", ret);
2553   return ret;
2554 }
2555
2556 static gboolean
2557 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
2558     GstClockTime * duration)
2559 {
2560   gboolean res = FALSE;
2561
2562   g_return_val_if_fail (duration != NULL, FALSE);
2563
2564   *duration = GST_CLOCK_TIME_NONE;
2565   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
2566     GST_LOG_OBJECT (parse, "using provided duration");
2567     *duration = parse->priv->duration;
2568     res = TRUE;
2569   } else if (parse->priv->duration != -1) {
2570     GST_LOG_OBJECT (parse, "converting provided duration");
2571     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
2572         parse->priv->duration, format, (gint64 *) duration);
2573   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
2574     GST_LOG_OBJECT (parse, "using estimated duration");
2575     *duration = parse->priv->estimated_duration;
2576     res = TRUE;
2577   }
2578
2579   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
2580       GST_TIME_ARGS (*duration));
2581   return res;
2582 }
2583
2584 /**
2585  * gst_base_parse_get_querytypes:
2586  * @pad: GstPad
2587  *
2588  * Returns: A table of #GstQueryType items describing supported query types.
2589  */
2590 static const GstQueryType *
2591 gst_base_parse_get_querytypes (GstPad * pad)
2592 {
2593   static const GstQueryType list[] = {
2594     GST_QUERY_POSITION,
2595     GST_QUERY_DURATION,
2596     GST_QUERY_FORMATS,
2597     GST_QUERY_SEEKING,
2598     GST_QUERY_CONVERT,
2599     0
2600   };
2601
2602   return list;
2603 }
2604
2605
2606 /**
2607  * gst_base_parse_query:
2608  * @pad: #GstPad.
2609  * @query: #GstQuery.
2610  *
2611  * Returns: TRUE on success.
2612  */
2613 static gboolean
2614 gst_base_parse_query (GstPad * pad, GstQuery * query)
2615 {
2616   GstBaseParse *parse;
2617   GstBaseParseClass *klass;
2618   gboolean res = FALSE;
2619
2620   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
2621   klass = GST_BASE_PARSE_GET_CLASS (parse);
2622
2623   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
2624
2625   switch (GST_QUERY_TYPE (query)) {
2626     case GST_QUERY_POSITION:
2627     {
2628       gint64 dest_value;
2629       GstFormat format;
2630
2631       GST_DEBUG_OBJECT (parse, "position query");
2632       gst_query_parse_position (query, &format, NULL);
2633
2634       g_mutex_lock (parse->parse_lock);
2635       if (format == GST_FORMAT_BYTES) {
2636         dest_value = parse->priv->offset;
2637         res = TRUE;
2638       } else if (format == parse->segment.format &&
2639           GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
2640         dest_value = parse->segment.last_stop;
2641         res = TRUE;
2642       }
2643       g_mutex_unlock (parse->parse_lock);
2644
2645       if (res)
2646         gst_query_set_position (query, format, dest_value);
2647       else {
2648         res = gst_pad_query_default (pad, query);
2649         if (!res) {
2650           /* no precise result, upstream no idea either, then best estimate */
2651           /* priv->offset is updated in both PUSH/PULL modes */
2652           g_mutex_lock (parse->parse_lock);
2653           res = gst_base_parse_convert (parse,
2654               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
2655           g_mutex_unlock (parse->parse_lock);
2656         }
2657       }
2658       break;
2659     }
2660     case GST_QUERY_DURATION:
2661     {
2662       GstFormat format;
2663       GstClockTime duration;
2664
2665       GST_DEBUG_OBJECT (parse, "duration query");
2666       gst_query_parse_duration (query, &format, NULL);
2667
2668       /* consult upstream */
2669       res = gst_pad_query_default (pad, query);
2670
2671       /* otherwise best estimate from us */
2672       if (!res) {
2673         g_mutex_lock (parse->parse_lock);
2674         res = gst_base_parse_get_duration (parse, format, &duration);
2675         g_mutex_unlock (parse->parse_lock);
2676         if (res)
2677           gst_query_set_duration (query, format, duration);
2678       }
2679       break;
2680     }
2681     case GST_QUERY_SEEKING:
2682     {
2683       GstFormat fmt;
2684       GstClockTime duration = GST_CLOCK_TIME_NONE;
2685       gboolean seekable = FALSE;
2686
2687       GST_DEBUG_OBJECT (parse, "seeking query");
2688       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
2689
2690       /* consult upstream */
2691       res = gst_pad_query_default (pad, query);
2692
2693       /* we may be able to help if in TIME */
2694       if (fmt == GST_FORMAT_TIME &&
2695           parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
2696         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
2697         /* already OK if upstream takes care */
2698         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
2699             res, seekable);
2700         if (!(res && seekable)) {
2701           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
2702               || duration == -1) {
2703             seekable = FALSE;
2704           } else {
2705             seekable = parse->priv->upstream_seekable;
2706             GST_LOG_OBJECT (parse, "already determine upstream seekabled: %d",
2707                 seekable);
2708           }
2709           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
2710           res = TRUE;
2711         }
2712       }
2713       break;
2714     }
2715     case GST_QUERY_FORMATS:
2716       gst_query_set_formatsv (query, 3, fmtlist);
2717       res = TRUE;
2718       break;
2719     case GST_QUERY_CONVERT:
2720     {
2721       GstFormat src_format, dest_format;
2722       gint64 src_value, dest_value;
2723
2724       gst_query_parse_convert (query, &src_format, &src_value,
2725           &dest_format, &dest_value);
2726
2727       res = gst_base_parse_convert (parse, src_format, src_value,
2728           dest_format, &dest_value);
2729       if (res) {
2730         gst_query_set_convert (query, src_format, src_value,
2731             dest_format, dest_value);
2732       }
2733       break;
2734     }
2735     default:
2736       res = gst_pad_query_default (pad, query);
2737       break;
2738   }
2739   return res;
2740 }
2741
2742 static gint64
2743 gst_base_parse_find_offset (GstBaseParse * parse, GstClockTime time,
2744     gboolean before, GstClockTime * _ts)
2745 {
2746   gint64 bytes = 0, ts = 0;
2747   GstIndexEntry *entry = NULL;
2748
2749   if (time == GST_CLOCK_TIME_NONE) {
2750     ts = time;
2751     bytes = -1;
2752     goto exit;
2753   }
2754
2755   GST_OBJECT_LOCK (parse);
2756   if (parse->priv->index) {
2757     /* Let's check if we have an index entry for that time */
2758     entry = gst_index_get_assoc_entry (parse->priv->index,
2759         parse->priv->index_id,
2760         before ? GST_INDEX_LOOKUP_BEFORE : GST_INDEX_LOOKUP_AFTER,
2761         GST_ASSOCIATION_FLAG_KEY_UNIT, GST_FORMAT_TIME, time);
2762   }
2763
2764   if (entry) {
2765     gst_index_entry_assoc_map (entry, GST_FORMAT_BYTES, &bytes);
2766     gst_index_entry_assoc_map (entry, GST_FORMAT_TIME, &ts);
2767
2768     GST_DEBUG_OBJECT (parse, "found index entry for %" GST_TIME_FORMAT
2769         " at %" GST_TIME_FORMAT ", offset %" G_GINT64_FORMAT,
2770         GST_TIME_ARGS (time), GST_TIME_ARGS (ts), bytes);
2771   } else {
2772     GST_DEBUG_OBJECT (parse, "no index entry found for %" GST_TIME_FORMAT,
2773         GST_TIME_ARGS (time));
2774     if (!before) {
2775       bytes = -1;
2776       ts = GST_CLOCK_TIME_NONE;
2777     }
2778   }
2779   GST_OBJECT_UNLOCK (parse);
2780
2781 exit:
2782   if (_ts)
2783     *_ts = ts;
2784
2785   return bytes;
2786 }
2787
2788
2789 /**
2790  * gst_base_parse_handle_seek:
2791  * @parse: #GstBaseParse.
2792  * @event: #GstEvent.
2793  *
2794  * Returns: TRUE if seek succeeded.
2795  */
2796 static gboolean
2797 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
2798 {
2799   GstBaseParseClass *klass;
2800   gdouble rate;
2801   GstFormat format;
2802   GstSeekFlags flags;
2803   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2804   gboolean flush, update, res = TRUE, accurate;
2805   gint64 cur, stop, seekpos, seekstop;
2806   GstSegment seeksegment = { 0, };
2807   GstFormat dstformat;
2808   GstClockTime start_ts;
2809
2810   klass = GST_BASE_PARSE_GET_CLASS (parse);
2811
2812   gst_event_parse_seek (event, &rate, &format, &flags,
2813       &cur_type, &cur, &stop_type, &stop);
2814
2815   GST_DEBUG_OBJECT (parse, "seek to format %s, rate %f, "
2816       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
2817       GST_TIME_FORMAT, gst_format_get_name (format), rate,
2818       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
2819
2820   /* no negative rates yet */
2821   if (rate < 0.0 && parse->priv->pad_mode == GST_ACTIVATE_PUSH)
2822     goto negative_rate;
2823
2824   if (cur_type != GST_SEEK_TYPE_SET ||
2825       (stop_type != GST_SEEK_TYPE_SET && stop_type != GST_SEEK_TYPE_NONE))
2826     goto wrong_type;
2827
2828   /* For any format other than TIME, see if upstream handles
2829    * it directly or fail. For TIME, try upstream, but do it ourselves if
2830    * it fails upstream */
2831   if (format != GST_FORMAT_TIME) {
2832     /* default action delegates to upstream */
2833     return FALSE;
2834   } else {
2835     gst_event_ref (event);
2836     if (gst_pad_push_event (parse->sinkpad, event)) {
2837       return TRUE;
2838     }
2839   }
2840
2841   /* get flush flag */
2842   flush = flags & GST_SEEK_FLAG_FLUSH;
2843
2844   /* copy segment, we need this because we still need the old
2845    * segment when we close the current segment. */
2846   memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
2847
2848   GST_DEBUG_OBJECT (parse, "configuring seek");
2849   gst_segment_set_seek (&seeksegment, rate, format, flags,
2850       cur_type, cur, stop_type, stop, &update);
2851
2852   /* accurate seeking implies seek tables are used to obtain position,
2853    * and the requested segment is maintained exactly, not adjusted any way */
2854   accurate = flags & GST_SEEK_FLAG_ACCURATE;
2855
2856   /* maybe we can be accurate for (almost) free */
2857   if (seeksegment.last_stop <= parse->priv->index_last_ts + 20 * GST_SECOND) {
2858     GST_DEBUG_OBJECT (parse,
2859         "seek position %" GST_TIME_FORMAT " <= %" GST_TIME_FORMAT
2860         "accurate seek possible", GST_TIME_ARGS (seeksegment.last_stop),
2861         GST_TIME_ARGS (parse->priv->index_last_ts));
2862     accurate = TRUE;
2863   }
2864   if (accurate) {
2865     GstClockTime startpos = seeksegment.last_stop;
2866
2867     /* accurate requested, so ... seek a bit before target */
2868     if (startpos < parse->priv->lead_in_ts)
2869       startpos = 0;
2870     else
2871       startpos -= parse->priv->lead_in_ts;
2872     seekpos = gst_base_parse_find_offset (parse, startpos, TRUE, &start_ts);
2873     seekstop = gst_base_parse_find_offset (parse, seeksegment.stop, FALSE,
2874         NULL);
2875   } else {
2876     start_ts = seeksegment.last_stop;
2877     dstformat = GST_FORMAT_BYTES;
2878     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
2879             &dstformat, &seekpos))
2880       goto convert_failed;
2881     if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.stop,
2882             &dstformat, &seekstop))
2883       goto convert_failed;
2884   }
2885
2886   GST_DEBUG_OBJECT (parse,
2887       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
2888       start_ts, seekpos);
2889   GST_DEBUG_OBJECT (parse,
2890       "seek stop %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT,
2891       seeksegment.stop, seekstop);
2892
2893   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
2894     gint64 last_stop;
2895
2896     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
2897
2898     if (flush) {
2899       if (parse->srcpad) {
2900         GST_DEBUG_OBJECT (parse, "sending flush start");
2901         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
2902       }
2903     } else {
2904       gst_pad_pause_task (parse->sinkpad);
2905     }
2906
2907     /* we should now be able to grab the streaming thread because we stopped it
2908      * with the above flush/pause code */
2909     GST_PAD_STREAM_LOCK (parse->sinkpad);
2910
2911     /* save current position */
2912     last_stop = parse->segment.last_stop;
2913     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
2914         last_stop);
2915
2916     /* now commit to new position */
2917
2918     /* prepare for streaming again */
2919     if (flush) {
2920       GST_DEBUG_OBJECT (parse, "sending flush stop");
2921       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
2922       gst_base_parse_clear_queues (parse);
2923     } else {
2924       if (parse->close_segment)
2925         gst_event_unref (parse->close_segment);
2926
2927       parse->close_segment = gst_event_new_new_segment (TRUE,
2928           parse->segment.rate, parse->segment.format,
2929           parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
2930
2931       /* keep track of our last_stop */
2932       seeksegment.accum = parse->segment.last_stop;
2933
2934       GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
2935           "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
2936           ", pos = %" GST_TIME_FORMAT, format,
2937           GST_TIME_ARGS (parse->segment.accum),
2938           GST_TIME_ARGS (parse->segment.last_stop),
2939           GST_TIME_ARGS (parse->segment.accum));
2940     }
2941
2942     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
2943
2944     /* store the newsegment event so it can be sent from the streaming thread. */
2945     if (parse->pending_segment)
2946       gst_event_unref (parse->pending_segment);
2947
2948     /* This will be sent later in _loop() */
2949     parse->pending_segment =
2950         gst_event_new_new_segment (FALSE, parse->segment.rate,
2951         parse->segment.format, parse->segment.start, parse->segment.stop,
2952         parse->segment.start);
2953
2954     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
2955         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
2956         ", pos = %" GST_TIME_FORMAT, format,
2957         GST_TIME_ARGS (parse->segment.start),
2958         GST_TIME_ARGS (parse->segment.stop),
2959         GST_TIME_ARGS (parse->segment.start));
2960
2961     /* mark discont if we are going to stream from another position. */
2962     if (seekpos != parse->priv->offset) {
2963       GST_DEBUG_OBJECT (parse,
2964           "mark DISCONT, we did a seek to another position");
2965       parse->priv->offset = seekpos;
2966       parse->priv->last_offset = seekpos;
2967       parse->priv->discont = TRUE;
2968       parse->priv->next_ts = start_ts;
2969       parse->priv->last_ts = GST_CLOCK_TIME_NONE;
2970       parse->priv->sync_offset = seekpos;
2971       parse->priv->exact_position = accurate;
2972     }
2973
2974     /* Start streaming thread if paused */
2975     gst_pad_start_task (parse->sinkpad,
2976         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
2977
2978     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2979   } else {
2980     GstEvent *new_event;
2981     GstBaseParseSeek *seek;
2982
2983     /* The only thing we need to do in PUSH-mode is to send the
2984        seek event (in bytes) to upstream. Segment / flush handling happens
2985        in corresponding src event handlers */
2986     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
2987     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
2988         GST_SEEK_TYPE_SET, seekpos, stop_type, seekstop);
2989
2990     /* store segment info so its precise details can be reconstructed when
2991      * receiving newsegment;
2992      * this matters for all details when accurate seeking,
2993      * is most useful to preserve NONE stop time otherwise */
2994     seek = g_new0 (GstBaseParseSeek, 1);
2995     seek->segment = seeksegment;
2996     seek->accurate = accurate;
2997     seek->offset = seekpos;
2998     seek->start_ts = start_ts;
2999     GST_OBJECT_LOCK (parse);
3000     /* less optimal, but preserves order */
3001     parse->priv->pending_seeks =
3002         g_slist_append (parse->priv->pending_seeks, seek);
3003     GST_OBJECT_UNLOCK (parse);
3004
3005     res = gst_pad_push_event (parse->sinkpad, new_event);
3006
3007     if (!res) {
3008       GST_OBJECT_LOCK (parse);
3009       parse->priv->pending_seeks =
3010           g_slist_remove (parse->priv->pending_seeks, seek);
3011       GST_OBJECT_UNLOCK (parse);
3012       g_free (seek);
3013     }
3014   }
3015
3016 done:
3017   return res;
3018
3019   /* ERRORS */
3020 negative_rate:
3021   {
3022     GST_DEBUG_OBJECT (parse, "negative playback rates are not supported yet.");
3023     res = FALSE;
3024     goto done;
3025   }
3026 wrong_type:
3027   {
3028     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
3029     res = FALSE;
3030     goto done;
3031   }
3032 convert_failed:
3033   {
3034     GST_DEBUG_OBJECT (parse, "conversion TIME to BYTES failed.");
3035     res = FALSE;
3036     goto done;
3037   }
3038 }
3039
3040 /**
3041  * gst_base_parse_handle_tag:
3042  * @parse: #GstBaseParse.
3043  * @event: #GstEvent.
3044  *
3045  * Checks if bitrates are available from upstream tags so that we don't
3046  * override them later
3047  */
3048 static void
3049 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
3050 {
3051   GstTagList *taglist = NULL;
3052   guint tmp;
3053
3054   gst_event_parse_tag (event, &taglist);
3055
3056   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp))
3057     parse->priv->post_min_bitrate = FALSE;
3058   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp))
3059     parse->priv->post_avg_bitrate = FALSE;
3060   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp))
3061     parse->priv->post_max_bitrate = FALSE;
3062 }
3063
3064 /**
3065  * gst_base_parse_sink_setcaps:
3066  * @pad: #GstPad.
3067  * @caps: #GstCaps.
3068  *
3069  * Returns: TRUE if caps were accepted.
3070  */
3071 static gboolean
3072 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
3073 {
3074   GstBaseParse *parse;
3075   GstBaseParseClass *klass;
3076   gboolean res = TRUE;
3077
3078   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
3079   klass = GST_BASE_PARSE_GET_CLASS (parse);
3080
3081   GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
3082
3083   if (klass->set_sink_caps)
3084     res = klass->set_sink_caps (parse, caps);
3085
3086   return res && gst_pad_set_caps (pad, caps);
3087 }
3088
3089 static void
3090 gst_base_parse_set_index (GstElement * element, GstIndex * index)
3091 {
3092   GstBaseParse *parse = GST_BASE_PARSE (element);
3093
3094   GST_OBJECT_LOCK (parse);
3095   if (parse->priv->index)
3096     gst_object_unref (parse->priv->index);
3097   if (index) {
3098     parse->priv->index = gst_object_ref (index);
3099     gst_index_get_writer_id (index, GST_OBJECT (element),
3100         &parse->priv->index_id);
3101     parse->priv->own_index = FALSE;
3102   } else
3103     parse->priv->index = NULL;
3104   GST_OBJECT_UNLOCK (parse);
3105 }
3106
3107 static GstIndex *
3108 gst_base_parse_get_index (GstElement * element)
3109 {
3110   GstBaseParse *parse = GST_BASE_PARSE (element);
3111   GstIndex *result = NULL;
3112
3113   GST_OBJECT_LOCK (parse);
3114   if (parse->priv->index)
3115     result = gst_object_ref (parse->priv->index);
3116   GST_OBJECT_UNLOCK (parse);
3117
3118   return result;
3119 }
3120
3121 static GstStateChangeReturn
3122 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
3123 {
3124   GstBaseParse *parse;
3125   GstStateChangeReturn result;
3126
3127   parse = GST_BASE_PARSE (element);
3128
3129   switch (transition) {
3130     case GST_STATE_CHANGE_READY_TO_PAUSED:
3131       /* If this is our own index destroy it as the
3132        * old entries might be wrong for the new stream */
3133       if (parse->priv->own_index) {
3134         gst_object_unref (parse->priv->index);
3135         parse->priv->index = NULL;
3136         parse->priv->own_index = FALSE;
3137       }
3138
3139       /* If no index was created, generate one */
3140       if (G_UNLIKELY (!parse->priv->index)) {
3141         GST_DEBUG_OBJECT (parse, "no index provided creating our own");
3142
3143         parse->priv->index = gst_index_factory_make ("memindex");
3144         gst_index_get_writer_id (parse->priv->index, GST_OBJECT (parse),
3145             &parse->priv->index_id);
3146         parse->priv->own_index = TRUE;
3147       }
3148       break;
3149     default:
3150       break;
3151   }
3152
3153   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3154
3155   switch (transition) {
3156     case GST_STATE_CHANGE_PAUSED_TO_READY:
3157       gst_base_parse_reset (parse);
3158       break;
3159     default:
3160       break;
3161   }
3162
3163   return result;
3164 }