gstbaseparse.c 120 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* GStreamer
 * Copyright (C) 2008 Nokia Corporation. All rights reserved.
 *   Contact: Stefan Kost <stefan.kost@nokia.com>
 * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/**
 * SECTION:gstbaseparse
 * @short_description: Base class for stream parsers
 * @see_also: #GstBaseTransform
 *
27
 * This base class is for parser elements that process data and splits it
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 * into separate audio/video/whatever frames.
 *
 * It provides for:
 * <itemizedlist>
 *   <listitem><para>One sinkpad and one srcpad</para></listitem>
 *   <listitem><para>Handles state changes</para></listitem>
 *   <listitem><para>Does flushing</para></listitem>
 *   <listitem><para>Push mode</para></listitem>
 *   <listitem><para>Pull mode</para></listitem>
 *   <listitem><para>Handles events (NEWSEGMENT/EOS/FLUSH)</para></listitem>
 *   <listitem><para>Handles seeking in both modes</para></listitem>
 *   <listitem><para>
 *        Handles POSITION/DURATION/SEEKING/FORMAT/CONVERT queries
 *   </para></listitem>
 * </itemizedlist>
 *
 * The purpose of this base class is to provide a basic functionality of
 * a parser and share a lot of rather complex code.
 *
 * Description of the parsing mechanism:
 * <orderedlist>
 * <listitem>
 *   <itemizedlist><title>Set-up phase</title>
 *   <listitem><para>
 *     GstBaseParse class calls @set_sink_caps to inform the subclass about
 *     incoming sinkpad caps. Subclass should set the srcpad caps accordingly.
 *   </para></listitem>
 *   <listitem><para>
 *     GstBaseParse calls @start to inform subclass that data processing is
 *     about to start now.
 *   </para></listitem>
 *   <listitem><para>
 *      At least in this point subclass needs to tell the GstBaseParse class
61
 *      how big data chunks it wants to receive (min_frame_size). It can do
62
63
64
65
66
67
68
69
70
71
72
73
 *      this with @gst_base_parse_set_min_frame_size.
 *   </para></listitem>
 *   <listitem><para>
 *      GstBaseParse class sets up appropriate data passing mode (pull/push)
 *      and starts to process the data.
 *   </para></listitem>
 *   </itemizedlist>
 * </listitem>
 * <listitem>
 *   <itemizedlist>
 *   <title>Parsing phase</title>
 *     <listitem><para>
74
 *       GstBaseParse gathers at least min_frame_size bytes of data either
75
76
77
78
 *       by pulling it from upstream or collecting buffers into internal
 *       #GstAdapter.
 *     </para></listitem>
 *     <listitem><para>
79
 *       A buffer of (at least) min_frame_size bytes is passed to subclass with
80
81
82
83
84
 *       @check_valid_frame. Subclass checks the contents and returns TRUE
 *       if the buffer contains a valid frame. It also needs to set the
 *       @framesize according to the detected frame size. If buffer didn't
 *       contain a valid frame, this call must return FALSE and optionally
 *       set the @skipsize value to inform base class that how many bytes
85
86
 *       it needs to skip in order to find a valid frame. @framesize can always
 *       indicate a new minimum for current frame parsing.  The passed buffer
87
88
 *       is read-only.  Note that @check_valid_frame might receive any small
 *       amount of input data when leftover data is being drained (e.g. at EOS).
89
90
91
92
 *     </para></listitem>
 *     <listitem><para>
 *       After valid frame is found, it will be passed again to subclass with
 *       @parse_frame call. Now subclass is responsible for parsing the
93
94
 *       frame contents and setting the caps, and buffer metadata (e.g.
 *       buffer timestamp and duration, or keyframe if applicable).
95
 *       (although the latter can also be done by GstBaseParse if it is
96
97
98
99
 *       appropriately configured, see below).  Frame is provided with
 *       timestamp derived from upstream (as much as generally possible),
 *       duration obtained form configuration (see below), and offset
 *       if meaningful (in pull mode).
100
101
102
 *     </para></listitem>
 *     <listitem><para>
 *       Finally the buffer can be pushed downstream and parsing loop starts
103
104
105
106
 *       over again.  Just prior to actually pushing the buffer in question,
 *       it is passed to @pre_push_buffer which gives subclass yet one
 *       last chance to examine buffer metadata, or to send some custom (tag)
 *       events, or to perform custom (segment) filtering.
107
108
 *     </para></listitem>
 *     <listitem><para>
109
 *       During the parsing process GstBaseParseClass will handle both srcpad and
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
 *       sinkpad events. They will be passed to subclass if @event or
 *       @src_event callbacks have been provided.
 *     </para></listitem>
 *   </itemizedlist>
 * </listitem>
 * <listitem>
 *   <itemizedlist><title>Shutdown phase</title>
 *   <listitem><para>
 *     GstBaseParse class calls @stop to inform the subclass that data
 *     parsing will be stopped.
 *   </para></listitem>
 *   </itemizedlist>
 * </listitem>
 * </orderedlist>
 *
 * Subclass is responsible for providing pad template caps for
126
127
 * source and sink pads. The pads need to be named "sink" and "src". It also
 * needs to set the fixed caps on srcpad, when the format is ensured (e.g.
128
129
130
131
132
133
134
 * when base class calls subclass' @set_sink_caps function).
 *
 * This base class uses GST_FORMAT_DEFAULT as a meaning of frames. So,
 * subclass conversion routine needs to know that conversion from
 * GST_FORMAT_TIME to GST_FORMAT_DEFAULT must return the
 * frame number that can be found from the given byte position.
 *
135
136
 * GstBaseParse uses subclasses conversion methods also for seeking (or otherwise
 * uses its own default one, see also below).
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
 *
 * Subclass @start and @stop functions will be called to inform the beginning
 * and end of data processing.
 *
 * Things that subclass need to take care of:
 * <itemizedlist>
 *   <listitem><para>Provide pad templates</para></listitem>
 *   <listitem><para>
 *      Fixate the source pad caps when appropriate
 *   </para></listitem>
 *   <listitem><para>
 *      Inform base class how big data chunks should be retrieved. This is
 *      done with @gst_base_parse_set_min_frame_size function.
 *   </para></listitem>
 *   <listitem><para>
 *      Examine data chunks passed to subclass with @check_valid_frame
 *      and tell if they contain a valid frame
 *   </para></listitem>
 *   <listitem><para>
 *      Set the caps and timestamp to frame that is passed to subclass with
 *      @parse_frame function.
 *   </para></listitem>
 *   <listitem><para>Provide conversion functions</para></listitem>
 *   <listitem><para>
 *      Update the duration information with @gst_base_parse_set_duration
 *   </para></listitem>
163
 *   <listitem><para>
164
 *      Optionally passthrough using @gst_base_parse_set_format
165
166
167
 *   </para></listitem>
 *   <listitem><para>
 *      Configure various baseparse parameters using @gst_base_parse_set_seek and
168
 *      @gst_base_parse_set_frame_rate.
169
170
171
172
173
 *   </para></listitem>
 *   <listitem><para>
 *      In particular, if subclass is unable to determine a duration, but
 *      parsing (or specs) yields a frames per seconds rate, then this can be
 *      provided to GstBaseParse to enable it to cater for
174
 *      buffer time metadata (which will be taken from upstream as much as possible).
175
176
177
 *      Internally keeping track of frame durations and respective
 *      sizes that have been pushed provides GstBaseParse with an estimated bitrate.
 *      A default @convert (used if not overriden) will then use these
178
179
180
 *      rates to perform obvious conversions.  These rates are also used to update
 *      (estimated) duration at regular frame intervals.
 *   </para></listitem>
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
 * </itemizedlist>
 *
 */

