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