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