/* TODO:
 *  - In push mode provide a queue of adapter-"queued" buffers for upstream
 *    buffer metadata
 *  - Queue buffers/events until caps are set
 */

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include <stdlib.h>
#include <string.h>

198
199
#include <gst/base/gstadapter.h>

200
201
#include "gstbaseparse.h"

202
#define MIN_FRAMES_TO_POST_BITRATE 10
203
#define TARGET_DIFFERENCE          (20 * GST_SECOND)
204

205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
GST_DEBUG_CATEGORY_STATIC (gst_base_parse_debug);
#define GST_CAT_DEFAULT gst_base_parse_debug

/* Supported formats */
static GstFormat fmtlist[] = {
  GST_FORMAT_DEFAULT,
  GST_FORMAT_BYTES,
  GST_FORMAT_TIME,
  0
};

#define GST_BASE_PARSE_GET_PRIVATE(obj)  \
    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_PARSE, GstBaseParsePrivate))

struct _GstBaseParsePrivate
{
  GstActivateMode pad_mode;

223
224
  GstAdapter *adapter;

225
226
  gint64 duration;
  GstFormat duration_fmt;
227
  gint64 estimated_duration;
228
229

  guint min_frame_size;
230
231
232
  gboolean passthrough;
  gboolean syncable;
  gboolean has_timing_info;
233
  guint fps_num, fps_den;
234
  gint update_interval;
235
  guint bitrate;
236
237
  guint lead_in, lead_out;
  GstClockTime lead_in_ts, lead_out_ts;
238
239
240

  gboolean discont;
  gboolean flushing;
241
  gboolean drain;
242
243

  gint64 offset;
244
  gint64 sync_offset;
245
246
247
  GstClockTime next_ts;
  GstClockTime prev_ts;
  GstClockTime frame_duration;
248
249
  gboolean seen_keyframe;
  gboolean is_video;
250
251
252

  guint64 framecount;
  guint64 bytecount;
253
  guint64 data_bytecount;
254
  guint64 acc_duration;
255
256
  GstClockTime first_frame_ts;
  gint64 first_frame_offset;
257

258
259
260
261
262
263
  gboolean post_min_bitrate;
  gboolean post_avg_bitrate;
  gboolean post_max_bitrate;
  guint min_bitrate;
  guint avg_bitrate;
  guint max_bitrate;
264
  guint posted_avg_bitrate;
265

266
267
  GList *pending_events;

268
  /* frames/buffers that are queued and ready to go on OK */
269
  GQueue queued_frames;
270

271
  GstBuffer *cache;
272
273
274
275
276
277
278

  /* index entry storage, either ours or provided */
  GstIndex *index;
  gint index_id;
  gboolean own_index;
  /* seek table entries only maintained if upstream is BYTE seekable */
  gboolean upstream_seekable;
279
  gboolean upstream_has_duration;
280
  gint64 upstream_size;
281
282
283
284
  /* minimum distance between two index entries */
  GstClockTimeDiff idx_interval;
  /* ts and offset of last entry added */
  GstClockTime index_last_ts;
285
  gint64 index_last_offset;
286
  gboolean index_last_valid;
287
288
289
290
291

  /* timestamps currently produced are accurate, e.g. started from 0 onwards */
  gboolean exact_position;
  /* seek events are temporarily kept to match them with newsegments */
  GSList *pending_seeks;
292

293
294
295
  /* reverse playback */
  GSList *buffers_pending;
  GSList *buffers_queued;
296
  GSList *buffers_send;
297
298
  GstClockTime last_ts;
  gint64 last_offset;
299
300
301
302
303
304

  /* Newsegment event to be sent after SEEK */
  GstEvent *pending_segment;

  /* Segment event that closes the running segment prior to SEEK */
  GstEvent *close_segment;
305
306
};

307
308
309
310
311
312
313
314
typedef struct _GstBaseParseSeek
{
  GstSegment segment;
  gboolean accurate;
  gint64 offset;
  GstClockTime start_ts;
} GstBaseParseSeek;

315
316
317
318
319
320
321
322
323
static GstElementClass *parent_class = NULL;

static void gst_base_parse_class_init (GstBaseParseClass * klass);
static void gst_base_parse_init (GstBaseParse * parse,
    GstBaseParseClass * klass);

GType
gst_base_parse_get_type (void)
{
324
  static volatile gsize base_parse_type = 0;
325

326
  if (g_once_init_enter (&base_parse_type)) {
327
328
    static const GTypeInfo base_parse_info = {
      sizeof (GstBaseParseClass),
329
330
      (GBaseInitFunc) NULL,
      (GBaseFinalizeFunc) NULL,
331
332
333
334
335
336
337
      (GClassInitFunc) gst_base_parse_class_init,
      NULL,
      NULL,
      sizeof (GstBaseParse),
      0,
      (GInstanceInitFunc) gst_base_parse_init,
    };
338
    GType _type;
339

340
341
342
    _type = g_type_register_static (GST_TYPE_ELEMENT,
        "GstBaseParse", &base_parse_info, G_TYPE_FLAG_ABSTRACT);
    g_once_init_leave (&base_parse_type, _type);
343
  }
344
  return (GType) base_parse_type;
345
346
347
348
}

static void gst_base_parse_finalize (GObject * object);

349
350
351
352
static GstStateChangeReturn gst_base_parse_change_state (GstElement * element,
    GstStateChange transition);
