baseparse: refactor state reset
[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   GstBaseParseSeekable seekable;
223
224   gboolean discont;
225   gboolean flushing;
226   gboolean drain;
227
228   gint64 offset;
229   gint64 sync_offset;
230   GstClockTime next_ts;
231   GstClockTime prev_ts;
232   GstClockTime frame_duration;
233
234   guint64 framecount;
235   guint64 bytecount;
236   guint64 data_bytecount;
237   guint64 acc_duration;
238
239   gboolean post_min_bitrate;
240   gboolean post_avg_bitrate;
241   gboolean post_max_bitrate;
242   guint min_bitrate;
243   guint avg_bitrate;
244   guint max_bitrate;
245   guint posted_avg_bitrate;
246
247   GList *pending_events;
248
249   GstBuffer *cache;
250 };
251
252 static GstElementClass *parent_class = NULL;
253
254 static void gst_base_parse_class_init (GstBaseParseClass * klass);
255 static void gst_base_parse_init (GstBaseParse * parse,
256     GstBaseParseClass * klass);
257
258 GType
259 gst_base_parse_get_type (void)
260 {
261   static GType base_parse_type = 0;
262
263   if (!base_parse_type) {
264     static const GTypeInfo base_parse_info = {
265       sizeof (GstBaseParseClass),
266       (GBaseInitFunc) NULL,
267       (GBaseFinalizeFunc) NULL,
268       (GClassInitFunc) gst_base_parse_class_init,
269       NULL,
270       NULL,
271       sizeof (GstBaseParse),
272       0,
273       (GInstanceInitFunc) gst_base_parse_init,
274     };
275
276     base_parse_type = g_type_register_static (GST_TYPE_ELEMENT,
277         "GstAudioBaseParseBad", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
278   }
279   return base_parse_type;
280 }
281
282 static void gst_base_parse_finalize (GObject * object);
283
284 static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
285     GstStateChange transition);
286 static void gst_base_parse_reset (GstBaseParse * parse);
287
288 static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
289 static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
290     gboolean active);
291 static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
292     gboolean active);
293 static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
294     GstEvent * event);
295 static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
296
297 static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
298 static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
299 static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
300 static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
301 static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);
302
303 static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
304 static void gst_base_parse_loop (GstPad * pad);
305
306 static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
307     GstBuffer * buffer, guint * framesize, gint * skipsize);
308
309 static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
310     GstBuffer * buffer);
311
312 static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
313     GstEvent * event);
314
315 static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
316     GstEvent * event);
317
318 static void gst_base_parse_drain (GstBaseParse * parse);
319
320 static void gst_base_parse_post_bitrates (GstBaseParse * parse,
321     gboolean post_min, gboolean post_avg, gboolean post_max);
322
323 static void
324 gst_base_parse_finalize (GObject * object)
325 {
326   GstBaseParse *parse = GST_BASE_PARSE (object);
327   GstEvent **p_ev;
328
329   g_mutex_free (parse->parse_lock);
330   g_object_unref (parse->adapter);
331
332   if (parse->pending_segment) {
333     p_ev = &parse->pending_segment;
334     gst_event_replace (p_ev, NULL);
335   }
336   if (parse->close_segment) {
337     p_ev = &parse->close_segment;
338     gst_event_replace (p_ev, NULL);
339   }
340
341   if (parse->priv->cache) {
342     gst_buffer_unref (parse->priv->cache);
343     parse->priv->cache = NULL;
344   }
345
346   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
347       NULL);
348   g_list_free (parse->priv->pending_events);
349   parse->priv->pending_events = NULL;
350
351   G_OBJECT_CLASS (parent_class)->finalize (object);
352 }
353
354 static void
355 gst_base_parse_class_init (GstBaseParseClass * klass)
356 {
357   GObjectClass *gobject_class;
358   GstElementClass *gstelement_class;
359
360   gobject_class = G_OBJECT_CLASS (klass);
361   g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
362   parent_class = g_type_class_peek_parent (klass);
363   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);
364
365   gstelement_class = (GstElementClass *) klass;
366   gstelement_class->change_state =
367       GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
368
369   /* Default handlers */
370   klass->check_valid_frame = gst_base_parse_check_frame;
371   klass->parse_frame = gst_base_parse_parse_frame;
372   klass->src_event = gst_base_parse_src_eventfunc;
373   klass->convert = gst_base_parse_convert_default;
374
375   GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
376       "baseparse element");
377 }
378
379 static void
380 gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
381 {
382   GstPadTemplate *pad_template;
383
384   GST_DEBUG_OBJECT (parse, "gst_base_parse_init");
385
386   parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);
387
388   pad_template =
389       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
390   g_return_if_fail (pad_template != NULL);
391   parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
392   gst_pad_set_event_function (parse->sinkpad,
393       GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
394   gst_pad_set_setcaps_function (parse->sinkpad,
395       GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
396   gst_pad_set_chain_function (parse->sinkpad,
397       GST_DEBUG_FUNCPTR (gst_base_parse_chain));
398   gst_pad_set_activate_function (parse->sinkpad,
399       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
400   gst_pad_set_activatepush_function (parse->sinkpad,
401       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
402   gst_pad_set_activatepull_function (parse->sinkpad,
403       GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
404   gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);
405
406   GST_DEBUG_OBJECT (parse, "sinkpad created");
407
408   pad_template =
409       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
410   g_return_if_fail (pad_template != NULL);
411   parse->srcpad = gst_pad_new_from_template (pad_template, "src");
412   gst_pad_set_event_function (parse->srcpad,
413       GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
414   gst_pad_set_query_type_function (parse->srcpad,
415       GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
416   gst_pad_set_query_function (parse->srcpad,
417       GST_DEBUG_FUNCPTR (gst_base_parse_query));
418   gst_pad_use_fixed_caps (parse->srcpad);
419   gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
420   GST_DEBUG_OBJECT (parse, "src created");
421
422   parse->parse_lock = g_mutex_new ();
423   parse->adapter = gst_adapter_new ();
424
425   parse->priv->pad_mode = GST_ACTIVATE_NONE;
426
427   /* init state */
428   gst_base_parse_reset (parse);
429   GST_DEBUG_OBJECT (parse, "init ok");
430 }
431
432 static void
433 gst_base_parse_reset (GstBaseParse * parse)
434 {
435   GST_OBJECT_LOCK (parse);
436   gst_segment_init (&parse->segment, GST_FORMAT_TIME);
437   parse->priv->duration = -1;
438   parse->priv->min_frame_size = 1;
439   parse->priv->discont = TRUE;
440   parse->priv->flushing = FALSE;
441   parse->priv->offset = 0;
442   parse->priv->sync_offset = 0;
443   parse->priv->update_interval = 50;
444   parse->priv->fps_num = parse->priv->fps_den = 0;
445   parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
446   parse->priv->seekable = GST_BASE_PARSE_SEEK_DEFAULT;
447   parse->priv->bitrate = 0;
448   parse->priv->framecount = 0;
449   parse->priv->bytecount = 0;
450   parse->priv->acc_duration = 0;
451   parse->priv->estimated_duration = -1;
452   parse->priv->next_ts = 0;
453   parse->priv->passthrough = FALSE;
454   parse->priv->post_min_bitrate = TRUE;
455   parse->priv->post_avg_bitrate = TRUE;
456   parse->priv->post_max_bitrate = TRUE;
457   parse->priv->min_bitrate = G_MAXUINT;
458   parse->priv->max_bitrate = 0;
459   parse->priv->avg_bitrate = 0;
460   parse->priv->posted_avg_bitrate = 0;
461
462   if (parse->pending_segment)
463     gst_event_unref (parse->pending_segment);
464
465   g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
466       NULL);
467   g_list_free (parse->priv->pending_events);
468   parse->priv->pending_events = NULL;
469
470   if (parse->priv->cache) {
471     gst_buffer_unref (parse->priv->cache);
472     parse->priv->cache = NULL;
473   }
474   GST_OBJECT_UNLOCK (parse);
475 }
476
477 /**
478  * gst_base_parse_check_frame:
479  * @parse: #GstBaseParse.
480  * @buffer: GstBuffer.
481  * @framesize: This will be set to tell the found frame size in bytes.
482  * @skipsize: Output parameter that tells how much data needs to be skipped
483  *            in order to find the following frame header.
484  *
485  * Default callback for check_valid_frame.
486  * 
487  * Returns: Always TRUE.
488  */
489 static gboolean
490 gst_base_parse_check_frame (GstBaseParse * parse,
491     GstBuffer * buffer, guint * framesize, gint * skipsize)
492 {
493   *framesize = GST_BUFFER_SIZE (buffer);
494   *skipsize = 0;
495   return TRUE;
496 }
497
498
499 /**
500  * gst_base_parse_parse_frame:
501  * @parse: #GstBaseParse.
502  * @buffer: #GstBuffer.
503  *
504  * Default callback for parse_frame.
505  */
506 static GstFlowReturn
507 gst_base_parse_parse_frame (GstBaseParse * parse, GstBuffer * buffer)
508 {
509   if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
510       GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
511     GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
512   }
513   if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
514       GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
515     GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
516   }
517   return GST_FLOW_OK;
518 }
519
520 /**
521  * gst_base_parse_convert:
522  * @parse: #GstBaseParse.
523  * @src_format: #GstFormat describing the source format.
524  * @src_value: Source value to be converted.
525  * @dest_format: #GstFormat defining the converted format.
526  * @dest_value: Pointer where the conversion result will be put.
527  *
528  * Converts using configured "convert" vmethod in #GstBaseParse class.
529  *
530  * Returns: TRUE if conversion was successful.
531  */
532 static gboolean
533 gst_base_parse_convert (GstBaseParse * parse,
534     GstFormat src_format,
535     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
536 {
537   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
538   gboolean ret;
539
540   g_return_val_if_fail (dest_value != NULL, FALSE);
541
542   if (!klass->convert)
543     return FALSE;
544
545   ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);
546
547 #ifndef GST_DISABLE_GST_DEBUG
548   {
549     if (ret) {
550       if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
551         GST_LOG_OBJECT (parse,
552             "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
553             GST_TIME_ARGS (src_value), *dest_value);
554       } else if (dest_format == GST_FORMAT_TIME &&
555           src_format == GST_FORMAT_BYTES) {
556         GST_LOG_OBJECT (parse,
557             "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
558             src_value, GST_TIME_ARGS (*dest_value));
559       } else {
560         GST_LOG_OBJECT (parse,
561             "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
562             GST_STR_NULL (gst_format_get_name (src_format)),
563             GST_STR_NULL (gst_format_get_name (dest_format)),
564             src_value, *dest_value);
565       }
566     } else {
567       GST_DEBUG_OBJECT (parse, "conversion failed");
568     }
569   }
570 #endif
571
572   return ret;
573 }
574
575 /**
576  * gst_base_parse_sink_event:
577  * @pad: #GstPad that received the event.
578  * @event: #GstEvent to be handled.
579  *
580  * Handler for sink pad events.
581  *
582  * Returns: TRUE if the event was handled.
583  */
584 static gboolean
585 gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
586 {
587   GstBaseParse *parse;
588   GstBaseParseClass *bclass;
589   gboolean handled = FALSE;
590   gboolean ret = TRUE;
591
592
593   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
594   bclass = GST_BASE_PARSE_GET_CLASS (parse);
595
596   GST_DEBUG_OBJECT (parse, "handling event %d", GST_EVENT_TYPE (event));
597
598   /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
599    * pending segment */
600   if (parse->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
601       && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
602       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
603       && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
604
605     if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
606       /* See if any bitrate tags were posted */
607       gst_base_parse_handle_tag (parse, event);
608
609     parse->priv->pending_events =
610         g_list_append (parse->priv->pending_events, event);
611     ret = TRUE;
612   } else {
613
614     if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
615         parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
616       /* We've not posted bitrate tags yet - do so now */
617       gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
618
619     if (bclass->event)
620       handled = bclass->event (parse, event);
621
622     if (!handled)
623       handled = gst_base_parse_sink_eventfunc (parse, event);
624
625     if (!handled)
626       ret = gst_pad_event_default (pad, event);
627   }
628
629   gst_object_unref (parse);
630   GST_DEBUG_OBJECT (parse, "event handled");
631   return ret;
632 }
633
634
635 /**
636  * gst_base_parse_sink_eventfunc:
637  * @parse: #GstBaseParse.
638  * @event: #GstEvent to be handled.
639  *
640  * Element-level event handler function.
641  *
642  * Returns: TRUE if the event was handled and not need forwarding.
643  */
644 static gboolean
645 gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
646 {
647   gboolean handled = FALSE;
648   GstEvent **eventp;
649
650   switch (GST_EVENT_TYPE (event)) {
651     case GST_EVENT_NEWSEGMENT:
652     {
653       gdouble rate, applied_rate;
654       GstFormat format;
655       gint64 start, stop, pos, offset = 0;
656       gboolean update;
657
658       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
659           &format, &start, &stop, &pos);
660
661
662       if (format == GST_FORMAT_BYTES) {
663         GstClockTime seg_start, seg_stop, seg_pos;
664
665         /* stop time is allowed to be open-ended, but not start & pos */
666         seg_stop = GST_CLOCK_TIME_NONE;
667         offset = pos;
668
669         if (gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
670                 GST_FORMAT_TIME, (gint64 *) & seg_start) &&
671             gst_base_parse_convert (parse, GST_FORMAT_BYTES, pos,
672                 GST_FORMAT_TIME, (gint64 *) & seg_pos)) {
673           gst_event_unref (event);
674           event = gst_event_new_new_segment_full (update, rate, applied_rate,
675               GST_FORMAT_TIME, seg_start, seg_stop, seg_pos);
676           format = GST_FORMAT_TIME;
677           GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
678               "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
679               ", pos = %" GST_TIME_FORMAT, GST_TIME_ARGS (seg_start),
680               GST_TIME_ARGS (seg_stop), GST_TIME_ARGS (seg_pos));
681         }
682       }
683
684       if (format != GST_FORMAT_TIME) {
685         /* Unknown incoming segment format. Output a default open-ended 
686          * TIME segment */
687         gst_event_unref (event);
688         event = gst_event_new_new_segment_full (update, rate, applied_rate,
689             GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
690       }
691
692       gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
693           &format, &start, &stop, &pos);
694
695       gst_segment_set_newsegment_full (&parse->segment, update, rate,
696           applied_rate, format, start, stop, pos);
697
698       GST_DEBUG_OBJECT (parse, "Created newseg rate %g, applied rate %g, "
699           "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
700           ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
701           GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
702
703       /* save the segment for later, right before we push a new buffer so that
704        * the caps are fixed and the next linked element can receive
705        * the segment. */
706       eventp = &parse->pending_segment;
707       gst_event_replace (eventp, event);
708       gst_event_unref (event);
709       handled = TRUE;
710
711       /* but finish the current segment */
712       GST_DEBUG_OBJECT (parse, "draining current segment");
713       gst_base_parse_drain (parse);
714       gst_adapter_clear (parse->adapter);
715       parse->priv->offset = offset;
716       parse->priv->sync_offset = offset;
717       parse->priv->next_ts = start;
718       parse->priv->discont = TRUE;
719       break;
720     }
721
722     case GST_EVENT_FLUSH_START:
723       parse->priv->flushing = TRUE;
724       handled = gst_pad_push_event (parse->srcpad, event);
725       /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
726       GST_PAD_STREAM_LOCK (parse->srcpad);
727       GST_PAD_STREAM_UNLOCK (parse->srcpad);
728
729       break;
730
731     case GST_EVENT_FLUSH_STOP:
732       gst_adapter_clear (parse->adapter);
733       parse->priv->flushing = FALSE;
734       parse->priv->discont = TRUE;
735       break;
736
737     case GST_EVENT_EOS:
738       gst_base_parse_drain (parse);
739
740       /* If we STILL have zero frames processed, fire an error */
741       if (parse->priv->framecount == 0) {
742         GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
743             ("No valid frames found before end of stream"), (NULL));
744       }
745       /* newsegment before eos */
746       if (parse->pending_segment) {
747         gst_pad_push_event (parse->srcpad, parse->pending_segment);
748         parse->pending_segment = NULL;
749       }
750       break;
751
752     default:
753       break;
754   }
755
756   return handled;
757 }
758
759
760 /**
761  * gst_base_parse_src_event:
762  * @pad: #GstPad that received the event.
763  * @event: #GstEvent that was received.
764  *
765  * Handler for source pad events.
766  *
767  * Returns: TRUE if the event was handled.
768  */
769 static gboolean
770 gst_base_parse_src_event (GstPad * pad, GstEvent * event)
771 {
772   GstBaseParse *parse;
773   GstBaseParseClass *bclass;
774   gboolean handled = FALSE;
775   gboolean ret = TRUE;
776
777   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
778   bclass = GST_BASE_PARSE_GET_CLASS (parse);
779
780   GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
781       GST_EVENT_TYPE_NAME (event));
782
783   if (bclass->src_event)
784     handled = bclass->src_event (parse, event);
785
786   if (!handled)
787     ret = gst_pad_event_default (pad, event);
788   else
789     gst_event_unref (event);
790
791   gst_object_unref (parse);
792   return ret;
793 }
794
795
796 /**
797  * gst_base_parse_src_eventfunc:
798  * @parse: #GstBaseParse.
799  * @event: #GstEvent that was received.
800  *
801  * Default srcpad event handler.
802  *
803  * Returns: TRUE if the event was handled and can be dropped.
804  */
805 static gboolean
806 gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
807 {
808   gboolean handled = FALSE;
809   GstBaseParseClass *bclass;
810
811   bclass = GST_BASE_PARSE_GET_CLASS (parse);
812
813   switch (GST_EVENT_TYPE (event)) {
814     case GST_EVENT_SEEK:
815     {
816       if (parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
817         handled = gst_base_parse_handle_seek (parse, event);
818       }
819       break;
820     }
821     default:
822       break;
823   }
824   return handled;
825 }
826
827
828 /**
829  * gst_base_parse_convert_default:
830  * @parse: #GstBaseParse.
831  * @src_format: #GstFormat describing the source format.
832  * @src_value: Source value to be converted.
833  * @dest_format: #GstFormat defining the converted format.
834  * @dest_value: Pointer where the conversion result will be put.
835  *
836  * Default implementation of "convert" vmethod in #GstBaseParse class.
837  *
838  * Returns: TRUE if conversion was successful.
839  */
840 gboolean
841 gst_base_parse_convert_default (GstBaseParse * parse,
842     GstFormat src_format,
843     gint64 src_value, GstFormat dest_format, gint64 * dest_value)
844 {
845   gboolean ret = FALSE;
846   guint64 bytes, duration;
847
848   if (G_UNLIKELY (src_format == dest_format)) {
849     *dest_value = src_value;
850     return TRUE;
851   }
852
853   if (G_UNLIKELY (src_value == -1)) {
854     *dest_value = -1;
855     return TRUE;
856   }
857
858   if (G_UNLIKELY (src_value == 0)) {
859     *dest_value = 0;
860     return TRUE;
861   }
862
863   /* need at least some frames */
864   if (!parse->priv->framecount)
865     return FALSE;
866
867   /* either frame info (having num means den also ok) or use average bitrate */
868   if (parse->priv->fps_num) {
869     duration = parse->priv->framecount * parse->priv->fps_den * 1000;
870     bytes = parse->priv->bytecount * parse->priv->fps_num;
871   } else {
872     duration = parse->priv->acc_duration / GST_MSECOND;
873     bytes = parse->priv->bytecount;
874   }
875
876   if (G_UNLIKELY (!duration || !bytes))
877     return FALSE;
878
879   if (src_format == GST_FORMAT_BYTES) {
880     if (dest_format == GST_FORMAT_TIME) {
881       /* BYTES -> TIME conversion */
882       GST_DEBUG_OBJECT (parse, "converting bytes -> time");
883       *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
884       *dest_value *= GST_MSECOND;
885       GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
886           *dest_value / GST_MSECOND);
887       ret = TRUE;
888     }
889   } else if (src_format == GST_FORMAT_TIME) {
890     if (dest_format == GST_FORMAT_BYTES) {
891       GST_DEBUG_OBJECT (parse, "converting time -> bytes");
892       *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
893           duration);
894       GST_DEBUG_OBJECT (parse,
895           "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
896           src_value / GST_MSECOND, *dest_value);
897       ret = TRUE;
898     }
899   } else if (src_format == GST_FORMAT_DEFAULT) {
900     /* DEFAULT == frame-based */
901     if (dest_format == GST_FORMAT_TIME) {
902       if (parse->priv->fps_den) {
903         *dest_value = gst_util_uint64_scale (src_value,
904             GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
905         ret = TRUE;
906       }
907     } else if (dest_format == GST_FORMAT_BYTES) {
908     }
909   }
910
911   return ret;
912 }
913
914 /**
915  * gst_base_parse_update_duration:
916  * @parse: #GstBaseParse.
917  *
918  */
919 static void
920 gst_base_parse_update_duration (GstBaseParse * aacparse)
921 {
922   GstPad *peer;
923   GstBaseParse *parse;
924
925   parse = GST_BASE_PARSE (aacparse);
926
927   peer = gst_pad_get_peer (parse->sinkpad);
928   if (peer) {
929     GstFormat pformat = GST_FORMAT_BYTES;
930     gboolean qres = FALSE;
931     gint64 ptot, dest_value;
932
933     qres = gst_pad_query_duration (peer, &pformat, &ptot);
934     gst_object_unref (GST_OBJECT (peer));
935     if (qres) {
936       if (gst_base_parse_convert (parse, pformat, ptot,
937               GST_FORMAT_TIME, &dest_value))
938         parse->priv->estimated_duration = dest_value;
939     }
940   }
941 }
942
943 static void
944 gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
945     gboolean post_avg, gboolean post_max)
946 {
947   GstTagList *taglist = gst_tag_list_new ();
948
949   if (post_min && parse->priv->post_min_bitrate)
950     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
951         GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);
952
953   if (post_avg && parse->priv->post_avg_bitrate) {
954     parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
955     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
956         parse->priv->avg_bitrate, NULL);
957   }
958
959   if (post_max && parse->priv->post_max_bitrate)
960     gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
961         GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);
962
963   GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
964       parse->priv->min_bitrate, parse->priv->avg_bitrate,
965       parse->priv->max_bitrate);
966
967   gst_element_found_tags_for_pad (GST_ELEMENT (parse), parse->srcpad, taglist);
968 }
969
970 /**
971  * gst_base_parse_update_bitrates:
972  * @parse: #GstBaseParse.
973  * @buffer: Current frame as a #GstBuffer
974  *
975  * Keeps track of the minimum and maximum bitrates, and also maintains a
976  * running average bitrate of the stream so far.
977  */
978 static void
979 gst_base_parse_update_bitrates (GstBaseParse * parse, GstBuffer * buffer)
980 {
981   /* Only update the tag on a 10 kbps delta */
982   static const gint update_threshold = 10000;
983
984   GstBaseParseClass *klass;
985   guint64 data_len, frame_dur;
986   gint overhead = 0, frame_bitrate, old_avg_bitrate;
987   gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
988
989   klass = GST_BASE_PARSE_GET_CLASS (parse);
990
991   if (klass->get_frame_overhead) {
992     overhead = klass->get_frame_overhead (parse, buffer);
993     if (overhead == -1)
994       return;
995   }
996
997   data_len = GST_BUFFER_SIZE (buffer) - overhead;
998   parse->priv->data_bytecount += data_len;
999
1000   if (parse->priv->fps_num) {
1001     /* Calculate duration of a frame from frame properties */
1002     frame_dur = (GST_SECOND * parse->priv->fps_den) / parse->priv->fps_num;
1003     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1004         (parse->priv->framecount * frame_dur);
1005
1006   } else if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1007     /* Calculate duration of a frame from buffer properties */
1008     frame_dur = GST_BUFFER_DURATION (buffer);
1009     parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
1010         parse->priv->acc_duration;
1011
1012   } else {
1013     /* No way to figure out frame duration (is this even possible?) */
1014     return;
1015   }
1016
1017   /* override if subclass provided bitrate, e.g. metadata based */
1018   if (parse->priv->bitrate) {
1019     parse->priv->avg_bitrate = parse->priv->bitrate;
1020   }
1021
1022   frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
1023
1024   GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
1025       parse->priv->avg_bitrate);
1026
1027   if (frame_bitrate < parse->priv->min_bitrate) {
1028     parse->priv->min_bitrate = frame_bitrate;
1029     update_min = TRUE;
1030   }
1031
1032   if (frame_bitrate > parse->priv->max_bitrate) {
1033     parse->priv->max_bitrate = frame_bitrate;
1034     update_max = TRUE;
1035   }
1036
1037   old_avg_bitrate = parse->priv->posted_avg_bitrate;
1038   if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold ||
1039       (gint) (parse->priv->avg_bitrate - old_avg_bitrate) > update_threshold)
1040     update_avg = TRUE;
1041
1042   /* always post all at threshold time */
1043   if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE)
1044     gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);
1045
1046   if (parse->priv->framecount > MIN_FRAMES_TO_POST_BITRATE &&
1047       (update_min || update_avg || update_max))
1048     gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1049
1050   /* If average bitrate changes that much and no valid (time) duration provided,
1051    * then post a new duration message so applications can update their cached
1052    * values */
1053   if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
1054           GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
1055     gst_element_post_message (GST_ELEMENT (parse),
1056         gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1057 }
1058
1059 /**
1060  * gst_base_parse_handle_and_push_buffer:
1061  * @parse: #GstBaseParse.
1062  * @klass: #GstBaseParseClass.
1063  * @buffer: #GstBuffer.
1064  *
1065  * Parses the frame from given buffer and pushes it forward. Also performs
1066  * timestamp handling and checks the segment limits.
1067  *
1068  * This is called with srcpad STREAM_LOCK held.
1069  *
1070  * Returns: #GstFlowReturn
1071  */
1072 static GstFlowReturn
1073 gst_base_parse_handle_and_push_buffer (GstBaseParse * parse,
1074     GstBaseParseClass * klass, GstBuffer * buffer)
1075 {
1076   GstFlowReturn ret;
1077
1078   if (parse->priv->discont) {
1079     GST_DEBUG_OBJECT (parse, "marking DISCONT");
1080     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1081     parse->priv->discont = FALSE;
1082   }
1083
1084   GST_LOG_OBJECT (parse,
1085       "parsing frame at offset %" G_GUINT64_FORMAT
1086       " (%#" G_GINT64_MODIFIER "x) of size %d",
1087       GST_BUFFER_OFFSET (buffer), GST_BUFFER_OFFSET (buffer),
1088       GST_BUFFER_SIZE (buffer));
1089
1090   ret = klass->parse_frame (parse, buffer);
1091
1092   /* re-use default handler to add missing metadata as-much-as-possible */
1093   gst_base_parse_parse_frame (parse, buffer);
1094   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1095       GST_BUFFER_DURATION_IS_VALID (buffer)) {
1096     parse->priv->next_ts =
1097         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1098   } else {
1099     /* we lost track, do not produce bogus time next time around
1100      * (probably means parser subclass has given up on parsing as well) */
1101     GST_DEBUG_OBJECT (parse, "no next fallback timestamp");
1102     parse->priv->next_ts = GST_CLOCK_TIME_NONE;
1103   }
1104
1105   /* First buffers are dropped, this means that the subclass needs more
1106    * frames to decide on the format and queues them internally */
1107   /* convert internal flow to OK and mark discont for the next buffer. */
1108   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1109     gst_buffer_unref (buffer);
1110     return GST_FLOW_OK;
1111   } else if (ret != GST_FLOW_OK) {
1112     return ret;
1113   }
1114
1115   return gst_base_parse_push_buffer (parse, buffer);
1116 }
1117
1118 /**
1119  * gst_base_parse_push_buffer:
1120  * @parse: #GstBaseParse.
1121  * @buffer: #GstBuffer.
1122  *
1123  * Pushes the buffer downstream, sends any pending events and
1124  * does some timestamp and segment handling.
1125  *
1126  * This must be called with srcpad STREAM_LOCK held.
1127  *
1128  * Returns: #GstFlowReturn
1129  */
1130 GstFlowReturn
1131 gst_base_parse_push_buffer (GstBaseParse * parse, GstBuffer * buffer)
1132 {
1133   GstFlowReturn ret = GST_FLOW_OK;
1134   GstClockTime last_start = GST_CLOCK_TIME_NONE;
1135   GstClockTime last_stop = GST_CLOCK_TIME_NONE;
1136   GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
1137
1138   GST_LOG_OBJECT (parse,
1139       "processing buffer of size %d with ts %" GST_TIME_FORMAT
1140       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1141       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1142       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1143
1144   /* update stats */
1145   parse->priv->bytecount += GST_BUFFER_SIZE (buffer);
1146   if (!GST_BUFFER_FLAG_IS_SET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME)) {
1147     parse->priv->framecount++;
1148     if (GST_BUFFER_DURATION_IS_VALID (buffer)) {
1149       parse->priv->acc_duration += GST_BUFFER_DURATION (buffer);
1150     }
1151   }
1152   GST_BUFFER_FLAG_UNSET (buffer, GST_BASE_PARSE_BUFFER_FLAG_NO_FRAME);
1153   if (parse->priv->update_interval &&
1154       (parse->priv->framecount % parse->priv->update_interval) == 0)
1155     gst_base_parse_update_duration (parse);
1156
1157   gst_base_parse_update_bitrates (parse, buffer);
1158
1159   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer))
1160     last_start = last_stop = GST_BUFFER_TIMESTAMP (buffer);
1161   if (last_start != GST_CLOCK_TIME_NONE
1162       && GST_BUFFER_DURATION_IS_VALID (buffer))
1163     last_stop = last_start + GST_BUFFER_DURATION (buffer);
1164
1165   /* should have caps by now */
1166   g_return_val_if_fail (GST_PAD_CAPS (parse->srcpad), GST_FLOW_ERROR);
1167
1168   gst_buffer_set_caps (buffer, GST_PAD_CAPS (parse->srcpad));
1169
1170   /* segment times are typically estimates,
1171    * actual frame data might lead subclass to different timestamps,
1172    * so override segment start from what is supplied there */
1173   if (G_UNLIKELY (parse->pending_segment && !parse->priv->passthrough &&
1174           GST_CLOCK_TIME_IS_VALID (last_start))) {
1175     gst_event_unref (parse->pending_segment);
1176     /* stop time possibly lost this way,
1177      * but unlikely and not really supported */
1178     parse->pending_segment =
1179         gst_event_new_new_segment (FALSE, parse->segment.rate,
1180         parse->segment.format, last_start, -1, last_start);
1181   }
1182
1183   /* and should then also be linked downstream, so safe to send some events */
1184   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
1185     if (G_UNLIKELY (parse->close_segment)) {
1186       GST_DEBUG_OBJECT (parse, "loop sending close segment");
1187       gst_pad_push_event (parse->srcpad, parse->close_segment);
1188       parse->close_segment = NULL;
1189     }
1190
1191     if (G_UNLIKELY (parse->pending_segment)) {
1192       GST_DEBUG_OBJECT (parse, "loop push pending segment");
1193       gst_pad_push_event (parse->srcpad, parse->pending_segment);
1194       parse->pending_segment = NULL;
1195     }
1196   } else {
1197     if (G_UNLIKELY (parse->pending_segment)) {
1198       GST_DEBUG_OBJECT (parse, "chain pushing a pending segment");
1199       gst_pad_push_event (parse->srcpad, parse->pending_segment);
1200       parse->pending_segment = NULL;
1201     }
1202   }
1203
1204   if (G_UNLIKELY (parse->priv->pending_events)) {
1205     GList *l;
1206
1207     for (l = parse->priv->pending_events; l != NULL; l = l->next) {
1208       gst_pad_push_event (parse->srcpad, GST_EVENT (l->data));
1209     }
1210     g_list_free (parse->priv->pending_events);
1211     parse->priv->pending_events = NULL;
1212   }
1213
1214   /* TODO: Add to seek table */
1215
1216   if (klass->pre_push_buffer)
1217     ret = klass->pre_push_buffer (parse, buffer);
1218   else
1219     ret = GST_BASE_PARSE_FLOW_CLIP;
1220
1221   if (ret == GST_BASE_PARSE_FLOW_CLIP) {
1222     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1223         GST_CLOCK_TIME_IS_VALID (parse->segment.stop) &&
1224         GST_BUFFER_TIMESTAMP (buffer) > parse->segment.stop) {
1225       GST_LOG_OBJECT (parse, "Dropped frame, after segment");
1226       ret = GST_FLOW_UNEXPECTED;
1227     } else if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1228         GST_BUFFER_DURATION_IS_VALID (buffer) &&
1229         GST_CLOCK_TIME_IS_VALID (parse->segment.start) &&
1230         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer)
1231         < parse->segment.start) {
1232       GST_LOG_OBJECT (parse, "Dropped frame, before segment");
1233       ret = GST_BASE_PARSE_FLOW_DROPPED;
1234     } else {
1235       ret = GST_FLOW_OK;
1236     }
1237   }
1238
1239   if (ret == GST_BASE_PARSE_FLOW_DROPPED) {
1240     GST_LOG_OBJECT (parse, "frame (%d bytes) dropped",
1241         GST_BUFFER_SIZE (buffer));
1242     gst_buffer_unref (buffer);
1243     ret = GST_FLOW_OK;
1244   } else if (ret == GST_FLOW_OK) {
1245     ret = gst_pad_push (parse->srcpad, buffer);
1246     GST_LOG_OBJECT (parse, "frame (%d bytes) pushed: %s",
1247         GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1248   } else {
1249     gst_buffer_unref (buffer);
1250     GST_LOG_OBJECT (parse, "frame (%d bytes) not pushed: %s",
1251         GST_BUFFER_SIZE (buffer), gst_flow_get_name (ret));
1252   }
1253
1254   /* Update current running segment position */
1255   if (ret == GST_FLOW_OK && last_stop != GST_CLOCK_TIME_NONE)
1256     gst_segment_set_last_stop (&parse->segment, GST_FORMAT_TIME, last_stop);
1257
1258   return ret;
1259 }
1260
1261
1262 /**
1263  * gst_base_parse_drain:
1264  * @parse: #GstBaseParse.
1265  *
1266  * Drains the adapter until it is empty. It decreases the min_frame_size to
1267  * match the current adapter size and calls chain method until the adapter
1268  * is emptied or chain returns with error.
1269  */
1270 static void
1271 gst_base_parse_drain (GstBaseParse * parse)
1272 {
1273   guint avail;
1274
1275   GST_DEBUG_OBJECT (parse, "draining");
1276   parse->priv->drain = TRUE;
1277
1278   for (;;) {
1279     avail = gst_adapter_available (parse->adapter);
1280     if (!avail)
1281       break;
1282
1283     if (gst_base_parse_chain (parse->sinkpad, NULL) != GST_FLOW_OK) {
1284       break;
1285     }
1286
1287     /* nothing changed, maybe due to truncated frame; break infinite loop */
1288     if (avail == gst_adapter_available (parse->adapter)) {
1289       GST_DEBUG_OBJECT (parse, "no change during draining; flushing");
1290       gst_adapter_clear (parse->adapter);
1291     }
1292   }
1293
1294   parse->priv->drain = FALSE;
1295 }
1296
1297 /* small helper that checks whether we have been trying to resync too long */
1298 static inline GstFlowReturn
1299 gst_base_parse_check_sync (GstBaseParse * parse)
1300 {
1301   if (G_UNLIKELY (parse->priv->discont &&
1302           parse->priv->offset - parse->priv->sync_offset > 2 * 1024 * 1024)) {
1303     GST_ELEMENT_ERROR (parse, STREAM, DECODE,
1304         ("Failed to parse stream"), (NULL));
1305     return GST_FLOW_ERROR;
1306   }
1307
1308   return GST_FLOW_OK;
1309 }
1310
1311
1312 /**
1313  * gst_base_parse_chain:
1314  * @pad: #GstPad.
1315  * @buffer: #GstBuffer.
1316  *
1317  * Returns: #GstFlowReturn.
1318  */
1319 static GstFlowReturn
1320 gst_base_parse_chain (GstPad * pad, GstBuffer * buffer)
1321 {
1322   GstBaseParseClass *bclass;
1323   GstBaseParse *parse;
1324   GstFlowReturn ret = GST_FLOW_OK;
1325   GstBuffer *outbuf = NULL;
1326   GstBuffer *tmpbuf = NULL;
1327   guint fsize = 0;
1328   gint skip = -1;
1329   const guint8 *data;
1330   guint min_size;
1331   GstClockTime timestamp;
1332
1333   parse = GST_BASE_PARSE (GST_OBJECT_PARENT (pad));
1334   bclass = GST_BASE_PARSE_GET_CLASS (parse);
1335
1336   if (G_LIKELY (buffer)) {
1337     GST_LOG_OBJECT (parse, "buffer size: %d, offset = %" G_GINT64_FORMAT,
1338         GST_BUFFER_SIZE (buffer), GST_BUFFER_OFFSET (buffer));
1339     if (G_UNLIKELY (parse->priv->passthrough)) {
1340       buffer = gst_buffer_make_metadata_writable (buffer);
1341       return gst_base_parse_push_buffer (parse, buffer);
1342     } else
1343       gst_adapter_push (parse->adapter, buffer);
1344   }
1345
1346   /* Parse and push as many frames as possible */
1347   /* Stop either when adapter is empty or we are flushing */
1348   while (!parse->priv->flushing) {
1349     tmpbuf = gst_buffer_new ();
1350
1351     /* Synchronization loop */
1352     for (;;) {
1353       GST_BASE_PARSE_LOCK (parse);
1354       min_size = parse->priv->min_frame_size;
1355       GST_BASE_PARSE_UNLOCK (parse);
1356
1357       if (G_UNLIKELY (parse->priv->drain)) {
1358         min_size = gst_adapter_available (parse->adapter);
1359         GST_DEBUG_OBJECT (parse, "draining, data left: %d", min_size);
1360         if (G_UNLIKELY (!min_size)) {
1361           gst_buffer_unref (tmpbuf);
1362           goto done;
1363         }
1364       }
1365
1366       /* Collect at least min_frame_size bytes */
1367       if (gst_adapter_available (parse->adapter) < min_size) {
1368         GST_DEBUG_OBJECT (parse, "not enough data available (only %d bytes)",
1369             gst_adapter_available (parse->adapter));
1370         gst_buffer_unref (tmpbuf);
1371         goto done;
1372       }
1373
1374       data = gst_adapter_peek (parse->adapter, min_size);
1375       GST_BUFFER_DATA (tmpbuf) = (guint8 *) data;
1376       GST_BUFFER_SIZE (tmpbuf) = min_size;
1377       GST_BUFFER_OFFSET (tmpbuf) = parse->priv->offset;
1378       GST_BUFFER_FLAG_SET (tmpbuf, GST_MINI_OBJECT_FLAG_READONLY);
1379
1380       if (parse->priv->discont) {
1381         GST_DEBUG_OBJECT (parse, "marking DISCONT");
1382         GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
1383       }
1384
1385       skip = -1;
1386       if (bclass->check_valid_frame (parse, tmpbuf, &fsize, &skip)) {
1387         if (gst_adapter_available (parse->adapter) < fsize) {
1388           GST_DEBUG_OBJECT (parse,
1389               "found valid frame but not enough data available (only %d bytes)",
1390               gst_adapter_available (parse->adapter));
1391           gst_buffer_unref (tmpbuf);
1392           goto done;
1393         }
1394         break;
1395       }
1396       if (skip > 0) {
1397         GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
1398         gst_adapter_flush (parse->adapter, skip);
1399         parse->priv->offset += skip;
1400         if (!parse->priv->discont)
1401           parse->priv->sync_offset = parse->priv->offset;
1402         parse->priv->discont = TRUE;
1403       } else if (skip == -1) {
1404         /* subclass didn't touch this value. By default we skip 1 byte */
1405         GST_LOG_OBJECT (parse, "finding sync, skipping 1 byte");
1406         gst_adapter_flush (parse->adapter, 1);
1407         parse->priv->offset++;
1408         if (!parse->priv->discont)
1409           parse->priv->sync_offset = parse->priv->offset;
1410         parse->priv->discont = TRUE;
1411       }
1412       /* There is a possibility that subclass set the skip value to zero.
1413          This means that it has probably found a frame but wants to ask
1414          more data (by increasing the min_size) to be sure of this. */
1415       if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
1416         gst_buffer_unref (tmpbuf);
1417         goto done;
1418       }
1419     }
1420     gst_buffer_unref (tmpbuf);
1421     tmpbuf = NULL;
1422
1423     if (skip > 0) {
1424       /* Subclass found the sync, but still wants to skip some data */
1425       GST_LOG_OBJECT (parse, "skipping %d bytes", skip);
1426       gst_adapter_flush (parse->adapter, skip);
1427       parse->priv->offset += skip;
1428     }
1429
1430     /* Grab lock to prevent a race with FLUSH_START handler */
1431     GST_PAD_STREAM_LOCK (parse->srcpad);
1432
1433     /* FLUSH_START event causes the "flushing" flag to be set. In this
1434      * case we can leave the frame pushing loop */
1435     if (parse->priv->flushing) {
1436       GST_PAD_STREAM_UNLOCK (parse->srcpad);
1437       break;
1438     }
1439
1440     /* FIXME: Would it be more efficient to make a subbuffer instead? */
1441     outbuf = gst_adapter_take_buffer (parse->adapter, fsize);
1442     outbuf = gst_buffer_make_metadata_writable (outbuf);
1443
1444     /* Subclass may want to know the data offset */
1445     GST_BUFFER_OFFSET (outbuf) = parse->priv->offset;
1446     parse->priv->offset += fsize;
1447
1448     /* move along with upstream timestamp (if any),
1449      * but interpolate in between */
1450     timestamp = gst_adapter_prev_timestamp (parse->adapter, NULL);
1451     if (GST_CLOCK_TIME_IS_VALID (timestamp) &&
1452         (parse->priv->prev_ts != timestamp)) {
1453       parse->priv->prev_ts = parse->priv->next_ts = timestamp;
1454     }
1455
1456     ret = gst_base_parse_handle_and_push_buffer (parse, bclass, outbuf);
1457     GST_PAD_STREAM_UNLOCK (parse->srcpad);
1458
1459     if (ret != GST_FLOW_OK) {
1460       GST_LOG_OBJECT (parse, "push returned %d", ret);
1461       break;
1462     }
1463   }
1464
1465 done:
1466   GST_LOG_OBJECT (parse, "chain leaving");
1467   return ret;
1468 }
1469
1470 /* pull @size bytes at current offset,
1471  * i.e. at least try to and possibly return a shorter buffer if near the end */
1472 static GstFlowReturn
1473 gst_base_parse_pull_range (GstBaseParse * parse, guint size,
1474     GstBuffer ** buffer)
1475 {
1476   GstFlowReturn ret = GST_FLOW_OK;
1477
1478   g_return_val_if_fail (buffer != NULL, GST_FLOW_ERROR);
1479
1480   /* Caching here actually makes much less difference than one would expect.
1481    * We do it mainly to avoid pulling buffers of 1 byte all the time */
1482   if (parse->priv->cache) {
1483     gint64 cache_offset = GST_BUFFER_OFFSET (parse->priv->cache);
1484     gint cache_size = GST_BUFFER_SIZE (parse->priv->cache);
1485
1486     if (cache_offset <= parse->priv->offset &&
1487         (parse->priv->offset + size) <= (cache_offset + cache_size)) {
1488       *buffer = gst_buffer_create_sub (parse->priv->cache,
1489           parse->priv->offset - cache_offset, size);
1490       GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1491       return GST_FLOW_OK;
1492     }
1493     /* not enough data in the cache, free cache and get a new one */
1494     gst_buffer_unref (parse->priv->cache);
1495     parse->priv->cache = NULL;
1496   }
1497
1498   /* refill the cache */
1499   ret =
1500       gst_pad_pull_range (parse->sinkpad, parse->priv->offset, MAX (size,
1501           64 * 1024), &parse->priv->cache);
1502   if (ret != GST_FLOW_OK) {
1503     parse->priv->cache = NULL;
1504     return ret;
1505   }
1506
1507   if (GST_BUFFER_SIZE (parse->priv->cache) >= size) {
1508     *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
1509     GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1510     return GST_FLOW_OK;
1511   }
1512
1513   /* Not possible to get enough data, try a last time with
1514    * requesting exactly the size we need */
1515   gst_buffer_unref (parse->priv->cache);
1516   parse->priv->cache = NULL;
1517
1518   ret = gst_pad_pull_range (parse->sinkpad, parse->priv->offset, size,
1519       &parse->priv->cache);
1520
1521   if (ret != GST_FLOW_OK) {
1522     GST_DEBUG_OBJECT (parse, "pull_range returned %d", ret);
1523     *buffer = NULL;
1524     return ret;
1525   }
1526
1527   if (GST_BUFFER_SIZE (parse->priv->cache) < size) {
1528     GST_DEBUG_OBJECT (parse, "Returning short buffer at offset %"
1529         G_GUINT64_FORMAT ": wanted %u bytes, got %u bytes", parse->priv->offset,
1530         size, GST_BUFFER_SIZE (parse->priv->cache));
1531
1532     *buffer = parse->priv->cache;
1533     parse->priv->cache = NULL;
1534
1535     return GST_FLOW_OK;
1536   }
1537
1538   *buffer = gst_buffer_create_sub (parse->priv->cache, 0, size);
1539   GST_BUFFER_OFFSET (*buffer) = parse->priv->offset;
1540
1541   return GST_FLOW_OK;
1542 }
1543
1544 /**
1545  * gst_base_parse_loop:
1546  * @pad: GstPad
1547  *
1548  * Loop that is used in pull mode to retrieve data from upstream.
1549  */
1550 static void
1551 gst_base_parse_loop (GstPad * pad)
1552 {
1553   GstBaseParse *parse;
1554   GstBaseParseClass *klass;
1555   GstBuffer *buffer, *outbuf;
1556   gboolean ret = FALSE;
1557   guint fsize = 0, min_size;
1558   gint skip = 0;
1559
1560   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1561   klass = GST_BASE_PARSE_GET_CLASS (parse);
1562
1563   /* TODO: Check if we reach segment stop limit */
1564
1565   while (TRUE) {
1566
1567     GST_BASE_PARSE_LOCK (parse);
1568     min_size = parse->priv->min_frame_size;
1569     GST_BASE_PARSE_UNLOCK (parse);
1570
1571     ret = gst_base_parse_pull_range (parse, min_size, &buffer);
1572
1573     if (ret == GST_FLOW_UNEXPECTED)
1574       goto eos;
1575     else if (ret != GST_FLOW_OK)
1576       goto need_pause;
1577
1578     if (parse->priv->discont) {
1579       GST_DEBUG_OBJECT (parse, "marking DISCONT");
1580       GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1581     }
1582
1583     /* if we got a short read, inform subclass we are draining leftover
1584      * and no more is to be expected */
1585     if (GST_BUFFER_SIZE (buffer) < min_size)
1586       parse->priv->drain = TRUE;
1587
1588     skip = -1;
1589     if (klass->check_valid_frame (parse, buffer, &fsize, &skip)) {
1590       parse->priv->drain = FALSE;
1591       break;
1592     }
1593     parse->priv->drain = FALSE;
1594     if (skip > 0) {
1595       GST_LOG_OBJECT (parse, "finding sync, skipping %d bytes", skip);
1596       parse->priv->offset += skip;
1597       if (!parse->priv->discont)
1598         parse->priv->sync_offset = parse->priv->offset;
1599       parse->priv->discont = TRUE;
1600     } else if (skip == -1) {
1601       GST_LOG_OBJECT (parse, "finding sync, skipping 1 byte");
1602       parse->priv->offset++;
1603       if (!parse->priv->discont)
1604         parse->priv->sync_offset = parse->priv->offset;
1605       parse->priv->discont = TRUE;
1606     }
1607     /* skip == 0 should imply subclass set min_size to need more data ... */
1608     GST_DEBUG_OBJECT (parse, "finding sync...");
1609     gst_buffer_unref (buffer);
1610     if ((ret = gst_base_parse_check_sync (parse)) != GST_FLOW_OK) {
1611       goto done;
1612     }
1613   }
1614
1615   if (fsize <= GST_BUFFER_SIZE (buffer)) {
1616     outbuf = gst_buffer_create_sub (buffer, 0, fsize);
1617     GST_BUFFER_OFFSET (outbuf) = GST_BUFFER_OFFSET (buffer);
1618     gst_buffer_unref (buffer);
1619   } else {
1620     gst_buffer_unref (buffer);
1621     ret = gst_base_parse_pull_range (parse, fsize, &outbuf);
1622
1623     if (ret == GST_FLOW_UNEXPECTED)
1624       goto eos;
1625     else if (ret != GST_FLOW_OK)
1626       goto need_pause;
1627     if (GST_BUFFER_SIZE (outbuf) < fsize)
1628       goto eos;
1629   }
1630
1631   parse->priv->offset += fsize;
1632
1633   /* Does the subclass want to skip too? */
1634   if (skip > 0)
1635     parse->priv->offset += skip;
1636
1637   /* This always unrefs the outbuf, even if error occurs */
1638   ret = gst_base_parse_handle_and_push_buffer (parse, klass, outbuf);
1639
1640   if (ret != GST_FLOW_OK) {
1641     GST_DEBUG_OBJECT (parse, "flow: %s", gst_flow_get_name (ret));
1642     if (ret == GST_FLOW_UNEXPECTED) {
1643       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
1644     } else if (ret == GST_FLOW_NOT_LINKED || ret < GST_FLOW_UNEXPECTED) {
1645       GST_ELEMENT_ERROR (parse, STREAM, FAILED, (NULL),
1646           ("streaming task paused, reason: %s", gst_flow_get_name (ret)));
1647       gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
1648     }
1649     goto need_pause;
1650   }
1651
1652 done:
1653   gst_object_unref (parse);
1654   return;
1655
1656 need_pause:
1657   {
1658     GST_LOG_OBJECT (parse, "pausing task %d", ret);
1659     gst_pad_pause_task (pad);
1660     gst_object_unref (parse);
1661     return;
1662   }
1663 eos:
1664   {
1665     GST_LOG_OBJECT (parse, "sending eos");
1666     gst_pad_push_event (parse->srcpad, gst_event_new_eos ());
1667     goto need_pause;
1668   }
1669 }
1670
1671
1672 /**
1673  * gst_base_parse_sink_activate:
1674  * @sinkpad: #GstPad to be activated.
1675  *
1676  * Returns: TRUE if activation succeeded.
1677  */
1678 static gboolean
1679 gst_base_parse_sink_activate (GstPad * sinkpad)
1680 {
1681   GstBaseParse *parse;
1682   gboolean result = TRUE;
1683
1684   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
1685
1686   GST_DEBUG_OBJECT (parse, "sink activate");
1687
1688   if (gst_pad_check_pull_range (sinkpad)) {
1689     GST_DEBUG_OBJECT (parse, "trying to activate in pull mode");
1690     result = gst_pad_activate_pull (sinkpad, TRUE);
1691   } else {
1692     GST_DEBUG_OBJECT (parse, "trying to activate in push mode");
1693     result = gst_pad_activate_push (sinkpad, TRUE);
1694   }
1695
1696   GST_DEBUG_OBJECT (parse, "sink activate return %d", result);
1697   gst_object_unref (parse);
1698   return result;
1699 }
1700
1701
1702 /**
1703  * gst_base_parse_activate:
1704  * @parse: #GstBaseParse.
1705  * @active: TRUE if element will be activated, FALSE if disactivated.
1706  *
1707  * Returns: TRUE if the operation succeeded.
1708  */
1709 static gboolean
1710 gst_base_parse_activate (GstBaseParse * parse, gboolean active)
1711 {
1712   GstBaseParseClass *klass;
1713   gboolean result = FALSE;
1714
1715   GST_DEBUG_OBJECT (parse, "activate");
1716
1717   klass = GST_BASE_PARSE_GET_CLASS (parse);
1718
1719   if (active) {
1720     if (parse->priv->pad_mode == GST_ACTIVATE_NONE && klass->start)
1721       result = klass->start (parse);
1722   } else {
1723     /* We must make sure streaming has finished before resetting things
1724      * and calling the ::stop vfunc */
1725     GST_PAD_STREAM_LOCK (parse->sinkpad);
1726     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
1727
1728     if (parse->priv->pad_mode != GST_ACTIVATE_NONE && klass->stop)
1729       result = klass->stop (parse);
1730
1731     parse->priv->pad_mode = GST_ACTIVATE_NONE;
1732   }
1733   GST_DEBUG_OBJECT (parse, "activate: %d", result);
1734   return result;
1735 }
1736
1737
1738 /**
1739  * gst_base_parse_sink_activate_push:
1740  * @pad: #GstPad to be (de)activated.
1741  * @active: TRUE when activating, FALSE when deactivating.
1742  *
1743  * Returns: TRUE if (de)activation succeeded.
1744  */
1745 static gboolean
1746 gst_base_parse_sink_activate_push (GstPad * pad, gboolean active)
1747 {
1748   gboolean result = TRUE;
1749   GstBaseParse *parse;
1750
1751   parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
1752
1753   GST_DEBUG_OBJECT (parse, "sink activate push");
1754
1755   result = gst_base_parse_activate (parse, active);
1756
1757   if (result)
1758     parse->priv->pad_mode = active ? GST_ACTIVATE_PUSH : GST_ACTIVATE_NONE;
1759
1760   GST_DEBUG_OBJECT (parse, "sink activate push: %d", result);
1761
1762   gst_object_unref (parse);
1763   return result;
1764 }
1765
1766
1767 /**
1768  * gst_base_parse_sink_activate_pull:
1769  * @sinkpad: #GstPad to be (de)activated.
1770  * @active: TRUE when activating, FALSE when deactivating.
1771  *
1772  * Returns: TRUE if (de)activation succeeded.
1773  */
1774 static gboolean
1775 gst_base_parse_sink_activate_pull (GstPad * sinkpad, gboolean active)
1776 {
1777   gboolean result = FALSE;
1778   GstBaseParse *parse;
1779
1780   parse = GST_BASE_PARSE (gst_pad_get_parent (sinkpad));
1781
1782   GST_DEBUG_OBJECT (parse, "activate pull");
1783
1784   result = gst_base_parse_activate (parse, active);
1785
1786   if (result) {
1787     if (active) {
1788       parse->pending_segment = gst_event_new_new_segment (FALSE,
1789           parse->segment.rate, parse->segment.format,
1790           parse->segment.start, parse->segment.stop, parse->segment.last_stop);
1791       result &= gst_pad_start_task (sinkpad,
1792           (GstTaskFunction) gst_base_parse_loop, sinkpad);
1793     } else {
1794       result &= gst_pad_stop_task (sinkpad);
1795     }
1796   }
1797
1798   if (result)
1799     parse->priv->pad_mode = active ? GST_ACTIVATE_PULL : GST_ACTIVATE_NONE;
1800
1801   GST_DEBUG_OBJECT (parse, "sink activate pull: %d", result);
1802
1803   gst_object_unref (parse);
1804   return result;
1805 }
1806
1807
1808 /**
1809  * gst_base_parse_set_duration:
1810  * @parse: #GstBaseParse.
1811  * @fmt: #GstFormat.
1812  * @duration: duration value.
1813  *
1814  * Sets the duration of the currently playing media. Subclass can use this
1815  * when it notices a change in the media duration.
1816  */
1817 void
1818 gst_base_parse_set_duration (GstBaseParse * parse,
1819     GstFormat fmt, gint64 duration)
1820 {
1821   g_return_if_fail (parse != NULL);
1822
1823   GST_BASE_PARSE_LOCK (parse);
1824   if (duration != parse->priv->duration) {
1825     GstMessage *m;
1826
1827     m = gst_message_new_duration (GST_OBJECT (parse), fmt, duration);
1828     gst_element_post_message (GST_ELEMENT (parse), m);
1829
1830     /* TODO: what about duration tag? */
1831   }
1832   parse->priv->duration = duration;
1833   parse->priv->duration_fmt = fmt;
1834   GST_DEBUG_OBJECT (parse, "set duration: %" G_GINT64_FORMAT, duration);
1835   GST_BASE_PARSE_UNLOCK (parse);
1836 }
1837
1838 /**
1839  * gst_base_parse_set_seek:
1840  * @parse: #GstBaseParse.
1841  * @seek: #GstBaseParseSeekable.
1842  * @abitrate: average bitrate.
1843  *
1844  * Sets whether and how the media is seekable (in time).
1845  * Also optionally provides average bitrate detected in media (if non-zero),
1846  * e.g. based on metadata, as it will be posted to the application.
1847  *
1848  * By default, announced average bitrate is estimated, and seekability is assumed
1849  * possible based on estimated bitrate.
1850  */
1851 void
1852 gst_base_parse_set_seek (GstBaseParse * parse,
1853     GstBaseParseSeekable seek, guint bitrate)
1854 {
1855   parse->priv->seekable = seek;
1856   parse->priv->bitrate = bitrate;
1857 }
1858
1859
1860 /**
1861  * gst_base_parse_set_min_frame_size:
1862  * @parse: #GstBaseParse.
1863  * @min_size: Minimum size of the data that this base class should give to
1864  *            subclass.
1865  *
1866  * Subclass can use this function to tell the base class that it needs to
1867  * give at least #min_size buffers.
1868  */
1869 void
1870 gst_base_parse_set_min_frame_size (GstBaseParse * parse, guint min_size)
1871 {
1872   g_return_if_fail (parse != NULL);
1873
1874   GST_BASE_PARSE_LOCK (parse);
1875   parse->priv->min_frame_size = min_size;
1876   GST_LOG_OBJECT (parse, "set frame_min_size: %d", min_size);
1877   GST_BASE_PARSE_UNLOCK (parse);
1878 }
1879
1880 /**
1881  * gst_base_transform_set_passthrough:
1882  * @trans: the #GstBaseParse to set
1883  * @passthrough: boolean indicating passthrough mode.
1884  *
1885  * Set passthrough mode for this parser.  If operating in passthrough,
1886  * incoming buffers are pushed through unmodified.
1887  */
1888 void
1889 gst_base_parse_set_passthrough (GstBaseParse * parse, gboolean passthrough)
1890 {
1891   g_return_if_fail (parse != NULL);
1892
1893   GST_BASE_PARSE_LOCK (parse);
1894   parse->priv->passthrough = passthrough;
1895   GST_LOG_OBJECT (parse, "set passthrough: %d", passthrough);
1896   GST_BASE_PARSE_UNLOCK (parse);
1897 }
1898
1899 /**
1900  * gst_base_transform_set_frame_props:
1901  * @parse: the #GstBaseParse to set
1902  * @fps_num: frames per second (numerator).
1903  * @fps_den: frames per second (denominator).
1904  * @interval: duration update interval in frames.
1905  *
1906  * If frames per second is configured, parser can take care of buffer duration
1907  * and timestamping. If #interval is non-zero (default), then stream duration
1908  * is determined based on frame and byte counts, and updated every #interval
1909  * frames.
1910  */
1911 void
1912 gst_base_parse_set_frame_props (GstBaseParse * parse, guint fps_num,
1913     guint fps_den, gint interval)
1914 {
1915   g_return_if_fail (parse != NULL);
1916
1917   GST_BASE_PARSE_LOCK (parse);
1918   parse->priv->fps_num = fps_num;
1919   parse->priv->fps_den = fps_den;
1920   parse->priv->update_interval = interval;
1921   if (!fps_num || !fps_den) {
1922     GST_DEBUG_OBJECT (parse, "invalid fps (%d/%d), ignoring parameters",
1923         fps_num, fps_den);
1924     fps_num = fps_den = 0;
1925     interval = 0;
1926     parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
1927   } else {
1928     parse->priv->frame_duration =
1929         gst_util_uint64_scale (GST_SECOND, parse->priv->fps_den,
1930         parse->priv->fps_num);
1931   }
1932   GST_LOG_OBJECT (parse, "set fps: %d/%d => duration: %" G_GINT64_FORMAT " ms",
1933       fps_num, fps_den, parse->priv->frame_duration / GST_MSECOND);
1934   GST_LOG_OBJECT (parse, "set update interval: %d", interval);
1935   GST_BASE_PARSE_UNLOCK (parse);
1936 }
1937
1938 /**
1939  * gst_base_transform_get_sync:
1940  * @parse: the #GstBaseParse to query
1941  *
1942  * Returns: TRUE if parser is considered 'in sync'.  That is, frames have been
1943  * continuously successfully parsed and pushed.
1944  */
1945 gboolean
1946 gst_base_parse_get_sync (GstBaseParse * parse)
1947 {
1948   gboolean ret;
1949
1950   g_return_val_if_fail (parse != NULL, FALSE);
1951
1952   GST_BASE_PARSE_LOCK (parse);
1953   /* losing sync is pretty much a discont (and vice versa), no ? */
1954   ret = !parse->priv->discont;
1955   GST_BASE_PARSE_UNLOCK (parse);
1956
1957   GST_DEBUG_OBJECT (parse, "sync: %d", ret);
1958   return ret;
1959 }
1960
1961 /**
1962  * gst_base_transform_get_drain:
1963  * @parse: the #GstBaseParse to query
1964  *
1965  * Returns: TRUE if parser is currently 'draining'.  That is, leftover data
1966  * (e.g. in FLUSH or EOS situation) is being parsed.
1967  */
1968 gboolean
1969 gst_base_parse_get_drain (GstBaseParse * parse)
1970 {
1971   gboolean ret;
1972
1973   g_return_val_if_fail (parse != NULL, FALSE);
1974
1975   GST_BASE_PARSE_LOCK (parse);
1976   /* losing sync is pretty much a discont (and vice versa), no ? */
1977   ret = parse->priv->drain;
1978   GST_BASE_PARSE_UNLOCK (parse);
1979
1980   GST_DEBUG_OBJECT (parse, "drain: %d", ret);
1981   return ret;
1982 }
1983
1984 static gboolean
1985 gst_base_parse_get_duration (GstBaseParse * parse, GstFormat format,
1986     GstClockTime * duration)
1987 {
1988   gboolean res = FALSE;
1989
1990   g_return_val_if_fail (duration != NULL, FALSE);
1991
1992   *duration = GST_CLOCK_TIME_NONE;
1993   if (parse->priv->duration != -1 && format == parse->priv->duration_fmt) {
1994     GST_LOG_OBJECT (parse, "using provided duration");
1995     *duration = parse->priv->duration;
1996     res = TRUE;
1997   } else if (parse->priv->duration != -1) {
1998     GST_LOG_OBJECT (parse, "converting provided duration");
1999     res = gst_base_parse_convert (parse, parse->priv->duration_fmt,
2000         parse->priv->duration, format, (gint64 *) duration);
2001   } else if (format == GST_FORMAT_TIME && parse->priv->estimated_duration != -1) {
2002     GST_LOG_OBJECT (parse, "using estimated duration");
2003     *duration = parse->priv->estimated_duration;
2004     res = TRUE;
2005   }
2006
2007   GST_LOG_OBJECT (parse, "res: %d, duration %" GST_TIME_FORMAT, res,
2008       GST_TIME_ARGS (*duration));
2009   return res;
2010 }
2011
2012 /**
2013  * gst_base_parse_get_querytypes:
2014  * @pad: GstPad
2015  *
2016  * Returns: A table of #GstQueryType items describing supported query types.
2017  */
2018 static const GstQueryType *
2019 gst_base_parse_get_querytypes (GstPad * pad)
2020 {
2021   static const GstQueryType list[] = {
2022     GST_QUERY_POSITION,
2023     GST_QUERY_DURATION,
2024     GST_QUERY_FORMATS,
2025     GST_QUERY_SEEKING,
2026     GST_QUERY_CONVERT,
2027     0
2028   };
2029
2030   return list;
2031 }
2032
2033
2034 /**
2035  * gst_base_parse_query:
2036  * @pad: #GstPad.
2037  * @query: #GstQuery.
2038  *
2039  * Returns: TRUE on success.
2040  */
2041 static gboolean
2042 gst_base_parse_query (GstPad * pad, GstQuery * query)
2043 {
2044   GstBaseParse *parse;
2045   GstBaseParseClass *klass;
2046   gboolean res = FALSE;
2047
2048   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
2049   klass = GST_BASE_PARSE_GET_CLASS (parse);
2050
2051   GST_LOG_OBJECT (parse, "handling query: %" GST_PTR_FORMAT, query);
2052
2053   switch (GST_QUERY_TYPE (query)) {
2054     case GST_QUERY_POSITION:
2055     {
2056       gint64 dest_value;
2057       GstFormat format;
2058
2059       GST_DEBUG_OBJECT (parse, "position query");
2060       gst_query_parse_position (query, &format, NULL);
2061
2062       g_mutex_lock (parse->parse_lock);
2063       if (format == GST_FORMAT_BYTES) {
2064         dest_value = parse->priv->offset;
2065         res = TRUE;
2066       } else if (format == parse->segment.format &&
2067           GST_CLOCK_TIME_IS_VALID (parse->segment.last_stop)) {
2068         dest_value = parse->segment.last_stop;
2069         res = TRUE;
2070       }
2071       g_mutex_unlock (parse->parse_lock);
2072
2073       if (res)
2074         gst_query_set_position (query, format, dest_value);
2075       else {
2076         res = gst_pad_query_default (pad, query);
2077         if (!res) {
2078           /* no precise result, upstream no idea either, then best estimate */
2079           /* priv->offset is updated in both PUSH/PULL modes */
2080           g_mutex_lock (parse->parse_lock);
2081           res = gst_base_parse_convert (parse,
2082               GST_FORMAT_BYTES, parse->priv->offset, format, &dest_value);
2083           g_mutex_unlock (parse->parse_lock);
2084         }
2085       }
2086       break;
2087     }
2088     case GST_QUERY_DURATION:
2089     {
2090       GstFormat format;
2091       GstClockTime duration;
2092
2093       GST_DEBUG_OBJECT (parse, "duration query");
2094       gst_query_parse_duration (query, &format, NULL);
2095
2096       /* consult upstream */
2097       res = gst_pad_query_default (pad, query);
2098
2099       /* otherwise best estimate from us */
2100       if (!res) {
2101         g_mutex_lock (parse->parse_lock);
2102         res = gst_base_parse_get_duration (parse, format, &duration);
2103         g_mutex_unlock (parse->parse_lock);
2104         if (res)
2105           gst_query_set_duration (query, format, duration);
2106       }
2107       break;
2108     }
2109     case GST_QUERY_SEEKING:
2110     {
2111       GstFormat fmt;
2112       GstClockTime duration = GST_CLOCK_TIME_NONE;
2113       gboolean seekable = FALSE;
2114
2115       GST_DEBUG_OBJECT (parse, "seeking query");
2116       gst_query_parse_seeking (query, &fmt, NULL, NULL, NULL);
2117
2118       /* consult upstream */
2119       res = gst_pad_query_default (pad, query);
2120
2121       /* we may be able to help if in TIME */
2122       if (fmt == GST_FORMAT_TIME &&
2123           parse->priv->seekable > GST_BASE_PARSE_SEEK_NONE) {
2124         gst_query_parse_seeking (query, &fmt, &seekable, NULL, NULL);
2125         /* already OK if upstream takes care */
2126         GST_LOG_OBJECT (parse, "upstream handled %d, seekable %d",
2127             res, seekable);
2128         if (!(res && seekable)) {
2129           /* TODO maybe also check upstream provides proper duration ? */
2130           seekable = TRUE;
2131           if (!gst_base_parse_get_duration (parse, GST_FORMAT_TIME, &duration)
2132               || duration == -1) {
2133             seekable = FALSE;
2134           } else {
2135             GstQuery *q;
2136
2137             q = gst_query_new_seeking (GST_FORMAT_BYTES);
2138             if (!gst_pad_peer_query (parse->sinkpad, q)) {
2139               seekable = FALSE;
2140             } else {
2141               gst_query_parse_seeking (q, &fmt, &seekable, NULL, NULL);
2142             }
2143             GST_LOG_OBJECT (parse, "upstream BYTE handled %d, seekable %d",
2144                 res, seekable);
2145             gst_query_unref (q);
2146           }
2147           gst_query_set_seeking (query, GST_FORMAT_TIME, seekable, 0, duration);
2148           res = TRUE;
2149         }
2150       }
2151       break;
2152     }
2153     case GST_QUERY_FORMATS:
2154       gst_query_set_formatsv (query, 3, fmtlist);
2155       res = TRUE;
2156       break;
2157     case GST_QUERY_CONVERT:
2158     {
2159       GstFormat src_format, dest_format;
2160       gint64 src_value, dest_value;
2161
2162       gst_query_parse_convert (query, &src_format, &src_value,
2163           &dest_format, &dest_value);
2164
2165       res = gst_base_parse_convert (parse, src_format, src_value,
2166           dest_format, &dest_value);
2167       if (res) {
2168         gst_query_set_convert (query, src_format, src_value,
2169             dest_format, dest_value);
2170       }
2171       break;
2172     }
2173     default:
2174       res = gst_pad_query_default (pad, query);
2175       break;
2176   }
2177   return res;
2178 }
2179
2180
2181 /**
2182  * gst_base_parse_handle_seek:
2183  * @parse: #GstBaseParse.
2184  * @event: #GstEvent.
2185  *
2186  * Returns: TRUE if seek succeeded.
2187  */
2188 static gboolean
2189 gst_base_parse_handle_seek (GstBaseParse * parse, GstEvent * event)
2190 {
2191   GstBaseParseClass *klass;
2192   gdouble rate;
2193   GstFormat format;
2194   GstSeekFlags flags;
2195   GstSeekType cur_type = GST_SEEK_TYPE_NONE, stop_type;
2196   gboolean flush, update, res = TRUE;
2197   gint64 cur, stop, seekpos;
2198   GstSegment seeksegment = { 0, };
2199   GstFormat dstformat;
2200
2201   klass = GST_BASE_PARSE_GET_CLASS (parse);
2202
2203   gst_event_parse_seek (event, &rate, &format, &flags,
2204       &cur_type, &cur, &stop_type, &stop);
2205
2206   GST_DEBUG_OBJECT (parse, "seek to format %s, "
2207       "start type %d at %" GST_TIME_FORMAT ", end type %d at %"
2208       GST_TIME_FORMAT, gst_format_get_name (format),
2209       cur_type, GST_TIME_ARGS (cur), stop_type, GST_TIME_ARGS (stop));
2210
2211   /* no negative rates yet */
2212   if (rate < 0.0)
2213     goto negative_rate;
2214
2215   if (cur_type != GST_SEEK_TYPE_SET)
2216     goto wrong_type;
2217
2218   /* For any format other than TIME, see if upstream handles
2219    * it directly or fail. For TIME, try upstream, but do it ourselves if
2220    * it fails upstream */
2221   if (format != GST_FORMAT_TIME) {
2222     /* default action delegates to upstream */
2223     return FALSE;
2224   } else {
2225     gst_event_ref (event);
2226     if (gst_pad_push_event (parse->sinkpad, event)) {
2227       return TRUE;
2228     }
2229   }
2230
2231   /* too much estimating going on to support this sensibly,
2232    * and no eos/end-of-segment loop handling either ... */
2233   if ((stop_type == GST_SEEK_TYPE_SET && stop != GST_CLOCK_TIME_NONE) ||
2234       (stop_type != GST_SEEK_TYPE_NONE && stop_type != GST_SEEK_TYPE_SET) ||
2235       (flags & GST_SEEK_FLAG_SEGMENT))
2236     goto wrong_type;
2237   stop = -1;
2238
2239   /* get flush flag */
2240   flush = flags & GST_SEEK_FLAG_FLUSH;
2241
2242   /* copy segment, we need this because we still need the old
2243    * segment when we close the current segment. */
2244   memcpy (&seeksegment, &parse->segment, sizeof (GstSegment));
2245
2246   GST_DEBUG_OBJECT (parse, "configuring seek");
2247   gst_segment_set_seek (&seeksegment, rate, format, flags,
2248       cur_type, cur, stop_type, stop, &update);
2249
2250   /* figure out the last position we need to play. If it's configured (stop !=
2251    * -1), use that, else we play until the total duration of the file */
2252   if ((stop = seeksegment.stop) == -1)
2253     stop = seeksegment.duration;
2254
2255   dstformat = GST_FORMAT_BYTES;
2256   if (!gst_pad_query_convert (parse->srcpad, format, seeksegment.last_stop,
2257           &dstformat, &seekpos)) {
2258     GST_DEBUG_OBJECT (parse, "conversion failed");
2259     return FALSE;
2260   }
2261
2262   GST_DEBUG_OBJECT (parse,
2263       "seek position %" G_GINT64_FORMAT " in bytes: %" G_GINT64_FORMAT, cur,
2264       seekpos);
2265
2266   if (parse->priv->pad_mode == GST_ACTIVATE_PULL) {
2267     gint64 last_stop;
2268
2269     GST_DEBUG_OBJECT (parse, "seek in PULL mode");
2270
2271     if (flush) {
2272       if (parse->srcpad) {
2273         GST_DEBUG_OBJECT (parse, "sending flush start");
2274         gst_pad_push_event (parse->srcpad, gst_event_new_flush_start ());
2275       }
2276     } else {
2277       gst_pad_pause_task (parse->sinkpad);
2278     }
2279
2280     /* we should now be able to grab the streaming thread because we stopped it
2281      * with the above flush/pause code */
2282     GST_PAD_STREAM_LOCK (parse->sinkpad);
2283
2284     /* save current position */
2285     last_stop = parse->segment.last_stop;
2286     GST_DEBUG_OBJECT (parse, "stopped streaming at %" G_GINT64_FORMAT,
2287         last_stop);
2288
2289     /* now commit to new position */
2290
2291     /* prepare for streaming again */
2292     if (flush) {
2293       GST_DEBUG_OBJECT (parse, "sending flush stop");
2294       gst_pad_push_event (parse->srcpad, gst_event_new_flush_stop ());
2295     } else {
2296       if (parse->close_segment)
2297         gst_event_unref (parse->close_segment);
2298
2299       parse->close_segment = gst_event_new_new_segment (TRUE,
2300           parse->segment.rate, parse->segment.format,
2301           parse->segment.accum, parse->segment.last_stop, parse->segment.accum);
2302
2303       /* keep track of our last_stop */
2304       seeksegment.accum = parse->segment.last_stop;
2305
2306       GST_DEBUG_OBJECT (parse, "Created close seg format %d, "
2307           "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
2308           ", pos = %" GST_TIME_FORMAT, format,
2309           GST_TIME_ARGS (parse->segment.accum),
2310           GST_TIME_ARGS (parse->segment.last_stop),
2311           GST_TIME_ARGS (parse->segment.accum));
2312     }
2313
2314     memcpy (&parse->segment, &seeksegment, sizeof (GstSegment));
2315
2316     /* store the newsegment event so it can be sent from the streaming thread. */
2317     if (parse->pending_segment)
2318       gst_event_unref (parse->pending_segment);
2319
2320     /* This will be sent later in _loop() */
2321     parse->pending_segment =
2322         gst_event_new_new_segment (FALSE, parse->segment.rate,
2323         parse->segment.format,
2324         parse->segment.last_stop, stop, parse->segment.last_stop);
2325
2326     GST_DEBUG_OBJECT (parse, "Created newseg format %d, "
2327         "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
2328         ", pos = %" GST_TIME_FORMAT, format,
2329         GST_TIME_ARGS (parse->segment.last_stop),
2330         GST_TIME_ARGS (stop), GST_TIME_ARGS (parse->segment.last_stop));
2331
2332     /* mark discont if we are going to stream from another position. */
2333     if (seekpos != parse->priv->offset) {
2334       GST_DEBUG_OBJECT (parse,
2335           "mark DISCONT, we did a seek to another position");
2336       parse->priv->offset = seekpos;
2337       parse->priv->discont = TRUE;
2338       parse->priv->next_ts = parse->segment.last_stop;
2339       parse->priv->sync_offset = seekpos;
2340     }
2341
2342     /* Start streaming thread if paused */
2343     gst_pad_start_task (parse->sinkpad,
2344         (GstTaskFunction) gst_base_parse_loop, parse->sinkpad);
2345
2346     GST_PAD_STREAM_UNLOCK (parse->sinkpad);
2347   } else {
2348     GstEvent *new_event;
2349     /* The only thing we need to do in PUSH-mode is to send the
2350        seek event (in bytes) to upstream. Segment / flush handling happens
2351        in corresponding src event handlers */
2352     GST_DEBUG_OBJECT (parse, "seek in PUSH mode");
2353     new_event = gst_event_new_seek (rate, GST_FORMAT_BYTES, flush,
2354         GST_SEEK_TYPE_SET, seekpos, stop_type, stop);
2355
2356     res = gst_pad_push_event (parse->sinkpad, new_event);
2357   }
2358
2359 done:
2360   return res;
2361
2362   /* ERRORS */
2363 negative_rate:
2364   {
2365     GST_DEBUG_OBJECT (parse, "negative playback rates are not supported yet.");
2366     res = FALSE;
2367     goto done;
2368   }
2369 wrong_type:
2370   {
2371     GST_DEBUG_OBJECT (parse, "unsupported seek type.");
2372     res = FALSE;
2373     goto done;
2374   }
2375 }
2376
2377 /**
2378  * gst_base_parse_handle_tag:
2379  * @parse: #GstBaseParse.
2380  * @event: #GstEvent.
2381  *
2382  * Checks if bitrates are available from upstream tags so that we don't
2383  * override them later
2384  */
2385 static void
2386 gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event)
2387 {
2388   GstTagList *taglist = NULL;
2389   guint tmp;
2390
2391   gst_event_parse_tag (event, &taglist);
2392
2393   if (gst_tag_list_get_uint (taglist, GST_TAG_MINIMUM_BITRATE, &tmp))
2394     parse->priv->post_min_bitrate = FALSE;
2395   if (gst_tag_list_get_uint (taglist, GST_TAG_BITRATE, &tmp))
2396     parse->priv->post_avg_bitrate = FALSE;
2397   if (gst_tag_list_get_uint (taglist, GST_TAG_MAXIMUM_BITRATE, &tmp))
2398     parse->priv->post_max_bitrate = FALSE;
2399 }
2400
2401 /**
2402  * gst_base_parse_sink_setcaps:
2403  * @pad: #GstPad.
2404  * @caps: #GstCaps.
2405  *
2406  * Returns: TRUE if caps were accepted.
2407  */
2408 static gboolean
2409 gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps)
2410 {
2411   GstBaseParse *parse;
2412   GstBaseParseClass *klass;
2413   gboolean res = TRUE;
2414
2415   parse = GST_BASE_PARSE (GST_PAD_PARENT (pad));
2416   klass = GST_BASE_PARSE_GET_CLASS (parse);
2417
2418   GST_DEBUG_OBJECT (parse, "caps: %" GST_PTR_FORMAT, caps);
2419
2420   if (klass->set_sink_caps)
2421     res = klass->set_sink_caps (parse, caps);
2422
2423   return res && gst_pad_set_caps (pad, caps);
2424 }
2425
2426 static GstStateChangeReturn
2427 gst_base_parse_change_state (GstElement * element, GstStateChange transition)
2428 {
2429   GstBaseParse *parse;
2430   GstStateChangeReturn result;
2431
2432   parse = GST_BASE_PARSE (element);
2433
2434   result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2435
2436   switch (transition) {
2437     case GST_STATE_CHANGE_PAUSED_TO_READY:
2438       gst_base_parse_reset (parse);
2439       break;
2440     default:
2441       break;
2442   }
2443
2444   return result;
2445 }