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