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