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