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