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