static void gst_base_parse_reset (GstBaseParse * parse);

353
354
355
static void gst_base_parse_set_index (GstElement * element, GstIndex * index);
static GstIndex *gst_base_parse_get_index (GstElement * element);

356
357
358
359
360
361
362
static gboolean gst_base_parse_sink_activate (GstPad * sinkpad);
static gboolean gst_base_parse_sink_activate_push (GstPad * pad,
    gboolean active);
static gboolean gst_base_parse_sink_activate_pull (GstPad * pad,
    gboolean active);
static gboolean gst_base_parse_handle_seek (GstBaseParse * parse,
    GstEvent * event);
363
static void gst_base_parse_handle_tag (GstBaseParse * parse, GstEvent * event);
364
365
366
367
368
369
370
371
372
373
374

static gboolean gst_base_parse_src_event (GstPad * pad, GstEvent * event);
static gboolean gst_base_parse_sink_event (GstPad * pad, GstEvent * event);
static gboolean gst_base_parse_query (GstPad * pad, GstQuery * query);
static gboolean gst_base_parse_sink_setcaps (GstPad * pad, GstCaps * caps);
static const GstQueryType *gst_base_parse_get_querytypes (GstPad * pad);

static GstFlowReturn gst_base_parse_chain (GstPad * pad, GstBuffer * buffer);
static void gst_base_parse_loop (GstPad * pad);

static gboolean gst_base_parse_check_frame (GstBaseParse * parse,
375
    GstBaseParseFrame * frame, guint * framesize, gint * skipsize);
376
static GstFlowReturn gst_base_parse_parse_frame (GstBaseParse * parse,
377
    GstBaseParseFrame * frame);
378
379
380
381
382
383
384
385
386

static gboolean gst_base_parse_sink_eventfunc (GstBaseParse * parse,
    GstEvent * event);

static gboolean gst_base_parse_src_eventfunc (GstBaseParse * parse,
    GstEvent * event);

static void gst_base_parse_drain (GstBaseParse * parse);

387
388
389
static void gst_base_parse_post_bitrates (GstBaseParse * parse,
    gboolean post_min, gboolean post_avg, gboolean post_max);

390
391
static gint64 gst_base_parse_find_offset (GstBaseParse * parse,
    GstClockTime time, gboolean before, GstClockTime * _ts);
392
393
static GstFlowReturn gst_base_parse_locate_time (GstBaseParse * parse,
    GstClockTime * _time, gint64 * _offset);
394
395
396
397

static GstFlowReturn gst_base_parse_process_fragment (GstBaseParse * parse,
    gboolean push_only);

398
399
static gboolean gst_base_parse_is_seekable (GstBaseParse * parse);

400
401
402
403
static void gst_base_parse_frame_free (GstBaseParseFrame * frame);
static GstBaseParseFrame *gst_base_parse_frame_copy_and_clear (GstBaseParseFrame
    * frame);

404
405
406
407
408
409
410
411
412
413
static void
gst_base_parse_clear_queues (GstBaseParse * parse)
{
  g_slist_foreach (parse->priv->buffers_queued, (GFunc) gst_buffer_unref, NULL);
  g_slist_free (parse->priv->buffers_queued);
  parse->priv->buffers_queued = NULL;
  g_slist_foreach (parse->priv->buffers_pending, (GFunc) gst_buffer_unref,
      NULL);
  g_slist_free (parse->priv->buffers_pending);
  parse->priv->buffers_pending = NULL;
414
415
416
  g_slist_foreach (parse->priv->buffers_send, (GFunc) gst_buffer_unref, NULL);
  g_slist_free (parse->priv->buffers_send);
  parse->priv->buffers_send = NULL;
417
418
}

419
420
421
422
static void
gst_base_parse_finalize (GObject * object)
{
  GstBaseParse *parse = GST_BASE_PARSE (object);
423
  GstEvent **p_ev;
424

425
  g_object_unref (parse->priv->adapter);
426

427
428
  if (parse->priv->pending_segment) {
    p_ev = &parse->priv->pending_segment;
429
    gst_event_replace (p_ev, NULL);
430
  }
431
432
  if (parse->priv->close_segment) {
    p_ev = &parse->priv->close_segment;
433
    gst_event_replace (p_ev, NULL);
434
435
436
437
438
439
440
441
442
443
444
445
  }

  if (parse->priv->cache) {
    gst_buffer_unref (parse->priv->cache);
    parse->priv->cache = NULL;
  }

  g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
      NULL);
  g_list_free (parse->priv->pending_events);
  parse->priv->pending_events = NULL;

446
  g_queue_foreach (&parse->priv->queued_frames,
447
      (GFunc) gst_base_parse_frame_free, NULL);
448
  g_queue_clear (&parse->priv->queued_frames);
449

450
451
452
453
454
  if (parse->priv->index) {
    gst_object_unref (parse->priv->index);
    parse->priv->index = NULL;
  }

455
456
  gst_base_parse_clear_queues (parse);

457
458
459
460
461
462
463
  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
gst_base_parse_class_init (GstBaseParseClass * klass)
{
  GObjectClass *gobject_class;
464
  GstElementClass *gstelement_class;
465
466
467
468
469
470

  gobject_class = G_OBJECT_CLASS (klass);
  g_type_class_add_private (klass, sizeof (GstBaseParsePrivate));
  parent_class = g_type_class_peek_parent (klass);
  gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_parse_finalize);

471
472
473
  gstelement_class = (GstElementClass *) klass;
  gstelement_class->change_state =
      GST_DEBUG_FUNCPTR (gst_base_parse_change_state);
474
475
  gstelement_class->set_index = GST_DEBUG_FUNCPTR (gst_base_parse_set_index);
  gstelement_class->get_index = GST_DEBUG_FUNCPTR (gst_base_parse_get_index);
476

477
478
479
480
  /* Default handlers */
  klass->check_valid_frame = gst_base_parse_check_frame;
  klass->parse_frame = gst_base_parse_parse_frame;
  klass->src_event = gst_base_parse_src_eventfunc;
481
  klass->convert = gst_base_parse_convert_default;
482
483
484

  GST_DEBUG_CATEGORY_INIT (gst_base_parse_debug, "baseparse", 0,
      "baseparse element");
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
}

