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