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