static void
gst_base_parse_init (GstBaseParse * parse, GstBaseParseClass * bclass)
{
  GstPadTemplate *pad_template;

  GST_DEBUG_OBJECT (parse, "gst_base_parse_init");

  parse->priv = GST_BASE_PARSE_GET_PRIVATE (parse);

  pad_template =
      gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
  g_return_if_fail (pad_template != NULL);
  parse->sinkpad = gst_pad_new_from_template (pad_template, "sink");
  gst_pad_set_event_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_sink_event));
  gst_pad_set_setcaps_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_sink_setcaps));
  gst_pad_set_chain_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_chain));
  gst_pad_set_activate_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate));
  gst_pad_set_activatepush_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_push));
  gst_pad_set_activatepull_function (parse->sinkpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_sink_activate_pull));
  gst_element_add_pad (GST_ELEMENT (parse), parse->sinkpad);

  GST_DEBUG_OBJECT (parse, "sinkpad created");

  pad_template =
      gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
  g_return_if_fail (pad_template != NULL);
  parse->srcpad = gst_pad_new_from_template (pad_template, "src");
  gst_pad_set_event_function (parse->srcpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_src_event));
  gst_pad_set_query_type_function (parse->srcpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_get_querytypes));
  gst_pad_set_query_function (parse->srcpad,
      GST_DEBUG_FUNCPTR (gst_base_parse_query));
526
  gst_pad_use_fixed_caps (parse->srcpad);
527
528
529
  gst_element_add_pad (GST_ELEMENT (parse), parse->srcpad);
  GST_DEBUG_OBJECT (parse, "src created");

530
531
  g_queue_init (&parse->priv->queued_frames);

532
  parse->priv->adapter = gst_adapter_new ();
533
534

  parse->priv->pad_mode = GST_ACTIVATE_NONE;
535
536
537
538
539
540

  /* init state */
  gst_base_parse_reset (parse);
  GST_DEBUG_OBJECT (parse, "init ok");
}

541
542
543
/**
 * gst_base_parse_frame_init:
 * @parse: #GstBaseParse.
544
 * @frame: #GstBaseParseFrame.
545
546
547
 *
 * Sets a #GstBaseParseFrame to initial state.  Currently this means
 * all fields are zero-ed.
548
549
 *
 * Since: 0.10.33
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
 */
void
gst_base_parse_frame_init (GstBaseParse * parse, GstBaseParseFrame * frame)
{
  memset (frame, 0, sizeof (*frame));
}

/* clear == frame no longer to be used following this */
static void
gst_base_parse_frame_clear (GstBaseParse * parse, GstBaseParseFrame * frame)
{
  /* limited for now */
  if (frame->buffer) {
    gst_buffer_unref (frame->buffer);
    frame->buffer = NULL;
  }
}

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
/* free frame allocated with copy_and_clear (and not on the stack) */
static void
gst_base_parse_frame_free (GstBaseParseFrame * frame)
{
  gst_base_parse_frame_clear (NULL, frame);
  g_slice_free (GstBaseParseFrame, frame);
}

/* copy frame (taking ownership of contents of passed frame) */
static GstBaseParseFrame *
gst_base_parse_frame_copy_and_clear (GstBaseParseFrame * frame)
{
  GstBaseParseFrame *copy;

  copy = g_slice_dup (GstBaseParseFrame, frame);
  memset (frame, 0, sizeof (GstBaseParseFrame));
  return copy;
}

587
588
589
590
591
static inline void
gst_base_parse_frame_update (GstBaseParse * parse, GstBaseParseFrame * frame,
    GstBuffer * buf)
{
  gst_buffer_replace (&frame->buffer, buf);
592
593
594
595
596
597
598

  parse->flags = 0;

  /* set flags one by one for clarity */
  if (G_UNLIKELY (parse->priv->drain))
    parse->flags |= GST_BASE_PARSE_FLAG_DRAINING;

599
  /* losing sync is pretty much a discont (and vice versa), no ? */
600
601
  if (G_UNLIKELY (parse->priv->discont))
    parse->flags |= GST_BASE_PARSE_FLAG_LOST_SYNC;
602
603
}

604
605
606
607
608
static void
gst_base_parse_reset (GstBaseParse * parse)
{
  GST_OBJECT_LOCK (parse);
  gst_segment_init (&parse->segment, GST_FORMAT_TIME);
609
610
  parse->priv->duration = -1;
  parse->priv->min_frame_size = 1;
611
  parse->priv->discont = TRUE;
612
613
  parse->priv->flushing = FALSE;
  parse->priv->offset = 0;
614
  parse->priv->sync_offset = 0;
615
  parse->priv->update_interval = -1;
616
617
  parse->priv->fps_num = parse->priv->fps_den = 0;
  parse->priv->frame_duration = GST_CLOCK_TIME_NONE;
618
619
  parse->priv->lead_in = parse->priv->lead_out = 0;
  parse->priv->lead_in_ts = parse->priv->lead_out_ts = 0;
620
621
622
623
  parse->priv->bitrate = 0;
  parse->priv->framecount = 0;
  parse->priv->bytecount = 0;
  parse->priv->acc_duration = 0;
624
625
  parse->priv->first_frame_ts = GST_CLOCK_TIME_NONE;
  parse->priv->first_frame_offset = -1;
626
627
  parse->priv->estimated_duration = -1;
  parse->priv->next_ts = 0;
628
629
630
  parse->priv->syncable = TRUE;
  parse->priv->passthrough = FALSE;
  parse->priv->has_timing_info = FALSE;
631
632
633
634
635
636
637
638
  parse->priv->post_min_bitrate = TRUE;
  parse->priv->post_avg_bitrate = TRUE;
  parse->priv->post_max_bitrate = TRUE;
  parse->priv->min_bitrate = G_MAXUINT;
  parse->priv->max_bitrate = 0;
  parse->priv->avg_bitrate = 0;
  parse->priv->posted_avg_bitrate = 0;

639
640
  parse->priv->index_last_ts = GST_CLOCK_TIME_NONE;
  parse->priv->index_last_offset = -1;
641
  parse->priv->index_last_valid = TRUE;
642
  parse->priv->upstream_seekable = FALSE;
643
  parse->priv->upstream_size = 0;
644
  parse->priv->upstream_has_duration = FALSE;
645
  parse->priv->idx_interval = 0;
646
  parse->priv->exact_position = TRUE;
647
  parse->priv->seen_keyframe = FALSE;
648

649
650
651
  parse->priv->last_ts = GST_CLOCK_TIME_NONE;
  parse->priv->last_offset = 0;

652
653
654
  if (parse->priv->pending_segment) {
    gst_event_unref (parse->priv->pending_segment);
    parse->priv->pending_segment = NULL;
655
  }
656

657
658
659
660
  g_list_foreach (parse->priv->pending_events, (GFunc) gst_mini_object_unref,
      NULL);
  g_list_free (parse->priv->pending_events);
  parse->priv->pending_events = NULL;
661

662
663
664
665
  if (parse->priv->cache) {
    gst_buffer_unref (parse->priv->cache);
    parse->priv->cache = NULL;
  }
666
667
668
669

  g_slist_foreach (parse->priv->pending_seeks, (GFunc) g_free, NULL);
  g_slist_free (parse->priv->pending_seeks);
  parse->priv->pending_seeks = NULL;
670
671
  GST_OBJECT_UNLOCK (parse);
}
672

