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