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