673
/* gst_base_parse_check_frame:
674
675
676
677
678
679
680
 * @parse: #GstBaseParse.
 * @buffer: GstBuffer.
 * @framesize: This will be set to tell the found frame size in bytes.
 * @skipsize: Output parameter that tells how much data needs to be skipped
 *            in order to find the following frame header.
 *
 * Default callback for check_valid_frame.
681
 *
682
683
684
685
 * Returns: Always TRUE.
 */
static gboolean
gst_base_parse_check_frame (GstBaseParse * parse,
686
    GstBaseParseFrame * frame, guint * framesize, gint * skipsize)
687
{
688
  *framesize = GST_BUFFER_SIZE (frame->buffer);
689
690
691
692
693
  *skipsize = 0;
  return TRUE;
}


694
/* gst_base_parse_parse_frame:
695
696
697
698
699
 * @parse: #GstBaseParse.
 * @buffer: #GstBuffer.
 *
 * Default callback for parse_frame.
 */
700
static GstFlowReturn
701
gst_base_parse_parse_frame (GstBaseParse * parse, GstBaseParseFrame * frame)
702
{
703
704
  GstBuffer *buffer = frame->buffer;

705
706
707
708
709
710
711
712
  if (!GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
      GST_CLOCK_TIME_IS_VALID (parse->priv->next_ts)) {
    GST_BUFFER_TIMESTAMP (buffer) = parse->priv->next_ts;
  }
  if (!GST_BUFFER_DURATION_IS_VALID (buffer) &&
      GST_CLOCK_TIME_IS_VALID (parse->priv->frame_duration)) {
    GST_BUFFER_DURATION (buffer) = parse->priv->frame_duration;
  }
713
  return GST_FLOW_OK;
714
715
}

716
/* gst_base_parse_convert:
717
 * @parse: #GstBaseParse.
718
719
720
721
 * @src_format: #GstFormat describing the source format.
 * @src_value: Source value to be converted.
 * @dest_format: #GstFormat defining the converted format.
 * @dest_value: Pointer where the conversion result will be put.
722
 *
723
724
725
 * Converts using configured "convert" vmethod in #GstBaseParse class.
 *
 * Returns: TRUE if conversion was successful.
726
727
 */
static gboolean
728
729
730
gst_base_parse_convert (GstBaseParse * parse,
    GstFormat src_format,
    gint64 src_value, GstFormat dest_format, gint64 * dest_value)
731
{
732
733
  GstBaseParseClass *klass = GST_BASE_PARSE_GET_CLASS (parse);
  gboolean ret;
734

735
736
737
738
  g_return_val_if_fail (dest_value != NULL, FALSE);

  if (!klass->convert)
    return FALSE;
739

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
  ret = klass->convert (parse, src_format, src_value, dest_format, dest_value);

#ifndef GST_DISABLE_GST_DEBUG
  {
    if (ret) {
      if (src_format == GST_FORMAT_TIME && dest_format == GST_FORMAT_BYTES) {
        GST_LOG_OBJECT (parse,
            "TIME -> BYTES: %" GST_TIME_FORMAT " -> %" G_GINT64_FORMAT,
            GST_TIME_ARGS (src_value), *dest_value);
      } else if (dest_format == GST_FORMAT_TIME &&
          src_format == GST_FORMAT_BYTES) {
        GST_LOG_OBJECT (parse,
            "BYTES -> TIME: %" G_GINT64_FORMAT " -> %" GST_TIME_FORMAT,
            src_value, GST_TIME_ARGS (*dest_value));
      } else {
        GST_LOG_OBJECT (parse,
            "%s -> %s: %" G_GINT64_FORMAT " -> %" G_GINT64_FORMAT,
            GST_STR_NULL (gst_format_get_name (src_format)),
            GST_STR_NULL (gst_format_get_name (dest_format)),
            src_value, *dest_value);
      }
    } else {
      GST_DEBUG_OBJECT (parse, "conversion failed");
    }
764
  }
765
#endif
766

767
768
  return ret;
}
769

770
/* gst_base_parse_sink_event:
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
 * @pad: #GstPad that received the event.
 * @event: #GstEvent to be handled.
 *
 * Handler for sink pad events.
 *
 * Returns: TRUE if the event was handled.
 */
static gboolean
gst_base_parse_sink_event (GstPad * pad, GstEvent * event)
{
  GstBaseParse *parse;
  GstBaseParseClass *bclass;
  gboolean handled = FALSE;
  gboolean ret = TRUE;

  parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
  bclass = GST_BASE_PARSE_GET_CLASS (parse);

789
790
  GST_DEBUG_OBJECT (parse, "handling event %d, %s", GST_EVENT_TYPE (event),
      GST_EVENT_TYPE_NAME (event));
791
792
793

  /* Cache all events except EOS, NEWSEGMENT and FLUSH_STOP if we have a
   * pending segment */
794
  if (parse->priv->pending_segment && GST_EVENT_TYPE (event) != GST_EVENT_EOS
795
796
797
      && GST_EVENT_TYPE (event) != GST_EVENT_NEWSEGMENT
      && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_START
      && GST_EVENT_TYPE (event) != GST_EVENT_FLUSH_STOP) {
798
799
800
801
802

    if (GST_EVENT_TYPE (event) == GST_EVENT_TAG)
      /* See if any bitrate tags were posted */
      gst_base_parse_handle_tag (parse, event);

803
804
805
806
807
    parse->priv->pending_events =
        g_list_append (parse->priv->pending_events, event);
    ret = TRUE;
  } else {

808
809
810
811
812
    if (GST_EVENT_TYPE (event) == GST_EVENT_EOS &&
        parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE)
      /* We've not posted bitrate tags yet - do so now */
      gst_base_parse_post_bitrates (parse, TRUE, TRUE, TRUE);

813
814
815
    if (bclass->event)
      handled = bclass->event (parse, event);

816
817
818
    if (!handled)
      handled = gst_base_parse_sink_eventfunc (parse, event);

819
820
821
822
823
824
825
826
827
828
    if (!handled)
      ret = gst_pad_event_default (pad, event);
  }

  gst_object_unref (parse);
  GST_DEBUG_OBJECT (parse, "event handled");
  return ret;
}


