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