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