829
/* gst_base_parse_sink_eventfunc:
830
831
832
833
834
 * @parse: #GstBaseParse.
 * @event: #GstEvent to be handled.
 *
 * Element-level event handler function.
 *
835
836
837
838
 * The event will be unreffed only if it has been handled and this
 * function returns %TRUE
 *
 * Returns: %TRUE if the event was handled and not need forwarding.
839
840
841
842
843
844
845
846
847
848
849
850
 */
static gboolean
gst_base_parse_sink_eventfunc (GstBaseParse * parse, GstEvent * event)
{
  gboolean handled = FALSE;
  GstEvent **eventp;

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_NEWSEGMENT:
    {
      gdouble rate, applied_rate;
      GstFormat format;
851
      gint64 start, stop, pos, next_ts, offset = 0;
852
853
854
855
856
      gboolean update;

      gst_event_parse_new_segment_full (event, &update, &rate, &applied_rate,
          &format, &start, &stop, &pos);

857
858
859
860
      GST_DEBUG_OBJECT (parse, "newseg rate %g, applied rate %g, "
          "format %d, start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT
          ", pos = %" GST_TIME_FORMAT, rate, applied_rate, format,
          GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (pos));
861
862

      if (format == GST_FORMAT_BYTES) {
863
864
865
        GstClockTime seg_start, seg_stop;
        GstBaseParseSeek *seek = NULL;
        GSList *node;
866
867
868

        /* stop time is allowed to be open-ended, but not start & pos */
        seg_stop = GST_CLOCK_TIME_NONE;
869
        seg_start = 0;
870
        offset = pos;
871

872
873
874
875
876
877
878
879
        GST_OBJECT_LOCK (parse);
        for (node = parse->priv->pending_seeks; node; node = node->next) {
          GstBaseParseSeek *tmp = node->data;

          if (tmp->offset == pos) {
            seek = tmp;
            break;
          }
880
        }
881
882
883
        parse->priv->pending_seeks =
            g_slist_remove (parse->priv->pending_seeks, seek);
        GST_OBJECT_UNLOCK (parse);
884

885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
        if (seek) {
          GST_DEBUG_OBJECT (parse,
              "Matched newsegment to%s seek: %" GST_SEGMENT_FORMAT,
              seek->accurate ? " accurate" : "", &seek->segment);
          seg_start = seek->segment.start;
          seg_stop = seek->segment.stop;
          next_ts = seek->start_ts;
          parse->priv->exact_position = seek->accurate;
          g_free (seek);
        } else {
          /* best attempt convert */
          /* as these are only estimates, stop is kept open-ended to avoid
           * premature cutting */
          gst_base_parse_convert (parse, GST_FORMAT_BYTES, start,
              GST_FORMAT_TIME, (gint64 *) & seg_start);
          parse->priv->exact_position = (start == 0);
          next_ts = seg_start;
        }

        gst_event_unref (event);
        event = gst_event_new_new_segment_full (update, rate, applied_rate,
            GST_FORMAT_TIME, seg_start, seg_stop, seg_start);
        format = GST_FORMAT_TIME;
        start = seg_start;
        stop = seg_stop;
        GST_DEBUG_OBJECT (parse, "Converted incoming segment to TIME. "
            "start = %" GST_TIME_FORMAT ", stop = %" GST_TIME_FORMAT,
            GST_TIME_ARGS (seg_start), GST_TIME_ARGS (seg_stop));
      } else if (format != GST_FORMAT_TIME) {
914
        /* Unknown incoming segment format. Output a default open-ended
915
916
917
918
         * TIME segment */
        gst_event_unref (event);
        event = gst_event_new_new_segment_full (update, rate, applied_rate,
            GST_FORMAT_TIME, 0, GST_CLOCK_TIME_NONE, 0);
919
920
921
        format = GST_FORMAT_TIME;
        next_ts = start = 0;
        stop = GST_CLOCK_TIME_NONE;
922
923
924
925
      } else {
        /* not considered BYTE seekable if it is talking to us in TIME,
         * whatever else it might claim */
        parse->priv->upstream_seekable = FALSE;
926
        next_ts = start;
927
928
929
      }

      gst_segment_set_newsegment_full (&parse->segment, update, rate,
930
          applied_rate, format, start, stop, start);
931
932
933
934

      /* save the segment for later, right before we push a new buffer so that
       * the caps are fixed and the next linked element can receive
       * the segment. */
935
      eventp = &parse->priv->pending_segment;
936
937
938
      gst_event_replace (eventp, event);
      gst_event_unref (event);
      handled = TRUE;
939
940
941

      /* but finish the current segment */
      GST_DEBUG_OBJECT (parse, "draining current segment");
942
943
944
945
      if (parse->segment.rate > 0.0)
        gst_base_parse_drain (parse);
      else
        gst_base_parse_process_fragment (parse, FALSE);
946
      gst_adapter_clear (parse->priv->adapter);
947
      parse->priv->offset = offset;
948
      parse->priv->sync_offset = offset;
949
      parse->priv->next_ts = next_ts;
950
      parse->priv->last_ts = GST_CLOCK_TIME_NONE;
951
      parse->priv->discont = TRUE;
952
      parse->priv->seen_keyframe = FALSE;
953
954
955
956
957
      break;
    }

    case GST_EVENT_FLUSH_START:
      parse->priv->flushing = TRUE;
958
959
960
      handled = gst_pad_push_event (parse->srcpad, gst_event_ref (event));
      if (handled)
        gst_event_unref (event);
961
962
963
      /* Wait for _chain() to exit by taking the srcpad STREAM_LOCK */
      GST_PAD_STREAM_LOCK (parse->srcpad);
      GST_PAD_STREAM_UNLOCK (parse->srcpad);
964

965
966
967
      break;

    case GST_EVENT_FLUSH_STOP:
968
      gst_adapter_clear (parse->priv->adapter);
969
      gst_base_parse_clear_queues (parse);
970
971
      parse->priv->flushing = FALSE;
      parse->priv->discont = TRUE;
972
      parse->priv->last_ts = GST_CLOCK_TIME_NONE;
973
974
975
      break;

    case GST_EVENT_EOS:
976
977
978
979
      if (parse->segment.rate > 0.0)
        gst_base_parse_drain (parse);
      else
        gst_base_parse_process_fragment (parse, FALSE);
980
981
982
983
984
985
986

      /* If we STILL have zero frames processed, fire an error */
      if (parse->priv->framecount == 0) {
        GST_ELEMENT_ERROR (parse, STREAM, WRONG_TYPE,
            ("No valid frames found before end of stream"), (NULL));
      }
      /* newsegment before eos */
987
988
989
      if (parse->priv->pending_segment) {
        gst_pad_push_event (parse->srcpad, parse->priv->pending_segment);
        parse->priv->pending_segment = NULL;
990
      }
991
992
993
994
995
996
997
998
999
1000
      break;

    default:
      break;
  }

  return handled;
}


