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