637e140af6e254c31494a59ad6daac049afab358
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstbaseaudiodecoder.c
1 /* GStreamer
2  * Copyright (C) 2009 Igalia S.L.
3  * Author: Iago Toral Quiroga <itoral@igalia.com>
4  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
5  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
6  *   Contact: Stefan Kost <stefan.kost@nokia.com>
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., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:gstbaseaudiodecoder
26  * @short_description: Base class for audio decoders
27  * @see_also: #GstBaseTransform
28  * @since: 0.10.36
29  *
30  * This base class is for audio decoders turning encoded data into
31  * raw audio samples.
32  *
33  * GstBaseAudioDecoder and subclass should cooperate as follows.
34  * <orderedlist>
35  * <listitem>
36  *   <itemizedlist><title>Configuration</title>
37  *   <listitem><para>
38  *     Initially, GstBaseAudioDecoder calls @start when the decoder element
39  *     is activated, which allows subclass to perform any global setup.
40  *     Base class (context) parameters can already be set according to subclass
41  *     capabilities (or possibly upon receive more information in subsequent
42  *     @set_format).
43  *   </para></listitem>
44  *   <listitem><para>
45  *     GstBaseAudioDecoder calls @set_format to inform subclass of the format
46  *     of input audio data that it is about to receive.
47  *     While unlikely, it might be called more than once, if changing input
48  *     parameters require reconfiguration.
49  *   </para></listitem>
50  *   <listitem><para>
51  *     GstBaseAudioDecoder calls @stop at end of all processing.
52  *   </para></listitem>
53  *   </itemizedlist>
54  * </listitem>
55  * As of configuration stage, and throughout processing, GstBaseAudioDecoder
56  * provides various (context) parameters, e.g. describing the format of
57  * output audio data (valid when output caps have been caps) or current parsing state.
58  * Conversely, subclass can and should configure context to inform
59  * base class of its expectation w.r.t. buffer handling.
60  * <listitem>
61  *   <itemizedlist>
62  *   <title>Data processing</title>
63  *     <listitem><para>
64  *       Base class gathers input data, and optionally allows subclass
65  *       to parse this into subsequently manageable (as defined by subclass)
66  *       chunks.  Such chunks are subsequently referred to as 'frames',
67  *       though they may or may not correspond to 1 (or more) audio format frame.
68  *     </para></listitem>
69  *     <listitem><para>
70  *       Input frame is provided to subclass' @handle_frame.
71  *     </para></listitem>
72  *     <listitem><para>
73  *       If codec processing results in decoded data, subclass should call
74  *       @gst_base_audio_decoder_finish_frame to have decoded data pushed
75  *       downstream.
76  *     </para></listitem>
77  *     <listitem><para>
78  *       Just prior to actually pushing a buffer downstream,
79  *       it is passed to @pre_push.  Subclass should either use this callback
80  *       to arrange for additional downstream pushing or otherwise ensure such
81  *       custom pushing occurs after at least a method call has finished since
82  *       setting src pad caps.
83  *     </para></listitem>
84  *     <listitem><para>
85  *       During the parsing process GstBaseAudioDecoderClass will handle both
86  *       srcpad and sinkpad events. Sink events will be passed to subclass
87  *       if @event callback has been provided.
88  *     </para></listitem>
89  *   </itemizedlist>
90  * </listitem>
91  * <listitem>
92  *   <itemizedlist><title>Shutdown phase</title>
93  *   <listitem><para>
94  *     GstBaseAudioDecoder class calls @stop to inform the subclass that data
95  *     parsing will be stopped.
96  *   </para></listitem>
97  *   </itemizedlist>
98  * </listitem>
99  * </orderedlist>
100  *
101  * Subclass is responsible for providing pad template caps for
102  * source and sink pads. The pads need to be named "sink" and "src". It also
103  * needs to set the fixed caps on srcpad, when the format is ensured.  This
104  * is typically when base class calls subclass' @set_format function, though
105  * it might be delayed until calling @gst_base_audio_decoder_finish_frame.
106  *
107  * In summary, above process should have subclass concentrating on
108  * codec data processing while leaving other matters to base class,
109  * such as most notably timestamp handling.  While it may exert more control
110  * in this area (see e.g. @pre_push), it is very much not recommended.
111  *
112  * In particular, base class will try to arrange for perfect output timestamps
113  * as much as possible while tracking upstream timestamps.
114  * To this end, if deviation between the next ideal expected perfect timestamp
115  * and upstream exceeds #GstBaseAudioDecoder:tolerance, then resync to upstream
116  * occurs (which would happen always if the tolerance mechanism is disabled).
117  *
118  * In non-live pipelines, baseclass can also (configurably) arrange for
119  * output buffer aggregation which may help to redue large(r) numbers of
120  * small(er) buffers being pushed and processed downstream.
121  *
122  * On the other hand, it should be noted that baseclass only provides limited
123  * seeking support (upon explicit subclass request), as full-fledged support
124  * should rather be left to upstream demuxer, parser or alike.  This simple
125  * approach caters for seeking and duration reporting using estimated input
126  * bitrates.
127  *
128  * Things that subclass need to take care of:
129  * <itemizedlist>
130  *   <listitem><para>Provide pad templates</para></listitem>
131  *   <listitem><para>
132  *      Set source pad caps when appropriate
133  *   </para></listitem>
134  *   <listitem><para>
135  *      Set user-configurable properties to sane defaults for format and
136  *      implementing codec at hand, and convey some subclass capabilities and
137  *      expectations in context.
138  *   </para></listitem>
139  *   <listitem><para>
140  *      Accept data in @handle_frame and provide encoded results to
141  *      @gst_base_audio_decoder_finish_frame.  If it is prepared to perform
142  *      PLC, it should also accept NULL data in @handle_frame and provide for
143  *      data for indicated duration.
144  *   </para></listitem>
145  * </itemizedlist>
146  */
147
148 #ifdef HAVE_CONFIG_H
149 #include "config.h"
150 #endif
151
152 #define GST_USE_UNSTABLE_API
153 #include "gstbaseaudiodecoder.h"
154 #include <gst/pbutils/descriptions.h>
155
156 #include <string.h>
157
158 GST_DEBUG_CATEGORY (baseaudiodecoder_debug);
159 #define GST_CAT_DEFAULT baseaudiodecoder_debug
160
161 #define GST_BASE_AUDIO_DECODER_GET_PRIVATE(obj)  \
162     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_DECODER, \
163         GstBaseAudioDecoderPrivate))
164
165 enum
166 {
167   LAST_SIGNAL
168 };
169
170 enum
171 {
172   PROP_0,
173   PROP_LATENCY,
174   PROP_TOLERANCE,
175   PROP_PLC
176 };
177
178 #define DEFAULT_LATENCY    0
179 #define DEFAULT_TOLERANCE  0
180 #define DEFAULT_PLC        FALSE
181
182 typedef struct _GstBaseAudioDecoderContext
183 {
184   /* input */
185   /* (output) audio format */
186   GstAudioInfo info;
187
188   /* parsing state */
189   gboolean eos;
190   gboolean sync;
191
192   /* misc */
193   gint delay;
194
195   /* output */
196   gboolean do_plc;
197   gboolean do_byte_time;
198   gint max_errors;
199   /* MT-protected (with LOCK) */
200   GstClockTime min_latency;
201   GstClockTime max_latency;
202 } GstBaseAudioDecoderContext;
203
204 struct _GstBaseAudioDecoderPrivate
205 {
206   /* activation status */
207   gboolean active;
208
209   /* input base/first ts as basis for output ts */
210   GstClockTime base_ts;
211   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
212   guint64 samples;
213
214   /* collected input data */
215   GstAdapter *adapter;
216   /* tracking input ts for changes */
217   GstClockTime prev_ts;
218   /* frames obtained from input */
219   GQueue frames;
220   /* collected output data */
221   GstAdapter *adapter_out;
222   /* ts and duration for output data collected above */
223   GstClockTime out_ts, out_dur;
224   /* mark outgoing discont */
225   gboolean discont;
226
227   /* subclass gave all it could already */
228   gboolean drained;
229   /* subclass currently being forcibly drained */
230   gboolean force;
231
232   /* input bps estimatation */
233   /* global in bytes seen */
234   guint64 bytes_in;
235   /* global samples sent out */
236   guint64 samples_out;
237   /* bytes flushed during parsing */
238   guint sync_flush;
239   /* error count */
240   gint error_count;
241   /* codec id tag */
242   GstTagList *taglist;
243
244   /* whether circumstances allow output aggregation */
245   gint agg;
246
247   /* reverse playback queues */
248   /* collect input */
249   GList *gather;
250   /* to-be-decoded */
251   GList *decode;
252   /* reversed output */
253   GList *queued;
254
255   /* context storage */
256   GstBaseAudioDecoderContext ctx;
257
258   /* properties */
259   GstClockTime latency;
260   GstClockTime tolerance;
261   gboolean plc;
262
263 };
264
265
266 static void gst_base_audio_decoder_finalize (GObject * object);
267 static void gst_base_audio_decoder_set_property (GObject * object,
268     guint prop_id, const GValue * value, GParamSpec * pspec);
269 static void gst_base_audio_decoder_get_property (GObject * object,
270     guint prop_id, GValue * value, GParamSpec * pspec);
271
272 static void gst_base_audio_decoder_clear_queues (GstBaseAudioDecoder * dec);
273 static GstFlowReturn gst_base_audio_decoder_chain_reverse (GstBaseAudioDecoder *
274     dec, GstBuffer * buf);
275
276 static GstStateChangeReturn gst_base_audio_decoder_change_state (GstElement *
277     element, GstStateChange transition);
278 static gboolean gst_base_audio_decoder_sink_event (GstPad * pad,
279     GstEvent * event);
280 static gboolean gst_base_audio_decoder_src_event (GstPad * pad,
281     GstEvent * event);
282 static gboolean gst_base_audio_decoder_sink_setcaps (GstPad * pad,
283     GstCaps * caps);
284 static gboolean gst_base_audio_decoder_src_setcaps (GstPad * pad,
285     GstCaps * caps);
286 static GstFlowReturn gst_base_audio_decoder_chain (GstPad * pad,
287     GstBuffer * buf);
288 static gboolean gst_base_audio_decoder_src_query (GstPad * pad,
289     GstQuery * query);
290 static gboolean gst_base_audio_decoder_sink_query (GstPad * pad,
291     GstQuery * query);
292 static const GstQueryType *gst_base_audio_decoder_get_query_types (GstPad *
293     pad);
294 static void gst_base_audio_decoder_reset (GstBaseAudioDecoder * dec,
295     gboolean full);
296
297
298 GST_BOILERPLATE (GstBaseAudioDecoder, gst_base_audio_decoder, GstElement,
299     GST_TYPE_ELEMENT);
300
301 static void
302 gst_base_audio_decoder_base_init (gpointer g_class)
303 {
304 }
305
306 static void
307 gst_base_audio_decoder_class_init (GstBaseAudioDecoderClass * klass)
308 {
309   GObjectClass *gobject_class;
310   GstElementClass *element_class;
311
312   gobject_class = G_OBJECT_CLASS (klass);
313   element_class = GST_ELEMENT_CLASS (klass);
314
315   parent_class = g_type_class_peek_parent (klass);
316
317   g_type_class_add_private (klass, sizeof (GstBaseAudioDecoderPrivate));
318
319   GST_DEBUG_CATEGORY_INIT (baseaudiodecoder_debug, "baseaudiodecoder", 0,
320       "baseaudiodecoder element");
321
322   gobject_class->set_property = gst_base_audio_decoder_set_property;
323   gobject_class->get_property = gst_base_audio_decoder_get_property;
324   gobject_class->finalize = gst_base_audio_decoder_finalize;
325
326   element_class->change_state = gst_base_audio_decoder_change_state;
327
328   /* Properties */
329   g_object_class_install_property (gobject_class, PROP_LATENCY,
330       g_param_spec_int64 ("min-latency", "Minimum Latency",
331           "Aggregate output data to a minimum of latency time (ns)",
332           0, G_MAXINT64, DEFAULT_LATENCY,
333           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
334
335   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
336       g_param_spec_int64 ("tolerance", "Tolerance",
337           "Perfect ts while timestamp jitter/imperfection within tolerance (ns)",
338           0, G_MAXINT64, DEFAULT_TOLERANCE,
339           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
340
341   g_object_class_install_property (gobject_class, PROP_PLC,
342       g_param_spec_boolean ("plc", "Packet Loss Concealment",
343           "Perform packet loss concealment (if supported)",
344           DEFAULT_PLC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
345 }
346
347 static void
348 gst_base_audio_decoder_init (GstBaseAudioDecoder * dec,
349     GstBaseAudioDecoderClass * klass)
350 {
351   GstPadTemplate *pad_template;
352
353   GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_init");
354
355   dec->priv = GST_BASE_AUDIO_DECODER_GET_PRIVATE (dec);
356
357   /* Setup sink pad */
358   pad_template =
359       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
360   g_return_if_fail (pad_template != NULL);
361
362   dec->sinkpad = gst_pad_new_from_template (pad_template, "sink");
363   gst_pad_set_event_function (dec->sinkpad,
364       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_event));
365   gst_pad_set_setcaps_function (dec->sinkpad,
366       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_setcaps));
367   gst_pad_set_chain_function (dec->sinkpad,
368       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_chain));
369   gst_pad_set_query_function (dec->sinkpad,
370       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_sink_query));
371   gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
372   GST_DEBUG_OBJECT (dec, "sinkpad created");
373
374   /* Setup source pad */
375   pad_template =
376       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
377   g_return_if_fail (pad_template != NULL);
378
379   dec->srcpad = gst_pad_new_from_template (pad_template, "src");
380   gst_pad_set_setcaps_function (dec->srcpad,
381       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_setcaps));
382   gst_pad_set_event_function (dec->srcpad,
383       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_event));
384   gst_pad_set_query_function (dec->srcpad,
385       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_src_query));
386   gst_pad_set_query_type_function (dec->srcpad,
387       GST_DEBUG_FUNCPTR (gst_base_audio_decoder_get_query_types));
388   gst_pad_use_fixed_caps (dec->srcpad);
389   gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
390   GST_DEBUG_OBJECT (dec, "srcpad created");
391
392   dec->priv->adapter = gst_adapter_new ();
393   dec->priv->adapter_out = gst_adapter_new ();
394   g_queue_init (&dec->priv->frames);
395
396   /* property default */
397   dec->priv->latency = DEFAULT_LATENCY;
398   dec->priv->tolerance = DEFAULT_TOLERANCE;
399   dec->priv->plc = DEFAULT_PLC;
400
401   /* init state */
402   gst_base_audio_decoder_reset (dec, TRUE);
403   GST_DEBUG_OBJECT (dec, "init ok");
404 }
405
406 static void
407 gst_base_audio_decoder_reset (GstBaseAudioDecoder * dec, gboolean full)
408 {
409   GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_reset");
410
411   GST_OBJECT_LOCK (dec);
412
413   if (full) {
414     dec->priv->active = FALSE;
415     dec->priv->bytes_in = 0;
416     dec->priv->samples_out = 0;
417     dec->priv->agg = -1;
418     dec->priv->error_count = 0;
419     gst_base_audio_decoder_clear_queues (dec);
420
421     gst_audio_info_clear (&dec->priv->ctx.info);
422     memset (&dec->priv->ctx, 0, sizeof (dec->priv->ctx));
423
424     if (dec->priv->taglist) {
425       gst_tag_list_free (dec->priv->taglist);
426       dec->priv->taglist = NULL;
427     }
428
429     gst_segment_init (&dec->segment, GST_FORMAT_TIME);
430   }
431
432   g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL);
433   g_queue_clear (&dec->priv->frames);
434   gst_adapter_clear (dec->priv->adapter);
435   gst_adapter_clear (dec->priv->adapter_out);
436   dec->priv->out_ts = GST_CLOCK_TIME_NONE;
437   dec->priv->out_dur = 0;
438   dec->priv->prev_ts = GST_CLOCK_TIME_NONE;
439   dec->priv->drained = TRUE;
440   dec->priv->base_ts = GST_CLOCK_TIME_NONE;
441   dec->priv->samples = 0;
442   dec->priv->discont = TRUE;
443   dec->priv->sync_flush = FALSE;
444
445   GST_OBJECT_UNLOCK (dec);
446 }
447
448 static void
449 gst_base_audio_decoder_finalize (GObject * object)
450 {
451   GstBaseAudioDecoder *dec;
452
453   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (object));
454   dec = GST_BASE_AUDIO_DECODER (object);
455
456   if (dec->priv->adapter) {
457     g_object_unref (dec->priv->adapter);
458   }
459   if (dec->priv->adapter_out) {
460     g_object_unref (dec->priv->adapter_out);
461   }
462
463   G_OBJECT_CLASS (parent_class)->finalize (object);
464 }
465
466 /* automagically perform sanity checking of src caps;
467  * also extracts output data format */
468 static gboolean
469 gst_base_audio_decoder_src_setcaps (GstPad * pad, GstCaps * caps)
470 {
471   GstBaseAudioDecoder *dec;
472   gboolean res = TRUE;
473   guint old_rate;
474
475   dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad));
476
477   GST_DEBUG_OBJECT (dec, "setting src caps %" GST_PTR_FORMAT, caps);
478
479   /* parse caps here to check subclass;
480    * also makes us aware of output format */
481   if (!gst_caps_is_fixed (caps))
482     goto refuse_caps;
483
484   /* adjust ts tracking to new sample rate */
485   old_rate = GST_AUDIO_INFO_RATE (&dec->priv->ctx.info);
486   if (GST_CLOCK_TIME_IS_VALID (dec->priv->base_ts) && old_rate) {
487     dec->priv->base_ts +=
488         GST_FRAMES_TO_CLOCK_TIME (dec->priv->samples, old_rate);
489     dec->priv->samples = 0;
490   }
491
492   if (!gst_audio_info_from_caps (&dec->priv->ctx.info, caps))
493     goto refuse_caps;
494
495   gst_object_unref (dec);
496   return res;
497
498   /* ERRORS */
499 refuse_caps:
500   {
501     GST_WARNING_OBJECT (dec, "rejected caps %" GST_PTR_FORMAT, caps);
502     gst_object_unref (dec);
503     return res;
504   }
505 }
506
507 static gboolean
508 gst_base_audio_decoder_sink_setcaps (GstPad * pad, GstCaps * caps)
509 {
510   GstBaseAudioDecoder *dec;
511   GstBaseAudioDecoderClass *klass;
512   gboolean res = TRUE;
513
514   dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad));
515   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
516
517   GST_DEBUG_OBJECT (dec, "caps: %" GST_PTR_FORMAT, caps);
518
519   /* NOTE pbutils only needed here */
520   /* TODO maybe (only) upstream demuxer/parser etc should handle this ? */
521   if (dec->priv->taglist)
522     gst_tag_list_free (dec->priv->taglist);
523   dec->priv->taglist = gst_tag_list_new ();
524   gst_pb_utils_add_codec_description_to_tag_list (dec->priv->taglist,
525       GST_TAG_AUDIO_CODEC, caps);
526
527   if (klass->set_format)
528     res = klass->set_format (dec, caps);
529
530   g_object_unref (dec);
531   return res;
532 }
533
534 static void
535 gst_base_audio_decoder_setup (GstBaseAudioDecoder * dec)
536 {
537   GstQuery *query;
538   gboolean res;
539
540   /* check if in live pipeline, then latency messing is no-no */
541   query = gst_query_new_latency ();
542   res = gst_pad_peer_query (dec->sinkpad, query);
543   if (res) {
544     gst_query_parse_latency (query, &res, NULL, NULL);
545     res = !res;
546   }
547   gst_query_unref (query);
548
549   /* normalize to bool */
550   dec->priv->agg = !!res;
551 }
552
553 /* mini aggregator combining output buffers into fewer larger ones,
554  * if so allowed/configured */
555 static GstFlowReturn
556 gst_base_audio_decoder_output (GstBaseAudioDecoder * dec, GstBuffer * buf)
557 {
558   GstBaseAudioDecoderClass *klass;
559   GstBaseAudioDecoderPrivate *priv;
560   GstBaseAudioDecoderContext *ctx;
561   GstFlowReturn ret = GST_FLOW_OK;
562   GstBuffer *inbuf = NULL;
563
564   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
565   priv = dec->priv;
566   ctx = &dec->priv->ctx;
567
568   if (G_UNLIKELY (priv->agg < 0))
569     gst_base_audio_decoder_setup (dec);
570
571   if (G_LIKELY (buf)) {
572     g_return_val_if_fail (ctx->info.bpf != 0, GST_FLOW_ERROR);
573
574     GST_LOG_OBJECT (dec, "output buffer of size %d with ts %" GST_TIME_FORMAT
575         ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
576         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
577         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
578
579     /* clip buffer */
580     buf = gst_audio_buffer_clip (buf, &dec->segment, ctx->info.rate,
581         ctx->info.bpf);
582     if (G_UNLIKELY (!buf)) {
583       GST_DEBUG_OBJECT (dec, "no data after clipping to segment");
584     } else {
585       GST_LOG_OBJECT (dec,
586           "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT
587           ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
588           GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
589           GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
590     }
591   } else {
592     GST_DEBUG_OBJECT (dec, "no output buffer");
593   }
594
595 again:
596   inbuf = NULL;
597   if (priv->agg && dec->priv->latency > 0) {
598     gint av;
599     gboolean assemble = FALSE;
600     const GstClockTimeDiff tol = 10 * GST_MSECOND;
601     GstClockTimeDiff diff = -100 * GST_MSECOND;
602
603     av = gst_adapter_available (priv->adapter_out);
604     if (G_UNLIKELY (!buf)) {
605       /* forcibly send current */
606       assemble = TRUE;
607       GST_LOG_OBJECT (dec, "forcing fragment flush");
608     } else if (av && (!GST_BUFFER_TIMESTAMP_IS_VALID (buf) ||
609             !GST_CLOCK_TIME_IS_VALID (priv->out_ts) ||
610             ((diff = GST_CLOCK_DIFF (GST_BUFFER_TIMESTAMP (buf),
611                         priv->out_ts + priv->out_dur)) > tol) || diff < -tol)) {
612       assemble = TRUE;
613       GST_LOG_OBJECT (dec, "buffer %d ms apart from current fragment",
614           (gint) (diff / GST_MSECOND));
615     } else {
616       /* add or start collecting */
617       if (!av) {
618         GST_LOG_OBJECT (dec, "starting new fragment");
619         priv->out_ts = GST_BUFFER_TIMESTAMP (buf);
620       } else {
621         GST_LOG_OBJECT (dec, "adding to fragment");
622       }
623       gst_adapter_push (priv->adapter_out, buf);
624       priv->out_dur += GST_BUFFER_DURATION (buf);
625       av += GST_BUFFER_SIZE (buf);
626       buf = NULL;
627     }
628     if (priv->out_dur > dec->priv->latency)
629       assemble = TRUE;
630     if (av && assemble) {
631       GST_LOG_OBJECT (dec, "assembling fragment");
632       inbuf = buf;
633       buf = gst_adapter_take_buffer (priv->adapter_out, av);
634       GST_BUFFER_TIMESTAMP (buf) = priv->out_ts;
635       GST_BUFFER_DURATION (buf) = priv->out_dur;
636       priv->out_ts = GST_CLOCK_TIME_NONE;
637       priv->out_dur = 0;
638     }
639   }
640
641   if (G_LIKELY (buf)) {
642
643     /* decorate */
644     gst_buffer_set_caps (buf, GST_PAD_CAPS (dec->srcpad));
645
646     if (G_UNLIKELY (priv->discont)) {
647       GST_LOG_OBJECT (dec, "marking discont");
648       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
649       priv->discont = FALSE;
650     }
651
652     if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
653       /* duration should always be valid for raw audio */
654       g_assert (GST_BUFFER_DURATION_IS_VALID (buf));
655       dec->segment.last_stop =
656           GST_BUFFER_TIMESTAMP (buf) + GST_BUFFER_DURATION (buf);
657     }
658
659     if (klass->pre_push) {
660       /* last chance for subclass to do some dirty stuff */
661       ret = klass->pre_push (dec, &buf);
662       if (ret != GST_FLOW_OK || !buf) {
663         GST_DEBUG_OBJECT (dec, "subclass returned %s, buf %p",
664             gst_flow_get_name (ret), buf);
665         if (buf)
666           gst_buffer_unref (buf);
667         goto exit;
668       }
669     }
670
671     GST_LOG_OBJECT (dec, "pushing buffer of size %d with ts %" GST_TIME_FORMAT
672         ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
673         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
674         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
675
676     if (dec->segment.rate > 0.0) {
677       ret = gst_pad_push (dec->srcpad, buf);
678       GST_LOG_OBJECT (dec, "buffer pushed: %s", gst_flow_get_name (ret));
679     } else {
680       ret = GST_FLOW_OK;
681       priv->queued = g_list_prepend (priv->queued, buf);
682       GST_LOG_OBJECT (dec, "buffer queued");
683     }
684
685   exit:
686     if (inbuf) {
687       buf = inbuf;
688       goto again;
689     }
690   }
691
692   return ret;
693 }
694
695 GstFlowReturn
696 gst_base_audio_decoder_finish_frame (GstBaseAudioDecoder * dec, GstBuffer * buf,
697     gint frames)
698 {
699   GstBaseAudioDecoderPrivate *priv;
700   GstBaseAudioDecoderContext *ctx;
701   gint samples = 0;
702   GstClockTime ts, next_ts;
703
704   /* subclass should know what it is producing by now */
705   g_return_val_if_fail (buf == NULL || GST_PAD_CAPS (dec->srcpad) != NULL,
706       GST_FLOW_ERROR);
707   /* subclass should not hand us no data */
708   g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0,
709       GST_FLOW_ERROR);
710   /* no dummy calls please */
711   g_return_val_if_fail (frames != 0, GST_FLOW_ERROR);
712
713   priv = dec->priv;
714   ctx = &dec->priv->ctx;
715
716   GST_LOG_OBJECT (dec, "accepting %d bytes == %d samples for %d frames",
717       buf ? GST_BUFFER_SIZE (buf) : -1,
718       buf ? GST_BUFFER_SIZE (buf) / ctx->info.bpf : -1, frames);
719
720   /* output shoud be whole number of sample frames */
721   if (G_LIKELY (buf && ctx->info.bpf)) {
722     if (GST_BUFFER_SIZE (buf) % ctx->info.bpf)
723       goto wrong_buffer;
724     /* per channel least */
725     samples = GST_BUFFER_SIZE (buf) / ctx->info.bpf;
726   }
727
728   /* frame and ts book-keeping */
729   if (G_UNLIKELY (frames < 0)) {
730     if (G_UNLIKELY (-frames - 1 > priv->frames.length))
731       goto overflow;
732     frames = priv->frames.length + frames + 1;
733   } else if (G_UNLIKELY (frames > priv->frames.length)) {
734     if (G_LIKELY (!priv->force)) {
735       /* no way we can let this pass */
736       g_assert_not_reached ();
737       /* really no way */
738       goto overflow;
739     }
740   }
741
742   if (G_LIKELY (priv->frames.length))
743     ts = GST_BUFFER_TIMESTAMP (priv->frames.head->data);
744   else
745     ts = GST_CLOCK_TIME_NONE;
746
747   GST_DEBUG_OBJECT (dec, "leading frame ts %" GST_TIME_FORMAT,
748       GST_TIME_ARGS (ts));
749
750   while (priv->frames.length && frames) {
751     gst_buffer_unref (g_queue_pop_head (&priv->frames));
752     dec->priv->ctx.delay = dec->priv->frames.length;
753     frames--;
754   }
755
756   /* lock on */
757   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
758     priv->base_ts = ts;
759     GST_DEBUG_OBJECT (dec, "base_ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (ts));
760   }
761
762   if (G_UNLIKELY (!buf))
763     goto exit;
764
765   /* slightly convoluted approach caters for perfect ts if subclass desires */
766   if (GST_CLOCK_TIME_IS_VALID (ts)) {
767     if (dec->priv->tolerance > 0) {
768       GstClockTimeDiff diff;
769
770       g_assert (GST_CLOCK_TIME_IS_VALID (priv->base_ts));
771       next_ts = priv->base_ts +
772           gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
773       GST_LOG_OBJECT (dec, "buffer is %d samples past base_ts %" GST_TIME_FORMAT
774           ", expected ts %" GST_TIME_FORMAT, samples,
775           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
776       diff = GST_CLOCK_DIFF (next_ts, ts);
777       GST_LOG_OBJECT (dec, "ts diff %d ms", (gint) (diff / GST_MSECOND));
778       /* if within tolerance,
779        * discard buffer ts and carry on producing perfect stream,
780        * otherwise resync to ts */
781       if (G_UNLIKELY (diff < -dec->priv->tolerance ||
782               diff > dec->priv->tolerance)) {
783         GST_DEBUG_OBJECT (dec, "base_ts resync");
784         priv->base_ts = ts;
785         priv->samples = 0;
786       }
787     } else {
788       GST_DEBUG_OBJECT (dec, "base_ts resync");
789       priv->base_ts = ts;
790       priv->samples = 0;
791     }
792   }
793
794   /* delayed one-shot stuff until confirmed data */
795   if (priv->taglist) {
796     GST_DEBUG_OBJECT (dec, "codec tag %" GST_PTR_FORMAT, priv->taglist);
797     if (gst_tag_list_is_empty (priv->taglist)) {
798       gst_tag_list_free (priv->taglist);
799     } else {
800       gst_element_found_tags (GST_ELEMENT (dec), priv->taglist);
801     }
802     priv->taglist = NULL;
803   }
804
805   buf = gst_buffer_make_metadata_writable (buf);
806   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
807     GST_BUFFER_TIMESTAMP (buf) =
808         priv->base_ts +
809         GST_FRAMES_TO_CLOCK_TIME (priv->samples, ctx->info.rate);
810     GST_BUFFER_DURATION (buf) = priv->base_ts +
811         GST_FRAMES_TO_CLOCK_TIME (priv->samples + samples, ctx->info.rate) -
812         GST_BUFFER_TIMESTAMP (buf);
813   } else {
814     GST_BUFFER_TIMESTAMP (buf) = GST_CLOCK_TIME_NONE;
815     GST_BUFFER_DURATION (buf) =
816         GST_FRAMES_TO_CLOCK_TIME (samples, ctx->info.rate);
817   }
818   priv->samples += samples;
819   priv->samples_out += samples;
820
821   /* we got data, so note things are looking up */
822   if (G_UNLIKELY (dec->priv->error_count))
823     dec->priv->error_count--;
824
825 exit:
826   return gst_base_audio_decoder_output (dec, buf);
827
828   /* ERRORS */
829 wrong_buffer:
830   {
831     GST_ELEMENT_ERROR (dec, STREAM, ENCODE, (NULL),
832         ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buf),
833             ctx->info.bpf));
834     gst_buffer_unref (buf);
835     return GST_FLOW_ERROR;
836   }
837 overflow:
838   {
839     GST_ELEMENT_ERROR (dec, STREAM, ENCODE,
840         ("received more decoded frames %d than provided %d", frames,
841             priv->frames.length), (NULL));
842     if (buf)
843       gst_buffer_unref (buf);
844     return GST_FLOW_ERROR;
845   }
846 }
847
848 static GstFlowReturn
849 gst_base_audio_decoder_handle_frame (GstBaseAudioDecoder * dec,
850     GstBaseAudioDecoderClass * klass, GstBuffer * buffer)
851 {
852   if (G_LIKELY (buffer)) {
853     /* keep around for admin */
854     GST_LOG_OBJECT (dec, "tracking frame size %d, ts %" GST_TIME_FORMAT,
855         GST_BUFFER_SIZE (buffer),
856         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)));
857     g_queue_push_tail (&dec->priv->frames, buffer);
858     dec->priv->ctx.delay = dec->priv->frames.length;
859     dec->priv->bytes_in += GST_BUFFER_SIZE (buffer);
860   } else {
861     GST_LOG_OBJECT (dec, "providing subclass with NULL frame");
862   }
863
864   return klass->handle_frame (dec, buffer);
865 }
866
867 /* maybe subclass configurable instead, but this allows for a whole lot of
868  * raw samples, so at least quite some encoded ... */
869 #define GST_BASE_AUDIO_DECODER_MAX_SYNC     10 * 8 * 2 * 1024
870
871 static GstFlowReturn
872 gst_base_audio_decoder_push_buffers (GstBaseAudioDecoder * dec, gboolean force)
873 {
874   GstBaseAudioDecoderClass *klass;
875   GstBaseAudioDecoderPrivate *priv;
876   GstBaseAudioDecoderContext *ctx;
877   GstFlowReturn ret = GST_FLOW_OK;
878   GstBuffer *buffer;
879   gint av, flush;
880
881   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
882   priv = dec->priv;
883   ctx = &dec->priv->ctx;
884
885   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
886
887   av = gst_adapter_available (priv->adapter);
888   GST_DEBUG_OBJECT (dec, "available: %d", av);
889
890   while (ret == GST_FLOW_OK) {
891
892     flush = 0;
893     ctx->eos = force;
894
895     if (G_LIKELY (av)) {
896       gint len;
897       GstClockTime ts;
898
899       /* parse if needed */
900       if (klass->parse) {
901         gint offset = 0;
902
903         /* limited (legacy) parsing; avoid whole of baseparse */
904         GST_DEBUG_OBJECT (dec, "parsing available: %d", av);
905         /* piggyback sync state on discont */
906         ctx->sync = !priv->discont;
907         ret = klass->parse (dec, priv->adapter, &offset, &len);
908
909         g_assert (offset <= av);
910         if (offset) {
911           /* jumped a bit */
912           GST_DEBUG_OBJECT (dec, "setting DISCONT");
913           gst_adapter_flush (priv->adapter, offset);
914           flush = offset;
915           /* avoid parsing indefinitely */
916           priv->sync_flush += offset;
917           if (priv->sync_flush > GST_BASE_AUDIO_DECODER_MAX_SYNC)
918             goto parse_failed;
919         }
920
921         if (ret == GST_FLOW_UNEXPECTED) {
922           GST_LOG_OBJECT (dec, "no frame yet");
923           ret = GST_FLOW_OK;
924           break;
925         } else if (ret == GST_FLOW_OK) {
926           GST_LOG_OBJECT (dec, "frame at offset %d of length %d", offset, len);
927           g_assert (offset + len <= av);
928           priv->sync_flush = 0;
929         } else {
930           break;
931         }
932       } else {
933         len = av;
934       }
935       /* track upstream ts, but do not get stuck if nothing new upstream */
936       ts = gst_adapter_prev_timestamp (priv->adapter, NULL);
937       if (ts == priv->prev_ts) {
938         GST_LOG_OBJECT (dec, "ts == prev_ts; discarding");
939         ts = GST_CLOCK_TIME_NONE;
940       } else {
941         priv->prev_ts = ts;
942       }
943       buffer = gst_adapter_take_buffer (priv->adapter, len);
944       buffer = gst_buffer_make_metadata_writable (buffer);
945       GST_BUFFER_TIMESTAMP (buffer) = ts;
946       flush += len;
947     } else {
948       if (!force)
949         break;
950       buffer = NULL;
951     }
952
953     ret = gst_base_audio_decoder_handle_frame (dec, klass, buffer);
954
955     /* do not keep pushing it ... */
956     if (G_UNLIKELY (!av)) {
957       priv->drained = TRUE;
958       break;
959     }
960
961     av -= flush;
962     g_assert (av >= 0);
963   }
964
965   GST_LOG_OBJECT (dec, "done pushing to subclass");
966   return ret;
967
968   /* ERRORS */
969 parse_failed:
970   {
971     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("failed to parse stream"));
972     return GST_FLOW_ERROR;
973   }
974 }
975
976 static GstFlowReturn
977 gst_base_audio_decoder_drain (GstBaseAudioDecoder * dec)
978 {
979   GstFlowReturn ret;
980
981   if (dec->priv->drained)
982     return GST_FLOW_OK;
983   else {
984     /* dispatch reverse pending buffers */
985     /* chain eventually calls upon drain as well, but by that time
986      * gather list should be clear, so ok ... */
987     if (dec->segment.rate < 0.0 && dec->priv->gather)
988       gst_base_audio_decoder_chain_reverse (dec, NULL);
989     /* have subclass give all it can */
990     ret = gst_base_audio_decoder_push_buffers (dec, TRUE);
991     /* ensure all output sent */
992     ret = gst_base_audio_decoder_output (dec, NULL);
993     /* everything should be away now */
994     if (dec->priv->frames.length) {
995       /* not fatal/impossible though if subclass/codec eats stuff */
996       GST_WARNING_OBJECT (dec, "still %d frames left after draining",
997           dec->priv->frames.length);
998       g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL);
999       g_queue_clear (&dec->priv->frames);
1000     }
1001     /* discard (unparsed) leftover */
1002     gst_adapter_clear (dec->priv->adapter);
1003
1004     return ret;
1005   }
1006 }
1007
1008 /* hard == FLUSH, otherwise discont */
1009 static GstFlowReturn
1010 gst_base_audio_decoder_flush (GstBaseAudioDecoder * dec, gboolean hard)
1011 {
1012   GstBaseAudioDecoderClass *klass;
1013   GstFlowReturn ret = GST_FLOW_OK;
1014
1015   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
1016
1017   GST_LOG_OBJECT (dec, "flush hard %d", hard);
1018
1019   if (!hard) {
1020     ret = gst_base_audio_decoder_drain (dec);
1021   } else {
1022     gst_base_audio_decoder_clear_queues (dec);
1023     gst_segment_init (&dec->segment, GST_FORMAT_TIME);
1024     dec->priv->error_count = 0;
1025   }
1026   /* only bother subclass with flushing if known it is already alive
1027    * and kicking out stuff */
1028   if (klass->flush && dec->priv->samples_out > 0)
1029     klass->flush (dec, hard);
1030   /* and get (re)set for the sequel */
1031   gst_base_audio_decoder_reset (dec, FALSE);
1032
1033   return ret;
1034 }
1035
1036 static GstFlowReturn
1037 gst_base_audio_decoder_chain_forward (GstBaseAudioDecoder * dec,
1038     GstBuffer * buffer)
1039 {
1040   GstFlowReturn ret;
1041
1042   /* grab buffer */
1043   gst_adapter_push (dec->priv->adapter, buffer);
1044   buffer = NULL;
1045   /* new stuff, so we can push subclass again */
1046   dec->priv->drained = FALSE;
1047
1048   /* hand to subclass */
1049   ret = gst_base_audio_decoder_push_buffers (dec, FALSE);
1050
1051   GST_LOG_OBJECT (dec, "chain-done");
1052   return ret;
1053 }
1054
1055 static void
1056 gst_base_audio_decoder_clear_queues (GstBaseAudioDecoder * dec)
1057 {
1058   GstBaseAudioDecoderPrivate *priv = dec->priv;
1059
1060   g_list_foreach (priv->queued, (GFunc) gst_mini_object_unref, NULL);
1061   g_list_free (priv->queued);
1062   priv->queued = NULL;
1063   g_list_foreach (priv->gather, (GFunc) gst_mini_object_unref, NULL);
1064   g_list_free (priv->gather);
1065   priv->gather = NULL;
1066   g_list_foreach (priv->decode, (GFunc) gst_mini_object_unref, NULL);
1067   g_list_free (priv->decode);
1068   priv->decode = NULL;
1069 }
1070
1071 /*
1072  * Input:
1073  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1074  *  Discont flag:           D        D        D  D
1075  *
1076  * - Each Discont marks a discont in the decoding order.
1077  *
1078  * for vorbis, each buffer is a keyframe when we have the previous
1079  * buffer. This means that to decode buffer 7, we need buffer 6, which
1080  * arrives out of order.
1081  *
1082  * we first gather buffers in the gather queue until we get a DISCONT. We
1083  * prepend each incomming buffer so that they are in reversed order.
1084  *
1085  *    gather queue:    9  8  7
1086  *    decode queue:
1087  *    output queue:
1088  *
1089  * When a DISCONT is received (buffer 4), we move the gather queue to the
1090  * decode queue. This is simply done be taking the head of the gather queue
1091  * and prepending it to the decode queue. This yields:
1092  *
1093  *    gather queue:
1094  *    decode queue:    7  8  9
1095  *    output queue:
1096  *
1097  * Then we decode each buffer in the decode queue in order and put the output
1098  * buffer in the output queue. The first buffer (7) will not produce any output
1099  * because it needs the previous buffer (6) which did not arrive yet. This
1100  * yields:
1101  *
1102  *    gather queue:
1103  *    decode queue:    7  8  9
1104  *    output queue:    9  8
1105  *
1106  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1107  * completely consumed, we need to keep it around for when we receive buffer
1108  * 6. This yields:
1109  *
1110  *    gather queue:
1111  *    decode queue:    7
1112  *    output queue:    9  8
1113  *
1114  * Then we accumulate more buffers:
1115  *
1116  *    gather queue:    6  5  4
1117  *    decode queue:    7
1118  *    output queue:
1119  *
1120  * prepending to the decode queue on DISCONT yields:
1121  *
1122  *    gather queue:
1123  *    decode queue:    4  5  6  7
1124  *    output queue:
1125  *
1126  * after decoding and keeping buffer 4:
1127  *
1128  *    gather queue:
1129  *    decode queue:    4
1130  *    output queue:    7  6  5
1131  *
1132  * Etc..
1133  */
1134 static GstFlowReturn
1135 gst_base_audio_decoder_flush_decode (GstBaseAudioDecoder * dec)
1136 {
1137   GstBaseAudioDecoderPrivate *priv = dec->priv;
1138   GstFlowReturn res = GST_FLOW_OK;
1139   GList *walk;
1140
1141   walk = priv->decode;
1142
1143   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1144
1145   /* clear buffer and decoder state */
1146   gst_base_audio_decoder_flush (dec, FALSE);
1147
1148   while (walk) {
1149     GList *next;
1150     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1151
1152     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1153         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1154
1155     next = g_list_next (walk);
1156     /* decode buffer, resulting data prepended to output queue */
1157     gst_buffer_ref (buf);
1158     res = gst_base_audio_decoder_chain_forward (dec, buf);
1159
1160     /* if we generated output, we can discard the buffer, else we
1161      * keep it in the queue */
1162     if (priv->queued) {
1163       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", priv->queued->data);
1164       priv->decode = g_list_delete_link (priv->decode, walk);
1165       gst_buffer_unref (buf);
1166     } else {
1167       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1168     }
1169     walk = next;
1170   }
1171
1172   /* drain any aggregation (or otherwise) leftover */
1173   gst_base_audio_decoder_drain (dec);
1174
1175   /* now send queued data downstream */
1176   while (priv->queued) {
1177     GstBuffer *buf = GST_BUFFER_CAST (priv->queued->data);
1178
1179     if (G_LIKELY (res == GST_FLOW_OK)) {
1180       GST_DEBUG_OBJECT (dec, "pushing buffer %p of size %u, "
1181           "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
1182           GST_BUFFER_SIZE (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1183           GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1184       /* should be already, but let's be sure */
1185       buf = gst_buffer_make_metadata_writable (buf);
1186       /* avoid stray DISCONT from forward processing,
1187        * which have no meaning in reverse pushing */
1188       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
1189       res = gst_pad_push (dec->srcpad, buf);
1190     } else {
1191       gst_buffer_unref (buf);
1192     }
1193
1194     priv->queued = g_list_delete_link (priv->queued, priv->queued);
1195   }
1196
1197   return res;
1198 }
1199
1200 static GstFlowReturn
1201 gst_base_audio_decoder_chain_reverse (GstBaseAudioDecoder * dec,
1202     GstBuffer * buf)
1203 {
1204   GstBaseAudioDecoderPrivate *priv = dec->priv;
1205   GstFlowReturn result = GST_FLOW_OK;
1206
1207   /* if we have a discont, move buffers to the decode list */
1208   if (!buf || GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)) {
1209     GST_DEBUG_OBJECT (dec, "received discont");
1210     while (priv->gather) {
1211       GstBuffer *gbuf;
1212
1213       gbuf = GST_BUFFER_CAST (priv->gather->data);
1214       /* remove from the gather list */
1215       priv->gather = g_list_delete_link (priv->gather, priv->gather);
1216       /* copy to decode queue */
1217       priv->decode = g_list_prepend (priv->decode, gbuf);
1218     }
1219     /* decode stuff in the decode queue */
1220     gst_base_audio_decoder_flush_decode (dec);
1221   }
1222
1223   if (G_LIKELY (buf)) {
1224     GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %u, "
1225         "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
1226         GST_BUFFER_SIZE (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1227         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1228
1229     /* add buffer to gather queue */
1230     priv->gather = g_list_prepend (priv->gather, buf);
1231   }
1232
1233   return result;
1234 }
1235
1236 static GstFlowReturn
1237 gst_base_audio_decoder_chain (GstPad * pad, GstBuffer * buffer)
1238 {
1239   GstBaseAudioDecoder *dec;
1240   GstFlowReturn ret;
1241
1242   dec = GST_BASE_AUDIO_DECODER (GST_PAD_PARENT (pad));
1243
1244   GST_LOG_OBJECT (dec,
1245       "received buffer of size %d with ts %" GST_TIME_FORMAT
1246       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
1247       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1248       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1249
1250   if (GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) {
1251     gint64 samples, ts;
1252
1253     /* track present position */
1254     ts = dec->priv->base_ts;
1255     samples = dec->priv->samples;
1256
1257     GST_DEBUG_OBJECT (dec, "handling discont");
1258     gst_base_audio_decoder_flush (dec, FALSE);
1259     dec->priv->discont = TRUE;
1260
1261     /* buffer may claim DISCONT loudly, if it can't tell us where we are now,
1262      * we'll stick to where we were ...
1263      * Particularly useful/needed for upstream BYTE based */
1264     if (dec->segment.rate > 0.0 && !GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1265       GST_DEBUG_OBJECT (dec, "... but restoring previous ts tracking");
1266       dec->priv->base_ts = ts;
1267       dec->priv->samples = samples;
1268     }
1269   }
1270
1271   if (dec->segment.rate > 0.0)
1272     ret = gst_base_audio_decoder_chain_forward (dec, buffer);
1273   else
1274     ret = gst_base_audio_decoder_chain_reverse (dec, buffer);
1275
1276   return ret;
1277 }
1278
1279 /* perform upstream byte <-> time conversion (duration, seeking)
1280  * if subclass allows and if enough data for moderately decent conversion */
1281 static inline gboolean
1282 gst_base_audio_decoder_do_byte (GstBaseAudioDecoder * dec)
1283 {
1284   return dec->priv->ctx.do_byte_time && dec->priv->ctx.info.bpf &&
1285       dec->priv->ctx.info.rate <= dec->priv->samples_out;
1286 }
1287
1288 static gboolean
1289 gst_base_audio_decoder_sink_eventfunc (GstBaseAudioDecoder * dec,
1290     GstEvent * event)
1291 {
1292   gboolean handled = FALSE;
1293
1294   switch (GST_EVENT_TYPE (event)) {
1295     case GST_EVENT_NEWSEGMENT:
1296     {
1297       GstFormat format;
1298       gdouble rate, arate;
1299       gint64 start, stop, time;
1300       gboolean update;
1301
1302       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
1303           &start, &stop, &time);
1304
1305       if (format == GST_FORMAT_TIME) {
1306         GST_DEBUG_OBJECT (dec, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT
1307             " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT
1308             ", rate %g, applied_rate %g",
1309             GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time),
1310             rate, arate);
1311       } else {
1312         GstFormat dformat = GST_FORMAT_TIME;
1313
1314         GST_DEBUG_OBJECT (dec, "received NEW_SEGMENT %" G_GINT64_FORMAT
1315             " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT
1316             ", rate %g, applied_rate %g", start, stop, time, rate, arate);
1317         /* handle newsegment resulting from legacy simple seeking */
1318         /* note that we need to convert this whether or not enough data
1319          * to handle initial newsegment */
1320         if (dec->priv->ctx.do_byte_time &&
1321             gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, start,
1322                 &dformat, &start)) {
1323           /* best attempt convert */
1324           /* as these are only estimates, stop is kept open-ended to avoid
1325            * premature cutting */
1326           GST_DEBUG_OBJECT (dec, "converted to TIME start %" GST_TIME_FORMAT,
1327               GST_TIME_ARGS (start));
1328           format = GST_FORMAT_TIME;
1329           time = start;
1330           stop = GST_CLOCK_TIME_NONE;
1331           /* replace event */
1332           gst_event_unref (event);
1333           event = gst_event_new_new_segment_full (update, rate, arate,
1334               GST_FORMAT_TIME, start, stop, time);
1335         } else {
1336           GST_DEBUG_OBJECT (dec, "unsupported format; ignoring");
1337           break;
1338         }
1339       }
1340
1341       /* finish current segment */
1342       gst_base_audio_decoder_drain (dec);
1343
1344       if (update) {
1345         /* time progressed without data, see if we can fill the gap with
1346          * some concealment data */
1347         GST_DEBUG_OBJECT (dec,
1348             "segment update: plc %d, do_plc %d, last_stop %" GST_TIME_FORMAT,
1349             dec->priv->plc, dec->priv->ctx.do_plc,
1350             GST_TIME_ARGS (dec->segment.last_stop));
1351         if (dec->priv->plc && dec->priv->ctx.do_plc &&
1352             dec->segment.rate > 0.0 && dec->segment.last_stop < start) {
1353           GstBaseAudioDecoderClass *klass;
1354           GstBuffer *buf;
1355
1356           klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
1357           /* hand subclass empty frame with duration that needs covering */
1358           buf = gst_buffer_new ();
1359           GST_BUFFER_DURATION (buf) = start - dec->segment.last_stop;
1360           /* best effort, not much error handling */
1361           gst_base_audio_decoder_handle_frame (dec, klass, buf);
1362         }
1363       } else {
1364         /* prepare for next one */
1365         gst_base_audio_decoder_flush (dec, FALSE);
1366         /* and that's where we time from,
1367          * in case upstream does not come up with anything better
1368          * (e.g. upstream BYTE) */
1369         if (format != GST_FORMAT_TIME) {
1370           dec->priv->base_ts = start;
1371           dec->priv->samples = 0;
1372         }
1373       }
1374
1375       /* and follow along with segment */
1376       gst_segment_set_newsegment_full (&dec->segment, update, rate, arate,
1377           format, start, stop, time);
1378
1379       gst_pad_push_event (dec->srcpad, event);
1380       handled = TRUE;
1381       break;
1382     }
1383
1384     case GST_EVENT_FLUSH_START:
1385       break;
1386
1387     case GST_EVENT_FLUSH_STOP:
1388       /* prepare for fresh start */
1389       gst_base_audio_decoder_flush (dec, TRUE);
1390       break;
1391
1392     case GST_EVENT_EOS:
1393       gst_base_audio_decoder_drain (dec);
1394       break;
1395
1396     default:
1397       break;
1398   }
1399
1400   return handled;
1401 }
1402
1403 static gboolean
1404 gst_base_audio_decoder_sink_event (GstPad * pad, GstEvent * event)
1405 {
1406   GstBaseAudioDecoder *dec;
1407   GstBaseAudioDecoderClass *klass;
1408   gboolean handled = FALSE;
1409   gboolean ret = TRUE;
1410
1411   dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad));
1412   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
1413
1414   GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event),
1415       GST_EVENT_TYPE_NAME (event));
1416
1417   if (klass->event)
1418     handled = klass->event (dec, event);
1419
1420   if (!handled)
1421     handled = gst_base_audio_decoder_sink_eventfunc (dec, event);
1422
1423   if (!handled)
1424     ret = gst_pad_event_default (pad, event);
1425
1426   GST_DEBUG_OBJECT (dec, "event handled");
1427
1428   gst_object_unref (dec);
1429   return ret;
1430 }
1431
1432 static gboolean
1433 gst_base_audio_decoder_do_seek (GstBaseAudioDecoder * dec, GstEvent * event)
1434 {
1435   GstSeekFlags flags;
1436   GstSeekType start_type, end_type;
1437   GstFormat format;
1438   gdouble rate;
1439   gint64 start, start_time, end_time;
1440   GstSegment seek_segment;
1441   guint32 seqnum;
1442
1443   gst_event_parse_seek (event, &rate, &format, &flags, &start_type,
1444       &start_time, &end_type, &end_time);
1445
1446   /* we'll handle plain open-ended flushing seeks with the simple approach */
1447   if (rate != 1.0) {
1448     GST_DEBUG_OBJECT (dec, "unsupported seek: rate");
1449     return FALSE;
1450   }
1451
1452   if (start_type != GST_SEEK_TYPE_SET) {
1453     GST_DEBUG_OBJECT (dec, "unsupported seek: start time");
1454     return FALSE;
1455   }
1456
1457   if (end_type != GST_SEEK_TYPE_NONE ||
1458       (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) {
1459     GST_DEBUG_OBJECT (dec, "unsupported seek: end time");
1460     return FALSE;
1461   }
1462
1463   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
1464     GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing");
1465     return FALSE;
1466   }
1467
1468   memcpy (&seek_segment, &dec->segment, sizeof (seek_segment));
1469   gst_segment_set_seek (&seek_segment, rate, format, flags, start_type,
1470       start_time, end_type, end_time, NULL);
1471   start_time = seek_segment.last_stop;
1472
1473   format = GST_FORMAT_BYTES;
1474   if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time,
1475           &format, &start)) {
1476     GST_DEBUG_OBJECT (dec, "conversion failed");
1477     return FALSE;
1478   }
1479
1480   seqnum = gst_event_get_seqnum (event);
1481   event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags,
1482       GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1);
1483   gst_event_set_seqnum (event, seqnum);
1484
1485   GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %"
1486       G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start);
1487
1488   return gst_pad_push_event (dec->sinkpad, event);
1489 }
1490
1491 static gboolean
1492 gst_base_audio_decoder_src_event (GstPad * pad, GstEvent * event)
1493 {
1494   GstBaseAudioDecoder *dec;
1495   gboolean res = FALSE;
1496
1497   dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad));
1498
1499   GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event),
1500       GST_EVENT_TYPE_NAME (event));
1501
1502   switch (GST_EVENT_TYPE (event)) {
1503     case GST_EVENT_SEEK:
1504     {
1505       GstFormat format, tformat;
1506       gdouble rate;
1507       GstSeekFlags flags;
1508       GstSeekType cur_type, stop_type;
1509       gint64 cur, stop;
1510       gint64 tcur, tstop;
1511       guint32 seqnum;
1512
1513       gst_event_parse_seek (event, &rate, &format, &flags, &cur_type, &cur,
1514           &stop_type, &stop);
1515       seqnum = gst_event_get_seqnum (event);
1516
1517       /* upstream gets a chance first */
1518       if ((res = gst_pad_push_event (dec->sinkpad, event)))
1519         break;
1520
1521       /* if upstream fails for a time seek, maybe we can help if allowed */
1522       if (format == GST_FORMAT_TIME) {
1523         if (gst_base_audio_decoder_do_byte (dec))
1524           res = gst_base_audio_decoder_do_seek (dec, event);
1525         break;
1526       }
1527
1528       /* ... though a non-time seek can be aided as well */
1529       /* First bring the requested format to time */
1530       tformat = GST_FORMAT_TIME;
1531       if (!(res = gst_pad_query_convert (pad, format, cur, &tformat, &tcur)))
1532         goto convert_error;
1533       if (!(res = gst_pad_query_convert (pad, format, stop, &tformat, &tstop)))
1534         goto convert_error;
1535
1536       /* then seek with time on the peer */
1537       event = gst_event_new_seek (rate, GST_FORMAT_TIME,
1538           flags, cur_type, tcur, stop_type, tstop);
1539       gst_event_set_seqnum (event, seqnum);
1540
1541       res = gst_pad_push_event (dec->sinkpad, event);
1542       break;
1543     }
1544     default:
1545       res = gst_pad_push_event (dec->sinkpad, event);
1546       break;
1547   }
1548 done:
1549   gst_object_unref (dec);
1550
1551   return res;
1552
1553   /* ERRORS */
1554 convert_error:
1555   {
1556     GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
1557     goto done;
1558   }
1559 }
1560
1561 /*
1562  * gst_base_audio_encoded_audio_convert:
1563  * @fmt: audio format of the encoded audio
1564  * @bytes: number of encoded bytes
1565  * @samples: number of encoded samples
1566  * @src_format: source format
1567  * @src_value: source value
1568  * @dest_format: destination format
1569  * @dest_value: destination format
1570  *
1571  * Helper function to convert @src_value in @src_format to @dest_value in
1572  * @dest_format for encoded audio data.  Conversion is possible between
1573  * BYTE and TIME format by using estimated bitrate based on
1574  * @samples and @bytes (and @fmt).
1575  */
1576 /* FIXME: make gst_base_audio_encoded_audio_convert() public? */
1577 static gboolean
1578 gst_base_audio_encoded_audio_convert (GstAudioInfo * fmt,
1579     gint64 bytes, gint64 samples, GstFormat src_format,
1580     gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
1581 {
1582   gboolean res = FALSE;
1583
1584   g_return_val_if_fail (dest_format != NULL, FALSE);
1585   g_return_val_if_fail (dest_value != NULL, FALSE);
1586
1587   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
1588           src_value == -1)) {
1589     if (dest_value)
1590       *dest_value = src_value;
1591     return TRUE;
1592   }
1593
1594   if (samples == 0 || bytes == 0 || fmt->rate == 0) {
1595     GST_DEBUG ("not enough metadata yet to convert");
1596     goto exit;
1597   }
1598
1599   bytes *= fmt->rate;
1600
1601   switch (src_format) {
1602     case GST_FORMAT_BYTES:
1603       switch (*dest_format) {
1604         case GST_FORMAT_TIME:
1605           *dest_value = gst_util_uint64_scale (src_value,
1606               GST_SECOND * samples, bytes);
1607           res = TRUE;
1608           break;
1609         default:
1610           res = FALSE;
1611       }
1612       break;
1613     case GST_FORMAT_TIME:
1614       switch (*dest_format) {
1615         case GST_FORMAT_BYTES:
1616           *dest_value = gst_util_uint64_scale (src_value, bytes,
1617               samples * GST_SECOND);
1618           res = TRUE;
1619           break;
1620         default:
1621           res = FALSE;
1622       }
1623       break;
1624     default:
1625       res = FALSE;
1626   }
1627
1628 exit:
1629   return res;
1630 }
1631
1632 static gboolean
1633 gst_base_audio_decoder_sink_query (GstPad * pad, GstQuery * query)
1634 {
1635   gboolean res = TRUE;
1636   GstBaseAudioDecoder *dec;
1637
1638   dec = GST_BASE_AUDIO_DECODER (gst_pad_get_parent (pad));
1639
1640   switch (GST_QUERY_TYPE (query)) {
1641     case GST_QUERY_FORMATS:
1642     {
1643       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1644       res = TRUE;
1645       break;
1646     }
1647     case GST_QUERY_CONVERT:
1648     {
1649       GstFormat src_fmt, dest_fmt;
1650       gint64 src_val, dest_val;
1651
1652       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1653       if (!(res = gst_base_audio_encoded_audio_convert (&dec->priv->ctx.info,
1654                   dec->priv->bytes_in, dec->priv->samples_out,
1655                   src_fmt, src_val, &dest_fmt, &dest_val)))
1656         goto error;
1657       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1658       break;
1659     }
1660     default:
1661       res = gst_pad_query_default (pad, query);
1662       break;
1663   }
1664
1665 error:
1666   gst_object_unref (dec);
1667   return res;
1668 }
1669
1670 static const GstQueryType *
1671 gst_base_audio_decoder_get_query_types (GstPad * pad)
1672 {
1673   static const GstQueryType gst_base_audio_decoder_src_query_types[] = {
1674     GST_QUERY_POSITION,
1675     GST_QUERY_DURATION,
1676     GST_QUERY_CONVERT,
1677     GST_QUERY_LATENCY,
1678     0
1679   };
1680
1681   return gst_base_audio_decoder_src_query_types;
1682 }
1683
1684 /* FIXME ? are any of these queries (other than latency) a decoder's business ??
1685  * also, the conversion stuff might seem to make sense, but seems to not mind
1686  * segment stuff etc at all
1687  * Supposedly that's backward compatibility ... */
1688 static gboolean
1689 gst_base_audio_decoder_src_query (GstPad * pad, GstQuery * query)
1690 {
1691   GstBaseAudioDecoder *dec;
1692   GstPad *peerpad;
1693   gboolean res = FALSE;
1694
1695   dec = GST_BASE_AUDIO_DECODER (GST_PAD_PARENT (pad));
1696   peerpad = gst_pad_get_peer (GST_PAD (dec->sinkpad));
1697
1698   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
1699
1700   switch (GST_QUERY_TYPE (query)) {
1701     case GST_QUERY_DURATION:
1702     {
1703       GstFormat format;
1704
1705       /* upstream in any case */
1706       if ((res = gst_pad_query_default (pad, query)))
1707         break;
1708
1709       gst_query_parse_duration (query, &format, NULL);
1710       /* try answering TIME by converting from BYTE if subclass allows  */
1711       if (format == GST_FORMAT_TIME && gst_base_audio_decoder_do_byte (dec)) {
1712         gint64 value;
1713
1714         format = GST_FORMAT_BYTES;
1715         if (gst_pad_query_peer_duration (dec->sinkpad, &format, &value)) {
1716           GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value);
1717           format = GST_FORMAT_TIME;
1718           if (gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, value,
1719                   &format, &value)) {
1720             gst_query_set_duration (query, GST_FORMAT_TIME, value);
1721             res = TRUE;
1722           }
1723         }
1724       }
1725       break;
1726     }
1727     case GST_QUERY_POSITION:
1728     {
1729       GstFormat format;
1730       gint64 time, value;
1731
1732       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
1733         GST_LOG_OBJECT (dec, "returning peer response");
1734         break;
1735       }
1736
1737       /* we start from the last seen time */
1738       time = dec->segment.last_stop;
1739       /* correct for the segment values */
1740       time = gst_segment_to_stream_time (&dec->segment, GST_FORMAT_TIME, time);
1741
1742       GST_LOG_OBJECT (dec,
1743           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
1744
1745       /* and convert to the final format */
1746       gst_query_parse_position (query, &format, NULL);
1747       if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time,
1748                   &format, &value)))
1749         break;
1750
1751       gst_query_set_position (query, format, value);
1752
1753       GST_LOG_OBJECT (dec,
1754           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
1755           format);
1756       break;
1757     }
1758     case GST_QUERY_FORMATS:
1759     {
1760       gst_query_set_formats (query, 3,
1761           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1762       res = TRUE;
1763       break;
1764     }
1765     case GST_QUERY_CONVERT:
1766     {
1767       GstFormat src_fmt, dest_fmt;
1768       gint64 src_val, dest_val;
1769
1770       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1771       if (!(res = gst_audio_info_convert (&dec->priv->ctx.info,
1772                   src_fmt, src_val, dest_fmt, &dest_val)))
1773         break;
1774       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1775       break;
1776     }
1777     case GST_QUERY_LATENCY:
1778     {
1779       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
1780         gboolean live;
1781         GstClockTime min_latency, max_latency;
1782
1783         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1784         GST_DEBUG_OBJECT (dec, "Peer latency: live %d, min %"
1785             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1786             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1787
1788         GST_OBJECT_LOCK (dec);
1789         /* add our latency */
1790         if (min_latency != -1)
1791           min_latency += dec->priv->ctx.min_latency;
1792         if (max_latency != -1)
1793           max_latency += dec->priv->ctx.max_latency;
1794         GST_OBJECT_UNLOCK (dec);
1795
1796         gst_query_set_latency (query, live, min_latency, max_latency);
1797       }
1798       break;
1799     }
1800     default:
1801       res = gst_pad_query_default (pad, query);
1802       break;
1803   }
1804
1805   gst_object_unref (peerpad);
1806   return res;
1807 }
1808
1809 static gboolean
1810 gst_base_audio_decoder_stop (GstBaseAudioDecoder * dec)
1811 {
1812   GstBaseAudioDecoderClass *klass;
1813   gboolean ret = TRUE;
1814
1815   GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_stop");
1816
1817   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
1818
1819   if (klass->stop) {
1820     ret = klass->stop (dec);
1821   }
1822
1823   /* clean up */
1824   gst_base_audio_decoder_reset (dec, TRUE);
1825
1826   if (ret)
1827     dec->priv->active = FALSE;
1828
1829   return TRUE;
1830 }
1831
1832 static gboolean
1833 gst_base_audio_decoder_start (GstBaseAudioDecoder * dec)
1834 {
1835   GstBaseAudioDecoderClass *klass;
1836   gboolean ret = TRUE;
1837
1838   GST_DEBUG_OBJECT (dec, "gst_base_audio_decoder_start");
1839
1840   klass = GST_BASE_AUDIO_DECODER_GET_CLASS (dec);
1841
1842   /* arrange clean state */
1843   gst_base_audio_decoder_reset (dec, TRUE);
1844
1845   if (klass->start) {
1846     ret = klass->start (dec);
1847   }
1848
1849   if (ret)
1850     dec->priv->active = TRUE;
1851
1852   return TRUE;
1853 }
1854
1855 static void
1856 gst_base_audio_decoder_get_property (GObject * object, guint prop_id,
1857     GValue * value, GParamSpec * pspec)
1858 {
1859   GstBaseAudioDecoder *dec;
1860
1861   dec = GST_BASE_AUDIO_DECODER (object);
1862
1863   switch (prop_id) {
1864     case PROP_LATENCY:
1865       g_value_set_int64 (value, dec->priv->latency);
1866       break;
1867     case PROP_TOLERANCE:
1868       g_value_set_int64 (value, dec->priv->tolerance);
1869       break;
1870     case PROP_PLC:
1871       g_value_set_boolean (value, dec->priv->plc);
1872       break;
1873     default:
1874       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1875       break;
1876   }
1877 }
1878
1879 static void
1880 gst_base_audio_decoder_set_property (GObject * object, guint prop_id,
1881     const GValue * value, GParamSpec * pspec)
1882 {
1883   GstBaseAudioDecoder *dec;
1884
1885   dec = GST_BASE_AUDIO_DECODER (object);
1886
1887   switch (prop_id) {
1888     case PROP_LATENCY:
1889       dec->priv->latency = g_value_get_int64 (value);
1890       break;
1891     case PROP_TOLERANCE:
1892       dec->priv->tolerance = g_value_get_int64 (value);
1893       break;
1894     case PROP_PLC:
1895       dec->priv->plc = g_value_get_boolean (value);
1896       break;
1897     default:
1898       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1899       break;
1900   }
1901 }
1902
1903 static GstStateChangeReturn
1904 gst_base_audio_decoder_change_state (GstElement * element,
1905     GstStateChange transition)
1906 {
1907   GstBaseAudioDecoder *codec;
1908   GstStateChangeReturn ret;
1909
1910   codec = GST_BASE_AUDIO_DECODER (element);
1911
1912   switch (transition) {
1913     case GST_STATE_CHANGE_NULL_TO_READY:
1914       break;
1915     case GST_STATE_CHANGE_READY_TO_PAUSED:
1916       if (!gst_base_audio_decoder_start (codec)) {
1917         goto start_failed;
1918       }
1919       break;
1920     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1921       break;
1922     default:
1923       break;
1924   }
1925
1926   ret = parent_class->change_state (element, transition);
1927
1928   switch (transition) {
1929     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1930       break;
1931     case GST_STATE_CHANGE_PAUSED_TO_READY:
1932       if (!gst_base_audio_decoder_stop (codec)) {
1933         goto stop_failed;
1934       }
1935       break;
1936     case GST_STATE_CHANGE_READY_TO_NULL:
1937       break;
1938     default:
1939       break;
1940   }
1941
1942   return ret;
1943
1944 start_failed:
1945   {
1946     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to start codec"));
1947     return GST_STATE_CHANGE_FAILURE;
1948   }
1949 stop_failed:
1950   {
1951     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to stop codec"));
1952     return GST_STATE_CHANGE_FAILURE;
1953   }
1954 }
1955
1956 GstFlowReturn
1957 _gst_base_audio_decoder_error (GstBaseAudioDecoder * dec, gint weight,
1958     GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file,
1959     const gchar * function, gint line)
1960 {
1961   if (txt)
1962     GST_WARNING_OBJECT (dec, "error: %s", txt);
1963   if (dbg)
1964     GST_WARNING_OBJECT (dec, "error: %s", dbg);
1965   dec->priv->error_count += weight;
1966   dec->priv->discont = TRUE;
1967   if (dec->priv->ctx.max_errors < dec->priv->error_count) {
1968     gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR,
1969         domain, code, txt, dbg, file, function, line);
1970     return GST_FLOW_ERROR;
1971   } else {
1972     return GST_FLOW_OK;
1973   }
1974 }
1975
1976 /**
1977  * gst_base_audio_decoder_get_audio_info:
1978  * @dec: a #GstBaseAudioDecoder
1979  *
1980  * Returns: a #GstAudioInfo describing the input audio format
1981  *
1982  * Since: 0.10.36
1983  */
1984 GstAudioInfo *
1985 gst_base_audio_decoder_get_audio_info (GstBaseAudioDecoder * dec)
1986 {
1987   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), NULL);
1988
1989   return &dec->priv->ctx.info;
1990 }
1991
1992 /**
1993  * gst_base_audio_decoder_set_plc_aware:
1994  * @dec: a #GstBaseAudioDecoder
1995  * @plc: new plc state
1996  *
1997  * Indicates whether or not subclass handles packet loss concealment (plc).
1998  *
1999  * Since: 0.10.36
2000  */
2001 void
2002 gst_base_audio_decoder_set_plc_aware (GstBaseAudioDecoder * dec, gboolean plc)
2003 {
2004   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2005
2006   dec->priv->ctx.do_plc = plc;
2007 }
2008
2009 /**
2010  * gst_base_audio_decoder_get_plc_aware:
2011  * @dec: a #GstBaseAudioDecoder
2012  *
2013  * Returns: currently configured plc handling
2014  *
2015  * Since: 0.10.36
2016  */
2017 gint
2018 gst_base_audio_decoder_get_plc_aware (GstBaseAudioDecoder * dec)
2019 {
2020   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0);
2021
2022   return dec->priv->ctx.do_plc;
2023 }
2024
2025 /**
2026  * gst_base_audio_decoder_set_byte_time:
2027  * @dec: a #GstBaseAudioDecoder
2028  * @enabled: whether to enable byte to time conversion
2029  *
2030  * Allows baseclass to perform byte to time estimated conversion.
2031  *
2032  * Since: 0.10.36
2033  */
2034 void
2035 gst_base_audio_decoder_set_byte_time (GstBaseAudioDecoder * dec,
2036     gboolean enabled)
2037 {
2038   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2039
2040   dec->priv->ctx.do_byte_time = enabled;
2041 }
2042
2043 /**
2044  * gst_base_audio_decoder_get_byte_time:
2045  * @dec: a #GstBaseAudioDecoder
2046  *
2047  * Returns: currently configured byte to time conversion setting
2048  *
2049  * Since: 0.10.36
2050  */
2051 gint
2052 gst_base_audio_decoder_get_byte_time (GstBaseAudioDecoder * dec)
2053 {
2054   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0);
2055
2056   return dec->priv->ctx.do_byte_time;
2057 }
2058
2059 /**
2060  * gst_base_audio_decoder_get_delay:
2061  * @dec: a #GstBaseAudioDecoder
2062  *
2063  * Returns: currently configured decoder delay
2064  *
2065  * Since: 0.10.36
2066  */
2067 gint
2068 gst_base_audio_decoder_get_delay (GstBaseAudioDecoder * dec)
2069 {
2070   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0);
2071
2072   return dec->priv->ctx.delay;
2073 }
2074
2075 /**
2076  * gst_base_audio_decoder_set_max_errors:
2077  * @dec: a #GstBaseAudioDecoder
2078  * @num: max tolerated errors
2079  *
2080  * Sets numbers of tolerated decoder errors, where a tolerated one is then only
2081  * warned about, but more than tolerated will lead to fatal error.
2082  *
2083  * Since: 0.10.36
2084  */
2085 void
2086 gst_base_audio_decoder_set_max_errors (GstBaseAudioDecoder * enc, gint num)
2087 {
2088   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (enc));
2089
2090   enc->priv->ctx.max_errors = num;
2091 }
2092
2093 /**
2094  * gst_base_audio_decoder_get_max_errors:
2095  * @dec: a #GstBaseAudioDecoder
2096  *
2097  * Returns: currently configured decoder tolerated error count.
2098  *
2099  * Since: 0.10.36
2100  */
2101 gint
2102 gst_base_audio_decoder_get_max_errors (GstBaseAudioDecoder * dec)
2103 {
2104   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0);
2105
2106   return dec->priv->ctx.max_errors;
2107 }
2108
2109 /**
2110  * gst_base_audio_decoder_set_latency:
2111  * @dec: a #GstBaseAudioDecoder
2112  * @min: minimum latency
2113  * @max: maximum latency
2114  *
2115  * Sets decoder latency.
2116  *
2117  * Since: 0.10.36
2118  */
2119 void
2120 gst_base_audio_decoder_set_latency (GstBaseAudioDecoder * dec,
2121     GstClockTime min, GstClockTime max)
2122 {
2123   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2124
2125   GST_OBJECT_LOCK (dec);
2126   dec->priv->ctx.min_latency = min;
2127   dec->priv->ctx.max_latency = max;
2128   GST_OBJECT_UNLOCK (dec);
2129 }
2130
2131 /**
2132  * gst_base_audio_decoder_get_latency:
2133  * @dec: a #GstBaseAudioDecoder
2134  * @min: a pointer to storage to hold minimum latency
2135  * @max: a pointer to storage to hold maximum latency
2136  *
2137  * Returns currently configured latency.
2138  *
2139  * Since: 0.10.36
2140  */
2141 void
2142 gst_base_audio_decoder_get_latency (GstBaseAudioDecoder * dec,
2143     GstClockTime * min, GstClockTime * max)
2144 {
2145   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2146
2147   GST_OBJECT_LOCK (dec);
2148   if (min)
2149     *min = dec->priv->ctx.min_latency;
2150   if (max)
2151     *max = dec->priv->ctx.max_latency;
2152   GST_OBJECT_UNLOCK (dec);
2153 }
2154
2155 /**
2156  * gst_base_audio_decoder_get_parse_state:
2157  * @dec: a #GstBaseAudioDecoder
2158  * @min: a pointer to storage to hold current sync state
2159  * @max: a pointer to storage to hold current eos state
2160  *
2161  * Return current parsing (sync and eos) state.
2162  *
2163  * Since: 0.10.36
2164  */
2165 void
2166 gst_base_audio_decoder_get_parse_state (GstBaseAudioDecoder * dec,
2167     gboolean * sync, gboolean * eos)
2168 {
2169   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2170
2171   if (sync)
2172     *sync = dec->priv->ctx.sync;
2173   if (eos)
2174     *eos = dec->priv->ctx.eos;
2175 }
2176
2177 /**
2178  * gst_base_audio_decoder_set_plc:
2179  * @dec: a #GstBaseAudioDecoder
2180  * @enabled: new state
2181  *
2182  * Enable or disable decoder packet loss concealment, provided subclass
2183  * and codec are capable and allow handling plc.
2184  *
2185  * MT safe.
2186  *
2187  * Since: 0.10.36
2188  */
2189 void
2190 gst_base_audio_decoder_set_plc (GstBaseAudioDecoder * dec, gboolean enabled)
2191 {
2192   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2193
2194   GST_LOG_OBJECT (dec, "enabled: %d", enabled);
2195
2196   GST_OBJECT_LOCK (dec);
2197   dec->priv->plc = enabled;
2198   GST_OBJECT_UNLOCK (dec);
2199 }
2200
2201 /**
2202  * gst_base_audio_decoder_get_plc:
2203  * @dec: a #GstBaseAudioDecoder
2204  *
2205  * Queries decoder packet loss concealment handling.
2206  *
2207  * Returns: TRUE if packet loss concealment is enabled.
2208  *
2209  * MT safe.
2210  *
2211  * Since: 0.10.36
2212  */
2213 gboolean
2214 gst_base_audio_decoder_get_plc (GstBaseAudioDecoder * dec)
2215 {
2216   gboolean result;
2217
2218   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), FALSE);
2219
2220   GST_OBJECT_LOCK (dec);
2221   result = dec->priv->plc;
2222   GST_OBJECT_UNLOCK (dec);
2223
2224   return result;
2225 }
2226
2227 /**
2228  * gst_base_audio_decoder_set_min_latency:
2229  * @dec: a #GstBaseAudioDecoder
2230  * @num: new minimum latency
2231  *
2232  * Sets decoder minimum aggregation latency.
2233  *
2234  * MT safe.
2235  *
2236  * Since: 0.10.36
2237  */
2238 void
2239 gst_base_audio_decoder_set_min_latency (GstBaseAudioDecoder * dec, gint64 num)
2240 {
2241   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2242
2243   GST_OBJECT_LOCK (dec);
2244   dec->priv->latency = num;
2245   GST_OBJECT_UNLOCK (dec);
2246 }
2247
2248 /**
2249  * gst_base_audio_decoder_get_min_latency:
2250  * @enc: a #GstBaseAudioDecoder
2251  *
2252  * Queries decoder's latency aggregation.
2253  *
2254  * Returns: aggregation latency.
2255  *
2256  * MT safe.
2257  *
2258  * Since: 0.10.36
2259  */
2260 gint64
2261 gst_base_audio_decoder_get_min_latency (GstBaseAudioDecoder * dec)
2262 {
2263   gint64 result;
2264
2265   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), FALSE);
2266
2267   GST_OBJECT_LOCK (dec);
2268   result = dec->priv->latency;
2269   GST_OBJECT_UNLOCK (dec);
2270
2271   return result;
2272 }
2273
2274 /**
2275  * gst_base_audio_decoder_set_tolerance:
2276  * @dec: a #GstBaseAudioDecoder
2277  * @tolerance: new tolerance
2278  *
2279  * Configures decoder audio jitter tolerance threshold.
2280  *
2281  * MT safe.
2282  *
2283  * Since: 0.10.36
2284  */
2285 void
2286 gst_base_audio_decoder_set_tolerance (GstBaseAudioDecoder * dec,
2287     gint64 tolerance)
2288 {
2289   g_return_if_fail (GST_IS_BASE_AUDIO_DECODER (dec));
2290
2291   GST_OBJECT_LOCK (dec);
2292   dec->priv->tolerance = tolerance;
2293   GST_OBJECT_UNLOCK (dec);
2294 }
2295
2296 /**
2297  * gst_base_audio_decoder_get_tolerance:
2298  * @dec: a #GstBaseAudioDecoder
2299  *
2300  * Queries current audio jitter tolerance threshold.
2301  *
2302  * Returns: decoder audio jitter tolerance threshold.
2303  *
2304  * MT safe.
2305  *
2306  * Since: 0.10.36
2307  */
2308 gint64
2309 gst_base_audio_decoder_get_tolerance (GstBaseAudioDecoder * dec)
2310 {
2311   gint64 result;
2312
2313   g_return_val_if_fail (GST_IS_BASE_AUDIO_DECODER (dec), 0);
2314
2315   GST_OBJECT_LOCK (dec);
2316   result = dec->priv->tolerance;
2317   GST_OBJECT_UNLOCK (dec);
2318
2319   return result;
2320 }