1001
/* gst_base_parse_src_event:
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
 * @pad: #GstPad that received the event.
 * @event: #GstEvent that was received.
 *
 * Handler for source pad events.
 *
 * Returns: TRUE if the event was handled.
 */
static gboolean
gst_base_parse_src_event (GstPad * pad, GstEvent * event)
{
  GstBaseParse *parse;
  GstBaseParseClass *bclass;
  gboolean handled = FALSE;
  gboolean ret = TRUE;

  parse = GST_BASE_PARSE (gst_pad_get_parent (pad));
  bclass = GST_BASE_PARSE_GET_CLASS (parse);

  GST_DEBUG_OBJECT (parse, "event %d, %s", GST_EVENT_TYPE (event),
      GST_EVENT_TYPE_NAME (event));

  if (bclass->src_event)
    handled = bclass->src_event (parse, event);

  if (!handled)
    ret = gst_pad_event_default (pad, event);

  gst_object_unref (parse);
  return ret;
}

1033
1034
1035
1036
1037
static gboolean
gst_base_parse_is_seekable (GstBaseParse * parse)
{
  /* FIXME: could do more here, e.g. check index or just send data from 0
   * in pull mode and let decoder/sink clip */
1038
  return parse->priv->syncable;
1039
}
1040

1041
/* gst_base_parse_src_eventfunc:
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
 * @parse: #GstBaseParse.
 * @event: #GstEvent that was received.
 *
 * Default srcpad event handler.
 *
 * Returns: TRUE if the event was handled and can be dropped.
 */
static gboolean
gst_base_parse_src_eventfunc (GstBaseParse * parse, GstEvent * event)
{
  gboolean handled = FALSE;

  switch (GST_EVENT_TYPE (event)) {
    case GST_EVENT_SEEK:
    {
1057
      if (gst_base_parse_is_seekable (parse)) {
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
        handled = gst_base_parse_handle_seek (parse, event);
      }
      break;
    }
    default:
      break;
  }
  return handled;
}


1069
/**
1070
 * gst_base_parse_convert_default:
1071
1072
1073
1074
1075
1076
 * @parse: #GstBaseParse.
 * @src_format: #GstFormat describing the source format.
 * @src_value: Source value to be converted.
 * @dest_format: #GstFormat defining the converted format.
 * @dest_value: Pointer where the conversion result will be put.
 *
1077
 * Default implementation of "convert" vmethod in #GstBaseParse class.
1078
1079
 *
 * Returns: TRUE if conversion was successful.
1080
1081
 *
 * Since: 0.10.33
1082
1083
 */
gboolean
1084
gst_base_parse_convert_default (GstBaseParse * parse,
1085
1086
1087
1088
    GstFormat src_format,
    gint64 src_value, GstFormat dest_format, gint64 * dest_value)
{
  gboolean ret = FALSE;
1089
  guint64 bytes, duration;
1090

1091
  if (G_UNLIKELY (src_format == dest_format)) {
1092
1093
1094
1095
    *dest_value = src_value;
    return TRUE;
  }

1096
1097
1098
1099
1100
  if (G_UNLIKELY (src_value == -1)) {
    *dest_value = -1;
    return TRUE;
  }

1101
1102
1103
1104
1105
  if (G_UNLIKELY (src_value == 0)) {
    *dest_value = 0;
    return TRUE;
  }

1106
1107
1108
1109
  /* need at least some frames */
  if (!parse->priv->framecount)
    return FALSE;

1110
1111
  duration = parse->priv->acc_duration / GST_MSECOND;
  bytes = parse->priv->bytecount;
1112
1113

  if (G_UNLIKELY (!duration || !bytes))
1114
1115
1116
1117
1118
1119
    return FALSE;

  if (src_format == GST_FORMAT_BYTES) {
    if (dest_format == GST_FORMAT_TIME) {
      /* BYTES -> TIME conversion */
      GST_DEBUG_OBJECT (parse, "converting bytes -> time");
1120
      *dest_value = gst_util_uint64_scale (src_value, duration, bytes);
1121
1122
1123
1124
1125
1126
1127
      *dest_value *= GST_MSECOND;
      GST_DEBUG_OBJECT (parse, "conversion result: %" G_GINT64_FORMAT " ms",
          *dest_value / GST_MSECOND);
      ret = TRUE;
    }
  } else if (src_format == GST_FORMAT_TIME) {
    if (dest_format == GST_FORMAT_BYTES) {
1128
      GST_DEBUG_OBJECT (parse, "converting time -> bytes");
1129
1130
      *dest_value = gst_util_uint64_scale (src_value / GST_MSECOND, bytes,
          duration);
1131
1132
1133
1134
1135
1136
      GST_DEBUG_OBJECT (parse,
          "time %" G_GINT64_FORMAT " ms in bytes = %" G_GINT64_FORMAT,
          src_value / GST_MSECOND, *dest_value);
      ret = TRUE;
    }
  } else if (src_format == GST_FORMAT_DEFAULT) {
1137
    /* DEFAULT == frame-based */
1138
    if (dest_format == GST_FORMAT_TIME) {
1139
1140
1141
1142
1143
      if (parse->priv->fps_den) {
        *dest_value = gst_util_uint64_scale (src_value,
            GST_SECOND * parse->priv->fps_den, parse->priv->fps_num);
        ret = TRUE;
      }
1144
1145
1146
1147
1148
1149
1150
1151
    } else if (dest_format == GST_FORMAT_BYTES) {
    }
  }

  return ret;
}

