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