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