static void
1152
gst_base_parse_update_duration (GstBaseParse * baseparse)
1153
1154
1155
1156
{
  GstPad *peer;
  GstBaseParse *parse;

1157
  parse = GST_BASE_PARSE (baseparse);
1158
1159
1160
1161
1162

  peer = gst_pad_get_peer (parse->sinkpad);
  if (peer) {
    GstFormat pformat = GST_FORMAT_BYTES;
    gboolean qres = FALSE;
1163
    gint64 ptot, dest_value;
1164
1165
1166
1167

    qres = gst_pad_query_duration (peer, &pformat, &ptot);
    gst_object_unref (GST_OBJECT (peer));
    if (qres) {
1168
      if (gst_base_parse_convert (parse, pformat, ptot,
1169
              GST_FORMAT_TIME, &dest_value)) {
1170
        parse->priv->estimated_duration = dest_value;
1171
1172
1173
1174
        GST_LOG_OBJECT (parse,
            "updated estimated duration to %" GST_TIME_FORMAT,
            GST_TIME_ARGS (dest_value));
      }
1175
1176
1177
    }
  }
}
1178

1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
static void
gst_base_parse_post_bitrates (GstBaseParse * parse, gboolean post_min,
    gboolean post_avg, gboolean post_max)
{
  GstTagList *taglist = gst_tag_list_new ();

  if (post_min && parse->priv->post_min_bitrate)
    gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
        GST_TAG_MINIMUM_BITRATE, parse->priv->min_bitrate, NULL);

1189
1190
  if (post_avg && parse->priv->post_avg_bitrate) {
    parse->priv->posted_avg_bitrate = parse->priv->avg_bitrate;
1191
1192
    gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE, GST_TAG_BITRATE,
        parse->priv->avg_bitrate, NULL);
1193
  }
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205

  if (post_max && parse->priv->post_max_bitrate)
    gst_tag_list_add (taglist, GST_TAG_MERGE_REPLACE,
        GST_TAG_MAXIMUM_BITRATE, parse->priv->max_bitrate, NULL);

  GST_DEBUG_OBJECT (parse, "Updated bitrates. Min: %u, Avg: %u, Max: %u",
      parse->priv->min_bitrate, parse->priv->avg_bitrate,
      parse->priv->max_bitrate);

  gst_element_found_tags_for_pad (GST_ELEMENT (parse), parse->srcpad, taglist);
}

1206
/* gst_base_parse_update_bitrates:
1207
1208
1209
1210
1211
1212
1213
 * @parse: #GstBaseParse.
 * @buffer: Current frame as a #GstBuffer
 *
 * Keeps track of the minimum and maximum bitrates, and also maintains a
 * running average bitrate of the stream so far.
 */
static void
1214
gst_base_parse_update_bitrates (GstBaseParse * parse, GstBaseParseFrame * frame)
1215
1216
1217
1218
1219
1220
{
  /* Only update the tag on a 10 kbps delta */
  static const gint update_threshold = 10000;

  GstBaseParseClass *klass;
  guint64 data_len, frame_dur;
1221
  gint overhead, frame_bitrate, old_avg_bitrate;
1222
  gboolean update_min = FALSE, update_avg = FALSE, update_max = FALSE;
1223
  GstBuffer *buffer = frame->buffer;
1224
1225
1226

  klass = GST_BASE_PARSE_GET_CLASS (parse);

1227
1228
1229
  overhead = frame->overhead;
  if (overhead == -1)
    return;
1230
1231
1232
1233

  data_len = GST_BUFFER_SIZE (buffer) - overhead;
  parse->priv->data_bytecount += data_len;

1234
1235
  /* duration should be valid by now,
   * either set by subclass or maybe based on fps settings */
1236
  if (GST_BUFFER_DURATION_IS_VALID (buffer) && parse->priv->acc_duration != 0) {
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
    /* Calculate duration of a frame from buffer properties */
    frame_dur = GST_BUFFER_DURATION (buffer);
    parse->priv->avg_bitrate = (8 * parse->priv->data_bytecount * GST_SECOND) /
        parse->priv->acc_duration;

  } else {
    /* No way to figure out frame duration (is this even possible?) */
    return;
  }

1247
1248
1249
  /* override if subclass provided bitrate, e.g. metadata based */
  if (parse->priv->bitrate) {
    parse->priv->avg_bitrate = parse->priv->bitrate;
1250
1251
1252
    /* spread this (confirmed) info ASAP */
    if (parse->priv->posted_avg_bitrate != parse->priv->avg_bitrate)
      gst_base_parse_post_bitrates (parse, FALSE, TRUE, FALSE);
1253
1254
  }

1255
1256
1257
1258
  if (frame_dur)
    frame_bitrate = (8 * data_len * GST_SECOND) / frame_dur;
  else
    return;
1259

1260
1261
1262
  GST_LOG_OBJECT (parse, "frame bitrate %u, avg bitrate %u", frame_bitrate,
      parse->priv->avg_bitrate);

1263
1264
1265
1266
1267
  if (parse->priv->framecount < MIN_FRAMES_TO_POST_BITRATE) {
    goto exit;
  } else if (parse->priv->framecount == MIN_FRAMES_TO_POST_BITRATE) {
    /* always post all at threshold time */
    update_min = update_max = update_avg = TRUE;
1268
1269
1270
  }

  if (G_LIKELY (parse->priv->framecount >= MIN_FRAMES_TO_POST_BITRATE)) {
1271
1272
1273
1274
    if (frame_bitrate < parse->priv->min_bitrate) {
      parse->priv->min_bitrate = frame_bitrate;
      update_min = TRUE;
    }
1275

1276
1277
1278
1279
    if (frame_bitrate > parse->priv->max_bitrate) {
      parse->priv->max_bitrate = frame_bitrate;
      update_max = TRUE;
    }
1280

1281
1282
1283
1284
1285
1286
    old_avg_bitrate = parse->priv->posted_avg_bitrate;
    if ((gint) (old_avg_bitrate - parse->priv->avg_bitrate) > update_threshold
        || (gint) (parse->priv->avg_bitrate - old_avg_bitrate) >
        update_threshold)
      update_avg = TRUE;
  }
1287

1288
  if ((update_min || update_avg || update_max))
1289
    gst_base_parse_post_bitrates (parse, update_min, update_avg, update_max);
1290
1291
1292
1293
1294
1295
1296
1297

  /* If average bitrate changes that much and no valid (time) duration provided,
   * then post a new duration message so applications can update their cached
   * values */
  if (update_avg && !(parse->priv->duration_fmt == GST_FORMAT_TIME &&
          GST_CLOCK_TIME_IS_VALID (parse->priv->duration)))
    gst_element_post_message (GST_ELEMENT (parse),
        gst_message_new_duration (GST_OBJECT (parse), GST_FORMAT_TIME, -1));
1298
1299
1300

exit:
  return;