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