95139eeac6b6fd735e82618237154be0856817b3
[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., 51 Franklin St, Fifth Floor,
21  * Boston, MA 02110-1301, USA.
22  */
23
24 /**
25  * SECTION:gstaudiodecoder
26  * @title: GstAudioDecoder
27  * @short_description: Base class for audio decoders
28  * @see_also: #GstBaseTransform
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  *
35  * ## Configuration
36  *
37  *   * Initially, GstAudioDecoder calls @start when the decoder element
38  *     is activated, which allows subclass to perform any global setup.
39  *     Base class (context) parameters can already be set according to subclass
40  *     capabilities (or possibly upon receive more information in subsequent
41  *     @set_format).
42  *   * GstAudioDecoder calls @set_format to inform subclass of the format
43  *     of input audio data that it is about to receive.
44  *     While unlikely, it might be called more than once, if changing input
45  *     parameters require reconfiguration.
46  *   * GstAudioDecoder calls @stop at end of all processing.
47  *
48  * As of configuration stage, and throughout processing, GstAudioDecoder
49  * provides various (context) parameters, e.g. describing the format of
50  * output audio data (valid when output caps have been set) or current parsing state.
51  * Conversely, subclass can and should configure context to inform
52  * base class of its expectation w.r.t. buffer handling.
53  *
54  * ## Data processing
55  *     * Base class gathers input data, and optionally allows subclass
56  *       to parse this into subsequently manageable (as defined by subclass)
57  *       chunks.  Such chunks are subsequently referred to as 'frames',
58  *       though they may or may not correspond to 1 (or more) audio format frame.
59  *     * Input frame is provided to subclass' @handle_frame.
60  *     * If codec processing results in decoded data, subclass should call
61  *       @gst_audio_decoder_finish_frame to have decoded data pushed
62  *       downstream.
63  *     * Just prior to actually pushing a buffer downstream,
64  *       it is passed to @pre_push.  Subclass should either use this callback
65  *       to arrange for additional downstream pushing or otherwise ensure such
66  *       custom pushing occurs after at least a method call has finished since
67  *       setting src pad caps.
68  *     * During the parsing process GstAudioDecoderClass will handle both
69  *       srcpad and sinkpad events. Sink events will be passed to subclass
70  *       if @event callback has been provided.
71  *
72  * ## Shutdown phase
73  *
74  *   * GstAudioDecoder class calls @stop to inform the subclass that data
75  *     parsing will be stopped.
76  *
77  * Subclass is responsible for providing pad template caps for
78  * source and sink pads. The pads need to be named "sink" and "src". It also
79  * needs to set the fixed caps on srcpad, when the format is ensured.  This
80  * is typically when base class calls subclass' @set_format function, though
81  * it might be delayed until calling @gst_audio_decoder_finish_frame.
82  *
83  * In summary, above process should have subclass concentrating on
84  * codec data processing while leaving other matters to base class,
85  * such as most notably timestamp handling.  While it may exert more control
86  * in this area (see e.g. @pre_push), it is very much not recommended.
87  *
88  * In particular, base class will try to arrange for perfect output timestamps
89  * as much as possible while tracking upstream timestamps.
90  * To this end, if deviation between the next ideal expected perfect timestamp
91  * and upstream exceeds #GstAudioDecoder:tolerance, then resync to upstream
92  * occurs (which would happen always if the tolerance mechanism is disabled).
93  *
94  * In non-live pipelines, baseclass can also (configurably) arrange for
95  * output buffer aggregation which may help to redue large(r) numbers of
96  * small(er) buffers being pushed and processed downstream. Note that this
97  * feature is only available if the buffer layout is interleaved. For planar
98  * buffers, the decoder implementation is fully responsible for the output
99  * buffer size.
100  *
101  * On the other hand, it should be noted that baseclass only provides limited
102  * seeking support (upon explicit subclass request), as full-fledged support
103  * should rather be left to upstream demuxer, parser or alike.  This simple
104  * approach caters for seeking and duration reporting using estimated input
105  * bitrates.
106  *
107  * Things that subclass need to take care of:
108  *
109  *   * Provide pad templates
110  *   * Set source pad caps when appropriate
111  *   * Set user-configurable properties to sane defaults for format and
112  *      implementing codec at hand, and convey some subclass capabilities and
113  *      expectations in context.
114  *
115  *   * Accept data in @handle_frame and provide encoded results to
116  *      @gst_audio_decoder_finish_frame.  If it is prepared to perform
117  *      PLC, it should also accept NULL data in @handle_frame and provide for
118  *      data for indicated duration.
119  *
120  */
121
122 #ifdef HAVE_CONFIG_H
123 #include "config.h"
124 #endif
125
126 #include "gstaudiodecoder.h"
127 #include "gstaudioutilsprivate.h"
128 #include <gst/pbutils/descriptions.h>
129
130 #include <string.h>
131
132 GST_DEBUG_CATEGORY (audiodecoder_debug);
133 #define GST_CAT_DEFAULT audiodecoder_debug
134
135 enum
136 {
137   LAST_SIGNAL
138 };
139
140 enum
141 {
142   PROP_0,
143   PROP_LATENCY,
144   PROP_TOLERANCE,
145   PROP_PLC
146 };
147
148 #define DEFAULT_LATENCY    0
149 #define DEFAULT_TOLERANCE  0
150 #define DEFAULT_PLC        FALSE
151 #define DEFAULT_DRAINABLE  TRUE
152 #define DEFAULT_NEEDS_FORMAT  FALSE
153
154 typedef struct _GstAudioDecoderContext
155 {
156   /* last negotiated input caps */
157   GstCaps *input_caps;
158
159   /* (output) audio format */
160   GstAudioInfo info;
161   GstCaps *caps;
162   gboolean output_format_changed;
163
164   /* parsing state */
165   gboolean eos;
166   gboolean sync;
167
168   gboolean had_output_data;
169   gboolean had_input_data;
170
171   /* misc */
172   gint delay;
173
174   /* output */
175   gboolean do_plc;
176   gboolean do_estimate_rate;
177   gint max_errors;
178   GstCaps *allocation_caps;
179   /* MT-protected (with LOCK) */
180   GstClockTime min_latency;
181   GstClockTime max_latency;
182
183   GstAllocator *allocator;
184   GstAllocationParams params;
185 } GstAudioDecoderContext;
186
187 struct _GstAudioDecoderPrivate
188 {
189   /* activation status */
190   gboolean active;
191
192   /* input base/first ts as basis for output ts */
193   GstClockTime base_ts;
194   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
195   guint64 samples;
196
197   /* collected input data */
198   GstAdapter *adapter;
199   /* tracking input ts for changes */
200   GstClockTime prev_ts;
201   guint64 prev_distance;
202   /* frames obtained from input */
203   GQueue frames;
204   /* collected output data */
205   GstAdapter *adapter_out;
206   /* ts and duration for output data collected above */
207   GstClockTime out_ts, out_dur;
208   /* mark outgoing discont */
209   gboolean discont;
210
211   /* subclass gave all it could already */
212   gboolean drained;
213   /* subclass currently being forcibly drained */
214   gboolean force;
215   /* input_segment are output_segment identical */
216   gboolean in_out_segment_sync;
217   /* expecting the buffer with DISCONT flag */
218   gboolean expecting_discont_buf;
219
220
221   /* input bps estimatation */
222   /* global in bytes seen */
223   guint64 bytes_in;
224   /* global samples sent out */
225   guint64 samples_out;
226   /* bytes flushed during parsing */
227   guint sync_flush;
228   /* error count */
229   gint error_count;
230
231   /* upstream stream tags (global tags are passed through as-is) */
232   GstTagList *upstream_tags;
233
234   /* subclass tags */
235   GstTagList *taglist;          /* FIXME: rename to decoder_tags */
236   GstTagMergeMode decoder_tags_merge_mode;
237
238   gboolean taglist_changed;     /* FIXME: rename to tags_changed */
239
240   /* whether circumstances allow output aggregation */
241   gint agg;
242
243   /* reverse playback queues */
244   /* collect input */
245   GList *gather;
246   /* to-be-decoded */
247   GList *decode;
248   /* reversed output */
249   GList *queued;
250
251   /* context storage */
252   GstAudioDecoderContext ctx;
253
254   /* properties */
255   GstClockTime latency;
256   GstClockTime tolerance;
257   gboolean plc;
258   gboolean drainable;
259   gboolean needs_format;
260
261   /* pending serialized sink events, will be sent from finish_frame() */
262   GList *pending_events;
263
264   /* flags */
265   gboolean use_default_pad_acceptcaps;
266 };
267
268 static void gst_audio_decoder_finalize (GObject * object);
269 static void gst_audio_decoder_set_property (GObject * object,
270     guint prop_id, const GValue * value, GParamSpec * pspec);
271 static void gst_audio_decoder_get_property (GObject * object,
272     guint prop_id, GValue * value, GParamSpec * pspec);
273
274 static void gst_audio_decoder_clear_queues (GstAudioDecoder * dec);
275 static GstFlowReturn gst_audio_decoder_chain_reverse (GstAudioDecoder *
276     dec, GstBuffer * buf);
277
278 static GstStateChangeReturn gst_audio_decoder_change_state (GstElement *
279     element, GstStateChange transition);
280 static gboolean gst_audio_decoder_sink_eventfunc (GstAudioDecoder * dec,
281     GstEvent * event);
282 static gboolean gst_audio_decoder_src_eventfunc (GstAudioDecoder * dec,
283     GstEvent * event);
284 static gboolean gst_audio_decoder_sink_event (GstPad * pad, GstObject * parent,
285     GstEvent * event);
286 static gboolean gst_audio_decoder_src_event (GstPad * pad, GstObject * parent,
287     GstEvent * event);
288 static gboolean gst_audio_decoder_sink_setcaps (GstAudioDecoder * dec,
289     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 gboolean gst_audio_decoder_decide_allocation_default (GstAudioDecoder *
299     dec, GstQuery * query);
300 static gboolean gst_audio_decoder_propose_allocation_default (GstAudioDecoder *
301     dec, GstQuery * query);
302 static gboolean gst_audio_decoder_negotiate_default (GstAudioDecoder * dec);
303 static gboolean gst_audio_decoder_negotiate_unlocked (GstAudioDecoder * dec);
304 static gboolean gst_audio_decoder_handle_gap (GstAudioDecoder * dec,
305     GstEvent * event);
306 static gboolean gst_audio_decoder_sink_query_default (GstAudioDecoder * dec,
307     GstQuery * query);
308 static gboolean gst_audio_decoder_src_query_default (GstAudioDecoder * dec,
309     GstQuery * query);
310
311 static gboolean gst_audio_decoder_transform_meta_default (GstAudioDecoder *
312     decoder, GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf);
313
314 static GstElementClass *parent_class = NULL;
315 static gint private_offset = 0;
316
317 static void gst_audio_decoder_class_init (GstAudioDecoderClass * klass);
318 static void gst_audio_decoder_init (GstAudioDecoder * dec,
319     GstAudioDecoderClass * klass);
320
321 GType
322 gst_audio_decoder_get_type (void)
323 {
324   static volatile gsize audio_decoder_type = 0;
325
326   if (g_once_init_enter (&audio_decoder_type)) {
327     GType _type;
328     static const GTypeInfo audio_decoder_info = {
329       sizeof (GstAudioDecoderClass),
330       NULL,
331       NULL,
332       (GClassInitFunc) gst_audio_decoder_class_init,
333       NULL,
334       NULL,
335       sizeof (GstAudioDecoder),
336       0,
337       (GInstanceInitFunc) gst_audio_decoder_init,
338     };
339
340     _type = g_type_register_static (GST_TYPE_ELEMENT,
341         "GstAudioDecoder", &audio_decoder_info, G_TYPE_FLAG_ABSTRACT);
342
343     private_offset =
344         g_type_add_instance_private (_type, sizeof (GstAudioDecoderPrivate));
345
346     g_once_init_leave (&audio_decoder_type, _type);
347   }
348   return audio_decoder_type;
349 }
350
351 static inline GstAudioDecoderPrivate *
352 gst_audio_decoder_get_instance_private (GstAudioDecoder * self)
353 {
354   return (G_STRUCT_MEMBER_P (self, private_offset));
355 }
356
357 static void
358 gst_audio_decoder_class_init (GstAudioDecoderClass * klass)
359 {
360   GObjectClass *gobject_class;
361   GstElementClass *element_class;
362   GstAudioDecoderClass *audiodecoder_class;
363
364   gobject_class = G_OBJECT_CLASS (klass);
365   element_class = GST_ELEMENT_CLASS (klass);
366   audiodecoder_class = GST_AUDIO_DECODER_CLASS (klass);
367
368   parent_class = g_type_class_peek_parent (klass);
369
370   if (private_offset != 0)
371     g_type_class_adjust_private_offset (klass, &private_offset);
372
373   GST_DEBUG_CATEGORY_INIT (audiodecoder_debug, "audiodecoder", 0,
374       "audio decoder base class");
375
376   gobject_class->set_property = gst_audio_decoder_set_property;
377   gobject_class->get_property = gst_audio_decoder_get_property;
378   gobject_class->finalize = gst_audio_decoder_finalize;
379
380   element_class->change_state =
381       GST_DEBUG_FUNCPTR (gst_audio_decoder_change_state);
382
383   /* Properties */
384   g_object_class_install_property (gobject_class, PROP_LATENCY,
385       g_param_spec_int64 ("min-latency", "Minimum Latency",
386           "Aggregate output data to a minimum of latency time (ns)",
387           0, G_MAXINT64, DEFAULT_LATENCY,
388           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
389
390   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
391       g_param_spec_int64 ("tolerance", "Tolerance",
392           "Perfect ts while timestamp jitter/imperfection within tolerance (ns)",
393           0, G_MAXINT64, DEFAULT_TOLERANCE,
394           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
395
396   g_object_class_install_property (gobject_class, PROP_PLC,
397       g_param_spec_boolean ("plc", "Packet Loss Concealment",
398           "Perform packet loss concealment (if supported)",
399           DEFAULT_PLC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
400
401   audiodecoder_class->sink_event =
402       GST_DEBUG_FUNCPTR (gst_audio_decoder_sink_eventfunc);
403   audiodecoder_class->src_event =
404       GST_DEBUG_FUNCPTR (gst_audio_decoder_src_eventfunc);
405   audiodecoder_class->propose_allocation =
406       GST_DEBUG_FUNCPTR (gst_audio_decoder_propose_allocation_default);
407   audiodecoder_class->decide_allocation =
408       GST_DEBUG_FUNCPTR (gst_audio_decoder_decide_allocation_default);
409   audiodecoder_class->negotiate =
410       GST_DEBUG_FUNCPTR (gst_audio_decoder_negotiate_default);
411   audiodecoder_class->sink_query =
412       GST_DEBUG_FUNCPTR (gst_audio_decoder_sink_query_default);
413   audiodecoder_class->src_query =
414       GST_DEBUG_FUNCPTR (gst_audio_decoder_src_query_default);
415   audiodecoder_class->transform_meta =
416       GST_DEBUG_FUNCPTR (gst_audio_decoder_transform_meta_default);
417 }
418
419 static void
420 gst_audio_decoder_init (GstAudioDecoder * dec, GstAudioDecoderClass * klass)
421 {
422   GstPadTemplate *pad_template;
423
424   GST_DEBUG_OBJECT (dec, "gst_audio_decoder_init");
425
426   dec->priv = gst_audio_decoder_get_instance_private (dec);
427
428   /* Setup sink pad */
429   pad_template =
430       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "sink");
431   g_return_if_fail (pad_template != NULL);
432
433   dec->sinkpad = gst_pad_new_from_template (pad_template, "sink");
434   gst_pad_set_event_function (dec->sinkpad,
435       GST_DEBUG_FUNCPTR (gst_audio_decoder_sink_event));
436   gst_pad_set_chain_function (dec->sinkpad,
437       GST_DEBUG_FUNCPTR (gst_audio_decoder_chain));
438   gst_pad_set_query_function (dec->sinkpad,
439       GST_DEBUG_FUNCPTR (gst_audio_decoder_sink_query));
440   gst_element_add_pad (GST_ELEMENT (dec), dec->sinkpad);
441   GST_DEBUG_OBJECT (dec, "sinkpad created");
442
443   /* Setup source pad */
444   pad_template =
445       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (klass), "src");
446   g_return_if_fail (pad_template != NULL);
447
448   dec->srcpad = gst_pad_new_from_template (pad_template, "src");
449   gst_pad_set_event_function (dec->srcpad,
450       GST_DEBUG_FUNCPTR (gst_audio_decoder_src_event));
451   gst_pad_set_query_function (dec->srcpad,
452       GST_DEBUG_FUNCPTR (gst_audio_decoder_src_query));
453   gst_element_add_pad (GST_ELEMENT (dec), dec->srcpad);
454   GST_DEBUG_OBJECT (dec, "srcpad created");
455
456   dec->priv->adapter = gst_adapter_new ();
457   dec->priv->adapter_out = gst_adapter_new ();
458   g_queue_init (&dec->priv->frames);
459
460   g_rec_mutex_init (&dec->stream_lock);
461
462   /* property default */
463   dec->priv->latency = DEFAULT_LATENCY;
464   dec->priv->tolerance = DEFAULT_TOLERANCE;
465   dec->priv->plc = DEFAULT_PLC;
466   dec->priv->drainable = DEFAULT_DRAINABLE;
467   dec->priv->needs_format = DEFAULT_NEEDS_FORMAT;
468
469   /* init state */
470   dec->priv->ctx.min_latency = 0;
471   dec->priv->ctx.max_latency = 0;
472   gst_audio_decoder_reset (dec, TRUE);
473   GST_DEBUG_OBJECT (dec, "init ok");
474 }
475
476 static void
477 gst_audio_decoder_reset (GstAudioDecoder * dec, gboolean full)
478 {
479   GST_DEBUG_OBJECT (dec, "gst_audio_decoder_reset");
480
481   GST_AUDIO_DECODER_STREAM_LOCK (dec);
482
483   if (full) {
484     dec->priv->active = FALSE;
485     GST_OBJECT_LOCK (dec);
486     dec->priv->bytes_in = 0;
487     dec->priv->samples_out = 0;
488     GST_OBJECT_UNLOCK (dec);
489     dec->priv->agg = -1;
490     dec->priv->error_count = 0;
491     gst_audio_decoder_clear_queues (dec);
492
493     if (dec->priv->taglist) {
494       gst_tag_list_unref (dec->priv->taglist);
495       dec->priv->taglist = NULL;
496     }
497     dec->priv->decoder_tags_merge_mode = GST_TAG_MERGE_KEEP_ALL;
498     if (dec->priv->upstream_tags) {
499       gst_tag_list_unref (dec->priv->upstream_tags);
500       dec->priv->upstream_tags = NULL;
501     }
502     dec->priv->taglist_changed = FALSE;
503
504     gst_segment_init (&dec->input_segment, GST_FORMAT_TIME);
505     gst_segment_init (&dec->output_segment, GST_FORMAT_TIME);
506     dec->priv->in_out_segment_sync = TRUE;
507
508     g_list_foreach (dec->priv->pending_events, (GFunc) gst_event_unref, NULL);
509     g_list_free (dec->priv->pending_events);
510     dec->priv->pending_events = NULL;
511
512     if (dec->priv->ctx.allocator)
513       gst_object_unref (dec->priv->ctx.allocator);
514
515     GST_OBJECT_LOCK (dec);
516     gst_caps_replace (&dec->priv->ctx.input_caps, NULL);
517     gst_caps_replace (&dec->priv->ctx.caps, NULL);
518     gst_caps_replace (&dec->priv->ctx.allocation_caps, NULL);
519
520     memset (&dec->priv->ctx, 0, sizeof (dec->priv->ctx));
521
522     gst_audio_info_init (&dec->priv->ctx.info);
523     GST_OBJECT_UNLOCK (dec);
524     dec->priv->ctx.max_errors = GST_AUDIO_DECODER_MAX_ERRORS;
525     dec->priv->ctx.had_output_data = FALSE;
526     dec->priv->ctx.had_input_data = FALSE;
527   }
528
529   g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL);
530   g_queue_clear (&dec->priv->frames);
531   gst_adapter_clear (dec->priv->adapter);
532   gst_adapter_clear (dec->priv->adapter_out);
533   dec->priv->out_ts = GST_CLOCK_TIME_NONE;
534   dec->priv->out_dur = 0;
535   dec->priv->prev_ts = GST_CLOCK_TIME_NONE;
536   dec->priv->prev_distance = 0;
537   dec->priv->drained = TRUE;
538   dec->priv->base_ts = GST_CLOCK_TIME_NONE;
539   dec->priv->samples = 0;
540   dec->priv->discont = TRUE;
541   dec->priv->sync_flush = FALSE;
542
543   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
544 }
545
546 static void
547 gst_audio_decoder_finalize (GObject * object)
548 {
549   GstAudioDecoder *dec;
550
551   g_return_if_fail (GST_IS_AUDIO_DECODER (object));
552   dec = GST_AUDIO_DECODER (object);
553
554   if (dec->priv->adapter) {
555     g_object_unref (dec->priv->adapter);
556   }
557   if (dec->priv->adapter_out) {
558     g_object_unref (dec->priv->adapter_out);
559   }
560
561   g_rec_mutex_clear (&dec->stream_lock);
562
563   G_OBJECT_CLASS (parent_class)->finalize (object);
564 }
565
566 static GstEvent *
567 gst_audio_decoder_create_merged_tags_event (GstAudioDecoder * dec)
568 {
569   GstTagList *merged_tags;
570
571   GST_LOG_OBJECT (dec, "upstream : %" GST_PTR_FORMAT, dec->priv->upstream_tags);
572   GST_LOG_OBJECT (dec, "decoder  : %" GST_PTR_FORMAT, dec->priv->taglist);
573   GST_LOG_OBJECT (dec, "mode     : %d", dec->priv->decoder_tags_merge_mode);
574
575   merged_tags =
576       gst_tag_list_merge (dec->priv->upstream_tags,
577       dec->priv->taglist, dec->priv->decoder_tags_merge_mode);
578
579   GST_DEBUG_OBJECT (dec, "merged   : %" GST_PTR_FORMAT, merged_tags);
580
581   if (merged_tags == NULL)
582     return NULL;
583
584   if (gst_tag_list_is_empty (merged_tags)) {
585     gst_tag_list_unref (merged_tags);
586     return NULL;
587   }
588
589   return gst_event_new_tag (merged_tags);
590 }
591
592 static gboolean
593 gst_audio_decoder_push_event (GstAudioDecoder * dec, GstEvent * event)
594 {
595   switch (GST_EVENT_TYPE (event)) {
596     case GST_EVENT_SEGMENT:{
597       GstSegment seg;
598
599       GST_AUDIO_DECODER_STREAM_LOCK (dec);
600       gst_event_copy_segment (event, &seg);
601
602       GST_DEBUG_OBJECT (dec, "starting segment %" GST_SEGMENT_FORMAT, &seg);
603
604       dec->output_segment = seg;
605       dec->priv->in_out_segment_sync =
606           gst_segment_is_equal (&dec->input_segment, &seg);
607       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
608       break;
609     }
610     default:
611       break;
612   }
613
614   return gst_pad_push_event (dec->srcpad, event);
615 }
616
617 static gboolean
618 gst_audio_decoder_negotiate_default (GstAudioDecoder * dec)
619 {
620   GstAudioDecoderClass *klass;
621   gboolean res = TRUE;
622   GstCaps *caps;
623   GstCaps *prevcaps;
624   GstQuery *query = NULL;
625   GstAllocator *allocator;
626   GstAllocationParams params;
627
628   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
629   g_return_val_if_fail (GST_AUDIO_INFO_IS_VALID (&dec->priv->ctx.info), FALSE);
630   g_return_val_if_fail (GST_IS_CAPS (dec->priv->ctx.caps), FALSE);
631
632   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
633
634   caps = dec->priv->ctx.caps;
635   if (dec->priv->ctx.allocation_caps == NULL)
636     dec->priv->ctx.allocation_caps = gst_caps_ref (caps);
637
638   GST_DEBUG_OBJECT (dec, "setting src caps %" GST_PTR_FORMAT, caps);
639
640   if (dec->priv->pending_events) {
641     GList **pending_events, *l;
642
643     pending_events = &dec->priv->pending_events;
644
645     GST_DEBUG_OBJECT (dec, "Pushing pending events");
646     for (l = *pending_events; l;) {
647       GstEvent *event = GST_EVENT (l->data);
648       GList *tmp;
649
650       if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
651         gst_audio_decoder_push_event (dec, l->data);
652         tmp = l;
653         l = l->next;
654         *pending_events = g_list_delete_link (*pending_events, tmp);
655       } else {
656         l = l->next;
657       }
658     }
659   }
660
661   prevcaps = gst_pad_get_current_caps (dec->srcpad);
662   if (!prevcaps || !gst_caps_is_equal (prevcaps, caps))
663     res = gst_pad_set_caps (dec->srcpad, caps);
664   if (prevcaps)
665     gst_caps_unref (prevcaps);
666
667   if (!res)
668     goto done;
669   dec->priv->ctx.output_format_changed = FALSE;
670
671   query = gst_query_new_allocation (dec->priv->ctx.allocation_caps, TRUE);
672   if (!gst_pad_peer_query (dec->srcpad, query)) {
673     GST_DEBUG_OBJECT (dec, "didn't get downstream ALLOCATION hints");
674   }
675
676   g_assert (klass->decide_allocation != NULL);
677   res = klass->decide_allocation (dec, query);
678
679   GST_DEBUG_OBJECT (dec, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, res,
680       query);
681
682   if (!res)
683     goto no_decide_allocation;
684
685   /* we got configuration from our peer or the decide_allocation method,
686    * parse them */
687   if (gst_query_get_n_allocation_params (query) > 0) {
688     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
689   } else {
690     allocator = NULL;
691     gst_allocation_params_init (&params);
692   }
693
694   if (dec->priv->ctx.allocator)
695     gst_object_unref (dec->priv->ctx.allocator);
696   dec->priv->ctx.allocator = allocator;
697   dec->priv->ctx.params = params;
698
699 done:
700
701   if (query)
702     gst_query_unref (query);
703
704   return res;
705
706   /* ERRORS */
707 no_decide_allocation:
708   {
709     GST_WARNING_OBJECT (dec, "Subclass failed to decide allocation");
710     goto done;
711   }
712 }
713
714 static gboolean
715 gst_audio_decoder_negotiate_unlocked (GstAudioDecoder * dec)
716 {
717   GstAudioDecoderClass *klass = GST_AUDIO_DECODER_GET_CLASS (dec);
718   gboolean ret = TRUE;
719
720   if (G_LIKELY (klass->negotiate))
721     ret = klass->negotiate (dec);
722
723   return ret;
724 }
725
726 /**
727  * gst_audio_decoder_negotiate:
728  * @dec: a #GstAudioDecoder
729  *
730  * Negotiate with downstream elements to currently configured #GstAudioInfo.
731  * Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if
732  * negotiate fails.
733  *
734  * Returns: %TRUE if the negotiation succeeded, else %FALSE.
735  */
736 gboolean
737 gst_audio_decoder_negotiate (GstAudioDecoder * dec)
738 {
739   GstAudioDecoderClass *klass;
740   gboolean res = TRUE;
741
742   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
743
744   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
745
746   GST_AUDIO_DECODER_STREAM_LOCK (dec);
747   gst_pad_check_reconfigure (dec->srcpad);
748   if (klass->negotiate) {
749     res = klass->negotiate (dec);
750     if (!res)
751       gst_pad_mark_reconfigure (dec->srcpad);
752   }
753   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
754
755   return res;
756 }
757
758 /**
759  * gst_audio_decoder_set_output_format:
760  * @dec: a #GstAudioDecoder
761  * @info: #GstAudioInfo
762  *
763  * Configure output info on the srcpad of @dec.
764  *
765  * Returns: %TRUE on success.
766  **/
767 gboolean
768 gst_audio_decoder_set_output_format (GstAudioDecoder * dec,
769     const GstAudioInfo * info)
770 {
771   gboolean res = TRUE;
772   GstCaps *caps = NULL;
773
774   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
775   g_return_val_if_fail (GST_AUDIO_INFO_IS_VALID (info), FALSE);
776
777   /* If the audio info can't be converted to caps,
778    * it was invalid */
779   caps = gst_audio_info_to_caps (info);
780   if (!caps) {
781     GST_WARNING_OBJECT (dec, "invalid output format");
782     return FALSE;
783   }
784
785   res = gst_audio_decoder_set_output_caps (dec, caps);
786   gst_caps_unref (caps);
787
788   return res;
789 }
790
791 /**
792  * gst_audio_decoder_set_output_caps:
793  * @dec: a #GstAudioDecoder
794  * @caps: (transfer none): (fixed) #GstCaps
795  *
796  * Configure output caps on the srcpad of @dec. Similar to
797  * gst_audio_decoder_set_output_format(), but allows subclasses to specify
798  * output caps that can't be expressed via #GstAudioInfo e.g. caps that have
799  * caps features.
800  *
801  * Returns: %TRUE on success.
802  *
803  * Since: 1.16
804  **/
805 gboolean
806 gst_audio_decoder_set_output_caps (GstAudioDecoder * dec, GstCaps * caps)
807 {
808   gboolean res = TRUE;
809   guint old_rate;
810   GstCaps *templ_caps;
811   GstAudioInfo info;
812
813   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
814
815   GST_DEBUG_OBJECT (dec, "Setting srcpad caps %" GST_PTR_FORMAT, caps);
816
817   GST_AUDIO_DECODER_STREAM_LOCK (dec);
818
819   if (!gst_caps_is_fixed (caps))
820     goto refuse_caps;
821
822   /* check if caps can be parsed */
823   if (!gst_audio_info_from_caps (&info, caps))
824     goto refuse_caps;
825
826   /* Only allow caps that are a subset of the template caps */
827   templ_caps = gst_pad_get_pad_template_caps (dec->srcpad);
828   if (!gst_caps_is_subset (caps, templ_caps)) {
829     GST_WARNING_OBJECT (dec, "Requested output format %" GST_PTR_FORMAT
830         " do not match template %" GST_PTR_FORMAT, caps, templ_caps);
831     gst_caps_unref (templ_caps);
832     goto refuse_caps;
833   }
834   gst_caps_unref (templ_caps);
835
836   /* adjust ts tracking to new sample rate */
837   old_rate = GST_AUDIO_INFO_RATE (&dec->priv->ctx.info);
838   if (GST_CLOCK_TIME_IS_VALID (dec->priv->base_ts) && old_rate) {
839     dec->priv->base_ts +=
840         GST_FRAMES_TO_CLOCK_TIME (dec->priv->samples, old_rate);
841     dec->priv->samples = 0;
842   }
843
844   /* copy the GstAudioInfo */
845   GST_OBJECT_LOCK (dec);
846   dec->priv->ctx.info = info;
847   GST_OBJECT_UNLOCK (dec);
848
849   gst_caps_replace (&dec->priv->ctx.caps, caps);
850   dec->priv->ctx.output_format_changed = TRUE;
851
852 done:
853   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
854
855   return res;
856
857   /* ERRORS */
858 refuse_caps:
859   {
860     GST_WARNING_OBJECT (dec, "invalid output format");
861     res = FALSE;
862     goto done;
863   }
864 }
865
866 static gboolean
867 gst_audio_decoder_sink_setcaps (GstAudioDecoder * dec, GstCaps * caps)
868 {
869   GstAudioDecoderClass *klass;
870   gboolean res = TRUE;
871
872   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
873
874   GST_DEBUG_OBJECT (dec, "caps: %" GST_PTR_FORMAT, caps);
875
876   GST_AUDIO_DECODER_STREAM_LOCK (dec);
877
878   if (dec->priv->ctx.input_caps
879       && gst_caps_is_equal (dec->priv->ctx.input_caps, caps)) {
880     GST_DEBUG_OBJECT (dec, "Caps did not change, not setting again");
881     goto done;
882   }
883
884   /* NOTE pbutils only needed here */
885   /* TODO maybe (only) upstream demuxer/parser etc should handle this ? */
886 #if 0
887   if (!dec->priv->taglist)
888     dec->priv->taglist = gst_tag_list_new ();
889   dec->priv->taglist = gst_tag_list_make_writable (dec->priv->taglist);
890   gst_pb_utils_add_codec_description_to_tag_list (dec->priv->taglist,
891       GST_TAG_AUDIO_CODEC, caps);
892   dec->priv->taglist_changed = TRUE;
893 #endif
894
895   if (klass->set_format)
896     res = klass->set_format (dec, caps);
897
898   if (res)
899     gst_caps_replace (&dec->priv->ctx.input_caps, caps);
900
901 done:
902   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
903
904   return res;
905 }
906
907 static void
908 gst_audio_decoder_setup (GstAudioDecoder * dec)
909 {
910   GstQuery *query;
911   gboolean res;
912
913   /* check if in live pipeline, then latency messing is no-no */
914   query = gst_query_new_latency ();
915   res = gst_pad_peer_query (dec->sinkpad, query);
916   if (res) {
917     gst_query_parse_latency (query, &res, NULL, NULL);
918     res = !res;
919   }
920   gst_query_unref (query);
921
922   /* normalize to bool */
923   dec->priv->agg = ! !res;
924 }
925
926 static GstFlowReturn
927 gst_audio_decoder_push_forward (GstAudioDecoder * dec, GstBuffer * buf)
928 {
929   GstAudioDecoderClass *klass;
930   GstAudioDecoderPrivate *priv;
931   GstAudioDecoderContext *ctx;
932   GstFlowReturn ret = GST_FLOW_OK;
933   GstClockTime ts;
934
935   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
936   priv = dec->priv;
937   ctx = &dec->priv->ctx;
938
939   g_return_val_if_fail (ctx->info.bpf != 0, GST_FLOW_ERROR);
940
941   if (G_UNLIKELY (!buf)) {
942     g_assert_not_reached ();
943     return GST_FLOW_OK;
944   }
945
946   ctx->had_output_data = TRUE;
947   ts = GST_BUFFER_TIMESTAMP (buf);
948
949   GST_LOG_OBJECT (dec,
950       "clipping buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
951       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buf),
952       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
953       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
954
955   /* clip buffer */
956   buf = gst_audio_buffer_clip (buf, &dec->output_segment, ctx->info.rate,
957       ctx->info.bpf);
958   if (G_UNLIKELY (!buf)) {
959     GST_DEBUG_OBJECT (dec, "no data after clipping to segment");
960     /* only check and return EOS if upstream still
961      * in the same segment and interested as such */
962     if (dec->priv->in_out_segment_sync) {
963       if (dec->output_segment.rate >= 0) {
964         if (ts >= dec->output_segment.stop)
965           ret = GST_FLOW_EOS;
966       } else if (ts < dec->output_segment.start) {
967         ret = GST_FLOW_EOS;
968       }
969     }
970     goto exit;
971   }
972
973   /* decorate */
974   if (G_UNLIKELY (priv->discont)) {
975     GST_LOG_OBJECT (dec, "marking discont");
976     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
977     priv->discont = FALSE;
978   }
979
980   /* track where we are */
981   if (G_LIKELY (GST_BUFFER_TIMESTAMP_IS_VALID (buf))) {
982     /* duration should always be valid for raw audio */
983     g_assert (GST_BUFFER_DURATION_IS_VALID (buf));
984     dec->output_segment.position =
985         GST_BUFFER_TIMESTAMP (buf) + GST_BUFFER_DURATION (buf);
986   }
987
988   if (klass->pre_push) {
989     /* last chance for subclass to do some dirty stuff */
990     ret = klass->pre_push (dec, &buf);
991     if (ret != GST_FLOW_OK || !buf) {
992       GST_DEBUG_OBJECT (dec, "subclass returned %s, buf %p",
993           gst_flow_get_name (ret), buf);
994       if (buf)
995         gst_buffer_unref (buf);
996       goto exit;
997     }
998   }
999
1000   GST_LOG_OBJECT (dec,
1001       "pushing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1002       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buf),
1003       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1004       GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1005
1006   ret = gst_pad_push (dec->srcpad, buf);
1007
1008 exit:
1009   return ret;
1010 }
1011
1012 /* mini aggregator combining output buffers into fewer larger ones,
1013  * if so allowed/configured */
1014 static GstFlowReturn
1015 gst_audio_decoder_output (GstAudioDecoder * dec, GstBuffer * buf)
1016 {
1017   GstAudioDecoderPrivate *priv;
1018   GstFlowReturn ret = GST_FLOW_OK;
1019   GstBuffer *inbuf = NULL;
1020
1021   priv = dec->priv;
1022
1023   if (G_UNLIKELY (priv->agg < 0))
1024     gst_audio_decoder_setup (dec);
1025
1026   if (G_LIKELY (buf)) {
1027     GST_LOG_OBJECT (dec,
1028         "output buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1029         ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buf),
1030         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1031         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1032   }
1033
1034 again:
1035   inbuf = NULL;
1036   if (priv->agg && dec->priv->latency > 0 &&
1037       priv->ctx.info.layout == GST_AUDIO_LAYOUT_INTERLEAVED) {
1038     gint av;
1039     gboolean assemble = FALSE;
1040     const GstClockTimeDiff tol = 10 * GST_MSECOND;
1041     GstClockTimeDiff diff = -100 * GST_MSECOND;
1042
1043     av = gst_adapter_available (priv->adapter_out);
1044     if (G_UNLIKELY (!buf)) {
1045       /* forcibly send current */
1046       assemble = TRUE;
1047       GST_LOG_OBJECT (dec, "forcing fragment flush");
1048     } else if (av && (!GST_BUFFER_TIMESTAMP_IS_VALID (buf) ||
1049             !GST_CLOCK_TIME_IS_VALID (priv->out_ts) ||
1050             ((diff = GST_CLOCK_DIFF (GST_BUFFER_TIMESTAMP (buf),
1051                         priv->out_ts + priv->out_dur)) > tol) || diff < -tol)) {
1052       assemble = TRUE;
1053       GST_LOG_OBJECT (dec, "buffer %d ms apart from current fragment",
1054           (gint) (diff / GST_MSECOND));
1055     } else {
1056       /* add or start collecting */
1057       if (!av) {
1058         GST_LOG_OBJECT (dec, "starting new fragment");
1059         priv->out_ts = GST_BUFFER_TIMESTAMP (buf);
1060       } else {
1061         GST_LOG_OBJECT (dec, "adding to fragment");
1062       }
1063       gst_adapter_push (priv->adapter_out, buf);
1064       priv->out_dur += GST_BUFFER_DURATION (buf);
1065       av += gst_buffer_get_size (buf);
1066       buf = NULL;
1067     }
1068     if (priv->out_dur > dec->priv->latency)
1069       assemble = TRUE;
1070     if (av && assemble) {
1071       GST_LOG_OBJECT (dec, "assembling fragment");
1072       inbuf = buf;
1073       buf = gst_adapter_take_buffer (priv->adapter_out, av);
1074       GST_BUFFER_TIMESTAMP (buf) = priv->out_ts;
1075       GST_BUFFER_DURATION (buf) = priv->out_dur;
1076       priv->out_ts = GST_CLOCK_TIME_NONE;
1077       priv->out_dur = 0;
1078     }
1079   }
1080
1081   if (G_LIKELY (buf)) {
1082     if (dec->output_segment.rate > 0.0) {
1083       ret = gst_audio_decoder_push_forward (dec, buf);
1084       GST_LOG_OBJECT (dec, "buffer pushed: %s", gst_flow_get_name (ret));
1085     } else {
1086       ret = GST_FLOW_OK;
1087       priv->queued = g_list_prepend (priv->queued, buf);
1088       GST_LOG_OBJECT (dec, "buffer queued");
1089     }
1090
1091     if (inbuf) {
1092       buf = inbuf;
1093       goto again;
1094     }
1095   }
1096
1097   return ret;
1098 }
1099
1100 static void
1101 send_pending_events (GstAudioDecoder * dec)
1102 {
1103   GstAudioDecoderPrivate *priv = dec->priv;
1104   GList *pending_events, *l;
1105
1106   pending_events = priv->pending_events;
1107   priv->pending_events = NULL;
1108
1109   GST_DEBUG_OBJECT (dec, "Pushing pending events");
1110   for (l = pending_events; l; l = l->next)
1111     gst_audio_decoder_push_event (dec, l->data);
1112   g_list_free (pending_events);
1113 }
1114
1115 /* Iterate the list of pending events, and ensure
1116  * the current output segment is up to date for
1117  * decoding */
1118 static void
1119 apply_pending_events (GstAudioDecoder * dec)
1120 {
1121   GstAudioDecoderPrivate *priv = dec->priv;
1122   GList *l;
1123
1124   GST_DEBUG_OBJECT (dec, "Applying pending segments");
1125   for (l = priv->pending_events; l; l = l->next) {
1126     GstEvent *event = GST_EVENT (l->data);
1127     switch (GST_EVENT_TYPE (event)) {
1128       case GST_EVENT_SEGMENT:{
1129         GstSegment seg;
1130
1131         GST_AUDIO_DECODER_STREAM_LOCK (dec);
1132         gst_event_copy_segment (event, &seg);
1133
1134         GST_DEBUG_OBJECT (dec, "starting segment %" GST_SEGMENT_FORMAT, &seg);
1135
1136         dec->output_segment = seg;
1137         dec->priv->in_out_segment_sync =
1138             gst_segment_is_equal (&dec->input_segment, &seg);
1139         GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
1140         break;
1141       }
1142       default:
1143         break;
1144     }
1145   }
1146 }
1147
1148 static GstFlowReturn
1149 check_pending_reconfigure (GstAudioDecoder * dec)
1150 {
1151   GstFlowReturn ret = GST_FLOW_OK;
1152   GstAudioDecoderContext *ctx;
1153   gboolean needs_reconfigure;
1154
1155   ctx = &dec->priv->ctx;
1156
1157   needs_reconfigure = gst_pad_check_reconfigure (dec->srcpad);
1158   if (G_UNLIKELY (ctx->output_format_changed ||
1159           (GST_AUDIO_INFO_IS_VALID (&ctx->info)
1160               && needs_reconfigure))) {
1161     if (!gst_audio_decoder_negotiate_unlocked (dec)) {
1162       gst_pad_mark_reconfigure (dec->srcpad);
1163       if (GST_PAD_IS_FLUSHING (dec->srcpad))
1164         ret = GST_FLOW_FLUSHING;
1165       else
1166         ret = GST_FLOW_NOT_NEGOTIATED;
1167     }
1168   }
1169   return ret;
1170 }
1171
1172 static gboolean
1173 gst_audio_decoder_transform_meta_default (GstAudioDecoder *
1174     decoder, GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf)
1175 {
1176   const GstMetaInfo *info = meta->info;
1177   const gchar *const *tags;
1178
1179   tags = gst_meta_api_type_get_tags (info->api);
1180
1181   if (!tags || (g_strv_length ((gchar **) tags) == 1
1182           && gst_meta_api_type_has_tag (info->api,
1183               g_quark_from_string (GST_META_TAG_AUDIO_STR))))
1184     return TRUE;
1185
1186   return FALSE;
1187 }
1188
1189 typedef struct
1190 {
1191   GstAudioDecoder *decoder;
1192   GstBuffer *outbuf;
1193 } CopyMetaData;
1194
1195 static gboolean
1196 foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
1197 {
1198   CopyMetaData *data = user_data;
1199   GstAudioDecoder *decoder = data->decoder;
1200   GstAudioDecoderClass *klass = GST_AUDIO_DECODER_GET_CLASS (decoder);
1201   GstBuffer *outbuf = data->outbuf;
1202   const GstMetaInfo *info = (*meta)->info;
1203   gboolean do_copy = FALSE;
1204
1205   if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
1206     /* never call the transform_meta with memory specific metadata */
1207     GST_DEBUG_OBJECT (decoder, "not copying memory specific metadata %s",
1208         g_type_name (info->api));
1209     do_copy = FALSE;
1210   } else if (klass->transform_meta) {
1211     do_copy = klass->transform_meta (decoder, outbuf, *meta, inbuf);
1212     GST_DEBUG_OBJECT (decoder, "transformed metadata %s: copy: %d",
1213         g_type_name (info->api), do_copy);
1214   }
1215
1216   /* we only copy metadata when the subclass implemented a transform_meta
1217    * function and when it returns %TRUE */
1218   if (do_copy && info->transform_func) {
1219     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
1220     GST_DEBUG_OBJECT (decoder, "copy metadata %s", g_type_name (info->api));
1221     /* simply copy then */
1222     info->transform_func (outbuf, *meta, inbuf,
1223         _gst_meta_transform_copy, &copy_data);
1224   }
1225   return TRUE;
1226 }
1227
1228 /**
1229  * gst_audio_decoder_finish_frame:
1230  * @dec: a #GstAudioDecoder
1231  * @buf: decoded data
1232  * @frames: number of decoded frames represented by decoded data
1233  *
1234  * Collects decoded data and pushes it downstream.
1235  *
1236  * @buf may be NULL in which case the indicated number of frames
1237  * are discarded and considered to have produced no output
1238  * (e.g. lead-in or setup frames).
1239  * Otherwise, source pad caps must be set when it is called with valid
1240  * data in @buf.
1241  *
1242  * Note that a frame received in #GstAudioDecoderClass.handle_frame() may be
1243  * invalidated by a call to this function.
1244  *
1245  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
1246  */
1247 GstFlowReturn
1248 gst_audio_decoder_finish_frame (GstAudioDecoder * dec, GstBuffer * buf,
1249     gint frames)
1250 {
1251   GstAudioDecoderPrivate *priv;
1252   GstAudioDecoderContext *ctx;
1253   GstAudioDecoderClass *klass = GST_AUDIO_DECODER_GET_CLASS (dec);
1254   GstAudioMeta *meta;
1255   GstClockTime ts, next_ts;
1256   gsize size, samples = 0;
1257   GstFlowReturn ret = GST_FLOW_OK;
1258   GQueue inbufs = G_QUEUE_INIT;
1259
1260   /* subclass should not hand us no data */
1261   g_return_val_if_fail (buf == NULL || gst_buffer_get_size (buf) > 0,
1262       GST_FLOW_ERROR);
1263   /* no dummy calls please */
1264   g_return_val_if_fail (frames != 0, GST_FLOW_ERROR);
1265
1266   priv = dec->priv;
1267   ctx = &dec->priv->ctx;
1268   meta = buf ? gst_buffer_get_audio_meta (buf) : NULL;
1269   size = buf ? gst_buffer_get_size (buf) : 0;
1270   samples = buf ? (meta ? meta->samples : size / ctx->info.bpf) : 0;
1271
1272   /* must know the output format by now */
1273   g_return_val_if_fail (buf == NULL || GST_AUDIO_INFO_IS_VALID (&ctx->info),
1274       GST_FLOW_ERROR);
1275
1276   GST_LOG_OBJECT (dec,
1277       "accepting %" G_GSIZE_FORMAT " bytes == %" G_GSIZE_FORMAT
1278       " samples for %d frames", buf ? size : 0, samples, frames);
1279
1280   GST_AUDIO_DECODER_STREAM_LOCK (dec);
1281
1282   if (buf) {
1283     ret = check_pending_reconfigure (dec);
1284     if (ret == GST_FLOW_FLUSHING || ret == GST_FLOW_NOT_NEGOTIATED) {
1285       gst_buffer_unref (buf);
1286       goto exit;
1287     }
1288
1289     if (priv->pending_events)
1290       send_pending_events (dec);
1291   }
1292
1293   /* sanity checking */
1294   if (G_LIKELY (buf && ctx->info.bpf)) {
1295     if (!meta || meta->info.layout == GST_AUDIO_LAYOUT_INTERLEAVED) {
1296       /* output shoud be whole number of sample frames */
1297       if (size % ctx->info.bpf)
1298         goto wrong_buffer;
1299       /* output should have no additional padding */
1300       if (samples != size / ctx->info.bpf)
1301         goto wrong_samples;
1302     } else {
1303       /* can't have more samples than what the buffer fits */
1304       if (samples > size / ctx->info.bpf)
1305         goto wrong_samples;
1306     }
1307   }
1308
1309   /* frame and ts book-keeping */
1310   if (G_UNLIKELY (frames < 0)) {
1311     if (G_UNLIKELY (-frames - 1 > priv->frames.length)) {
1312       GST_ELEMENT_WARNING (dec, STREAM, DECODE,
1313           ("received more decoded frames %d than provided %d", frames,
1314               priv->frames.length), (NULL));
1315       frames = 0;
1316     } else {
1317       frames = priv->frames.length + frames + 1;
1318     }
1319   } else if (G_UNLIKELY (frames > priv->frames.length)) {
1320     if (G_LIKELY (!priv->force)) {
1321       GST_ELEMENT_WARNING (dec, STREAM, DECODE,
1322           ("received more decoded frames %d than provided %d", frames,
1323               priv->frames.length), (NULL));
1324     }
1325     frames = priv->frames.length;
1326   }
1327
1328   if (G_LIKELY (priv->frames.length))
1329     ts = GST_BUFFER_TIMESTAMP (priv->frames.head->data);
1330   else
1331     ts = GST_CLOCK_TIME_NONE;
1332
1333   GST_DEBUG_OBJECT (dec, "leading frame ts %" GST_TIME_FORMAT,
1334       GST_TIME_ARGS (ts));
1335
1336   while (priv->frames.length && frames) {
1337     g_queue_push_tail (&inbufs, g_queue_pop_head (&priv->frames));
1338     dec->priv->ctx.delay = dec->priv->frames.length;
1339     frames--;
1340   }
1341
1342   if (G_UNLIKELY (!buf))
1343     goto exit;
1344
1345   /* lock on */
1346   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
1347     priv->base_ts = ts;
1348     GST_DEBUG_OBJECT (dec, "base_ts now %" GST_TIME_FORMAT, GST_TIME_ARGS (ts));
1349   }
1350
1351   /* still no valid ts, track the segment one */
1352   if (G_UNLIKELY (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) &&
1353       dec->output_segment.rate > 0.0) {
1354     priv->base_ts = dec->output_segment.start;
1355   }
1356
1357   /* slightly convoluted approach caters for perfect ts if subclass desires */
1358   if (GST_CLOCK_TIME_IS_VALID (ts)) {
1359     if (dec->priv->tolerance > 0) {
1360       GstClockTimeDiff diff;
1361
1362       g_assert (GST_CLOCK_TIME_IS_VALID (priv->base_ts));
1363       next_ts = priv->base_ts +
1364           gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
1365       GST_LOG_OBJECT (dec,
1366           "buffer is %" G_GUINT64_FORMAT " samples past base_ts %"
1367           GST_TIME_FORMAT ", expected ts %" GST_TIME_FORMAT, priv->samples,
1368           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
1369       diff = GST_CLOCK_DIFF (next_ts, ts);
1370       GST_LOG_OBJECT (dec, "ts diff %d ms", (gint) (diff / GST_MSECOND));
1371       /* if within tolerance,
1372        * discard buffer ts and carry on producing perfect stream,
1373        * otherwise resync to ts */
1374       if (G_UNLIKELY (diff < (gint64) - dec->priv->tolerance ||
1375               diff > (gint64) dec->priv->tolerance)) {
1376         GST_DEBUG_OBJECT (dec, "base_ts resync");
1377         priv->base_ts = ts;
1378         priv->samples = 0;
1379       }
1380     } else {
1381       GST_DEBUG_OBJECT (dec, "base_ts resync");
1382       priv->base_ts = ts;
1383       priv->samples = 0;
1384     }
1385   }
1386
1387   /* delayed one-shot stuff until confirmed data */
1388   if (priv->taglist && priv->taglist_changed) {
1389     GstEvent *tags_event;
1390
1391     tags_event = gst_audio_decoder_create_merged_tags_event (dec);
1392
1393     if (tags_event != NULL)
1394       gst_audio_decoder_push_event (dec, tags_event);
1395
1396     priv->taglist_changed = FALSE;
1397   }
1398
1399   buf = gst_buffer_make_writable (buf);
1400   if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
1401     GST_BUFFER_TIMESTAMP (buf) =
1402         priv->base_ts +
1403         GST_FRAMES_TO_CLOCK_TIME (priv->samples, ctx->info.rate);
1404     GST_BUFFER_DURATION (buf) = priv->base_ts +
1405         GST_FRAMES_TO_CLOCK_TIME (priv->samples + samples, ctx->info.rate) -
1406         GST_BUFFER_TIMESTAMP (buf);
1407   } else {
1408     GST_BUFFER_TIMESTAMP (buf) = GST_CLOCK_TIME_NONE;
1409     GST_BUFFER_DURATION (buf) =
1410         GST_FRAMES_TO_CLOCK_TIME (samples, ctx->info.rate);
1411   }
1412
1413   if (klass->transform_meta) {
1414     if (inbufs.length) {
1415       GList *l;
1416       for (l = inbufs.head; l; l = l->next) {
1417         CopyMetaData data;
1418
1419         data.decoder = dec;
1420         data.outbuf = buf;
1421         gst_buffer_foreach_meta (l->data, foreach_metadata, &data);
1422       }
1423     } else {
1424       GST_WARNING_OBJECT (dec,
1425           "Can't copy metadata because input buffers disappeared");
1426     }
1427   }
1428
1429   GST_OBJECT_LOCK (dec);
1430   priv->samples += samples;
1431   priv->samples_out += samples;
1432   GST_OBJECT_UNLOCK (dec);
1433
1434   /* we got data, so note things are looking up */
1435   if (G_UNLIKELY (dec->priv->error_count))
1436     dec->priv->error_count = 0;
1437
1438   ret = gst_audio_decoder_output (dec, buf);
1439
1440 exit:
1441   g_queue_foreach (&inbufs, (GFunc) gst_buffer_unref, NULL);
1442   g_queue_clear (&inbufs);
1443
1444   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
1445
1446   return ret;
1447
1448   /* ERRORS */
1449 wrong_buffer:
1450   {
1451     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
1452         ("buffer size %" G_GSIZE_FORMAT " not a multiple of %d", size,
1453             ctx->info.bpf));
1454     gst_buffer_unref (buf);
1455     ret = GST_FLOW_ERROR;
1456     goto exit;
1457   }
1458 wrong_samples:
1459   {
1460     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL),
1461         ("GstAudioMeta samples (%" G_GSIZE_FORMAT ") are inconsistent with "
1462             "the buffer size and layout (size/bpf = %" G_GSIZE_FORMAT ")",
1463             meta->samples, size / ctx->info.bpf));
1464     gst_buffer_unref (buf);
1465     ret = GST_FLOW_ERROR;
1466     goto exit;
1467   }
1468 }
1469
1470 static GstFlowReturn
1471 gst_audio_decoder_handle_frame (GstAudioDecoder * dec,
1472     GstAudioDecoderClass * klass, GstBuffer * buffer)
1473 {
1474   /* Skip decoding and send a GAP instead if
1475    * GST_SEGMENT_FLAG_TRICKMODE_NO_AUDIO is set and we have timestamps
1476    * FIXME: We only do this for forward playback atm, because reverse
1477    * playback would require accumulating GAP events and pushing them
1478    * out in reverse order as for normal audio samples
1479    */
1480   if (G_UNLIKELY (dec->input_segment.rate > 0.0
1481           && dec->input_segment.flags & GST_SEGMENT_FLAG_TRICKMODE_NO_AUDIO)) {
1482     if (buffer) {
1483       GstClockTime ts = GST_BUFFER_PTS (buffer);
1484       if (GST_CLOCK_TIME_IS_VALID (ts)) {
1485         GstEvent *event = gst_event_new_gap (ts, GST_BUFFER_DURATION (buffer));
1486
1487         gst_buffer_unref (buffer);
1488         GST_LOG_OBJECT (dec, "Skipping decode in trickmode and sending gap");
1489         gst_audio_decoder_handle_gap (dec, event);
1490         return GST_FLOW_OK;
1491       }
1492     }
1493   }
1494
1495   if (G_LIKELY (buffer)) {
1496     gsize size = gst_buffer_get_size (buffer);
1497     /* keep around for admin */
1498     GST_LOG_OBJECT (dec,
1499         "tracking frame size %" G_GSIZE_FORMAT ", ts %" GST_TIME_FORMAT, size,
1500         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)));
1501     g_queue_push_tail (&dec->priv->frames, buffer);
1502     dec->priv->ctx.delay = dec->priv->frames.length;
1503     GST_OBJECT_LOCK (dec);
1504     dec->priv->bytes_in += size;
1505     GST_OBJECT_UNLOCK (dec);
1506   } else {
1507     GST_LOG_OBJECT (dec, "providing subclass with NULL frame");
1508   }
1509
1510   return klass->handle_frame (dec, buffer);
1511 }
1512
1513 /* maybe subclass configurable instead, but this allows for a whole lot of
1514  * raw samples, so at least quite some encoded ... */
1515 #define GST_AUDIO_DECODER_MAX_SYNC     10 * 8 * 2 * 1024
1516
1517 static GstFlowReturn
1518 gst_audio_decoder_push_buffers (GstAudioDecoder * dec, gboolean force)
1519 {
1520   GstAudioDecoderClass *klass;
1521   GstAudioDecoderPrivate *priv;
1522   GstAudioDecoderContext *ctx;
1523   GstFlowReturn ret = GST_FLOW_OK;
1524   GstBuffer *buffer;
1525   gint av, flush;
1526
1527   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
1528   priv = dec->priv;
1529   ctx = &dec->priv->ctx;
1530
1531   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1532
1533   av = gst_adapter_available (priv->adapter);
1534   GST_DEBUG_OBJECT (dec, "available: %d", av);
1535
1536   while (ret == GST_FLOW_OK) {
1537
1538     flush = 0;
1539     ctx->eos = force;
1540
1541     if (G_LIKELY (av)) {
1542       gint len;
1543       GstClockTime ts;
1544       guint64 distance;
1545
1546       /* parse if needed */
1547       if (klass->parse) {
1548         gint offset = 0;
1549
1550         /* limited (legacy) parsing; avoid whole of baseparse */
1551         GST_DEBUG_OBJECT (dec, "parsing available: %d", av);
1552         /* piggyback sync state on discont */
1553         ctx->sync = !priv->discont;
1554         ret = klass->parse (dec, priv->adapter, &offset, &len);
1555
1556         g_assert (offset <= av);
1557         if (offset) {
1558           /* jumped a bit */
1559           GST_DEBUG_OBJECT (dec, "skipped %d; setting DISCONT", offset);
1560           gst_adapter_flush (priv->adapter, offset);
1561           flush = offset;
1562           /* avoid parsing indefinitely */
1563           priv->sync_flush += offset;
1564           if (priv->sync_flush > GST_AUDIO_DECODER_MAX_SYNC)
1565             goto parse_failed;
1566         }
1567
1568         if (ret == GST_FLOW_EOS) {
1569           GST_LOG_OBJECT (dec, "no frame yet");
1570           ret = GST_FLOW_OK;
1571           break;
1572         } else if (ret == GST_FLOW_OK) {
1573           GST_LOG_OBJECT (dec, "frame at offset %d of length %d", offset, len);
1574           g_assert (len);
1575           g_assert (offset + len <= av);
1576           priv->sync_flush = 0;
1577         } else {
1578           break;
1579         }
1580       } else {
1581         len = av;
1582       }
1583       /* track upstream ts, but do not get stuck if nothing new upstream */
1584       ts = gst_adapter_prev_pts (priv->adapter, &distance);
1585       if (ts != priv->prev_ts || distance <= priv->prev_distance) {
1586         priv->prev_ts = ts;
1587         priv->prev_distance = distance;
1588       } else {
1589         GST_LOG_OBJECT (dec, "ts == prev_ts; discarding");
1590         ts = GST_CLOCK_TIME_NONE;
1591       }
1592       buffer = gst_adapter_take_buffer (priv->adapter, len);
1593       buffer = gst_buffer_make_writable (buffer);
1594       GST_BUFFER_TIMESTAMP (buffer) = ts;
1595       flush += len;
1596       priv->force = FALSE;
1597     } else {
1598       if (!force)
1599         break;
1600       if (!priv->drainable) {
1601         priv->drained = TRUE;
1602         break;
1603       }
1604       buffer = NULL;
1605       priv->force = TRUE;
1606     }
1607
1608     ret = gst_audio_decoder_handle_frame (dec, klass, buffer);
1609
1610     /* do not keep pushing it ... */
1611     if (G_UNLIKELY (!av)) {
1612       priv->drained = TRUE;
1613       break;
1614     }
1615
1616     av -= flush;
1617     g_assert (av >= 0);
1618   }
1619
1620   GST_LOG_OBJECT (dec, "done pushing to subclass");
1621   return ret;
1622
1623   /* ERRORS */
1624 parse_failed:
1625   {
1626     GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("failed to parse stream"));
1627     return GST_FLOW_ERROR;
1628   }
1629 }
1630
1631 static GstFlowReturn
1632 gst_audio_decoder_drain (GstAudioDecoder * dec)
1633 {
1634   GstFlowReturn ret;
1635
1636   if (dec->priv->drained && !dec->priv->gather)
1637     return GST_FLOW_OK;
1638
1639   /* Apply any pending events before draining, as that
1640    * may update the pending segment info */
1641   apply_pending_events (dec);
1642
1643   /* dispatch reverse pending buffers */
1644   /* chain eventually calls upon drain as well, but by that time
1645    * gather list should be clear, so ok ... */
1646   if (dec->output_segment.rate < 0.0 && dec->priv->gather)
1647     gst_audio_decoder_chain_reverse (dec, NULL);
1648   /* have subclass give all it can */
1649   ret = gst_audio_decoder_push_buffers (dec, TRUE);
1650   if (ret != GST_FLOW_OK) {
1651     GST_WARNING_OBJECT (dec, "audio decoder push buffers failed");
1652     goto drain_failed;
1653   }
1654   /* ensure all output sent */
1655   ret = gst_audio_decoder_output (dec, NULL);
1656   if (ret != GST_FLOW_OK)
1657     GST_WARNING_OBJECT (dec, "audio decoder output failed");
1658
1659 drain_failed:
1660   /* everything should be away now */
1661   if (dec->priv->frames.length) {
1662     /* not fatal/impossible though if subclass/codec eats stuff */
1663     GST_WARNING_OBJECT (dec, "still %d frames left after draining",
1664         dec->priv->frames.length);
1665     g_queue_foreach (&dec->priv->frames, (GFunc) gst_buffer_unref, NULL);
1666     g_queue_clear (&dec->priv->frames);
1667   }
1668
1669   /* discard (unparsed) leftover */
1670   gst_adapter_clear (dec->priv->adapter);
1671   return ret;
1672 }
1673
1674 /* hard == FLUSH, otherwise discont */
1675 static GstFlowReturn
1676 gst_audio_decoder_flush (GstAudioDecoder * dec, gboolean hard)
1677 {
1678   GstAudioDecoderClass *klass;
1679   GstFlowReturn ret = GST_FLOW_OK;
1680
1681   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
1682
1683   GST_LOG_OBJECT (dec, "flush hard %d", hard);
1684
1685   if (!hard) {
1686     ret = gst_audio_decoder_drain (dec);
1687   } else {
1688     gst_audio_decoder_clear_queues (dec);
1689     gst_segment_init (&dec->input_segment, GST_FORMAT_TIME);
1690     gst_segment_init (&dec->output_segment, GST_FORMAT_TIME);
1691     dec->priv->error_count = 0;
1692   }
1693   /* only bother subclass with flushing if known it is already alive
1694    * and kicking out stuff */
1695   if (klass->flush && dec->priv->samples_out > 0)
1696     klass->flush (dec, hard);
1697   /* and get (re)set for the sequel */
1698   gst_audio_decoder_reset (dec, FALSE);
1699
1700   return ret;
1701 }
1702
1703 static GstFlowReturn
1704 gst_audio_decoder_chain_forward (GstAudioDecoder * dec, GstBuffer * buffer)
1705 {
1706   GstFlowReturn ret = GST_FLOW_OK;
1707
1708   /* discard silly case, though maybe ts may be of value ?? */
1709   if (G_UNLIKELY (gst_buffer_get_size (buffer) == 0)) {
1710     GST_DEBUG_OBJECT (dec, "discarding empty buffer");
1711     gst_buffer_unref (buffer);
1712     goto exit;
1713   }
1714
1715   /* grab buffer */
1716   gst_adapter_push (dec->priv->adapter, buffer);
1717   buffer = NULL;
1718   /* new stuff, so we can push subclass again */
1719   dec->priv->drained = FALSE;
1720
1721   /* hand to subclass */
1722   ret = gst_audio_decoder_push_buffers (dec, FALSE);
1723
1724 exit:
1725   GST_LOG_OBJECT (dec, "chain-done");
1726   return ret;
1727 }
1728
1729 static void
1730 gst_audio_decoder_clear_queues (GstAudioDecoder * dec)
1731 {
1732   GstAudioDecoderPrivate *priv = dec->priv;
1733
1734   g_list_foreach (priv->queued, (GFunc) gst_mini_object_unref, NULL);
1735   g_list_free (priv->queued);
1736   priv->queued = NULL;
1737   g_list_foreach (priv->gather, (GFunc) gst_mini_object_unref, NULL);
1738   g_list_free (priv->gather);
1739   priv->gather = NULL;
1740   g_list_foreach (priv->decode, (GFunc) gst_mini_object_unref, NULL);
1741   g_list_free (priv->decode);
1742   priv->decode = NULL;
1743 }
1744
1745 /*
1746  * Input:
1747  *  Buffer decoding order:  7  8  9  4  5  6  3  1  2  EOS
1748  *  Discont flag:           D        D        D  D
1749  *
1750  * - Each Discont marks a discont in the decoding order.
1751  *
1752  * for vorbis, each buffer is a keyframe when we have the previous
1753  * buffer. This means that to decode buffer 7, we need buffer 6, which
1754  * arrives out of order.
1755  *
1756  * we first gather buffers in the gather queue until we get a DISCONT. We
1757  * prepend each incomming buffer so that they are in reversed order.
1758  *
1759  *    gather queue:    9  8  7
1760  *    decode queue:
1761  *    output queue:
1762  *
1763  * When a DISCONT is received (buffer 4), we move the gather queue to the
1764  * decode queue. This is simply done be taking the head of the gather queue
1765  * and prepending it to the decode queue. This yields:
1766  *
1767  *    gather queue:
1768  *    decode queue:    7  8  9
1769  *    output queue:
1770  *
1771  * Then we decode each buffer in the decode queue in order and put the output
1772  * buffer in the output queue. The first buffer (7) will not produce any output
1773  * because it needs the previous buffer (6) which did not arrive yet. This
1774  * yields:
1775  *
1776  *    gather queue:
1777  *    decode queue:    7  8  9
1778  *    output queue:    9  8
1779  *
1780  * Then we remove the consumed buffers from the decode queue. Buffer 7 is not
1781  * completely consumed, we need to keep it around for when we receive buffer
1782  * 6. This yields:
1783  *
1784  *    gather queue:
1785  *    decode queue:    7
1786  *    output queue:    9  8
1787  *
1788  * Then we accumulate more buffers:
1789  *
1790  *    gather queue:    6  5  4
1791  *    decode queue:    7
1792  *    output queue:
1793  *
1794  * prepending to the decode queue on DISCONT yields:
1795  *
1796  *    gather queue:
1797  *    decode queue:    4  5  6  7
1798  *    output queue:
1799  *
1800  * after decoding and keeping buffer 4:
1801  *
1802  *    gather queue:
1803  *    decode queue:    4
1804  *    output queue:    7  6  5
1805  *
1806  * Etc..
1807  */
1808 static GstFlowReturn
1809 gst_audio_decoder_flush_decode (GstAudioDecoder * dec)
1810 {
1811   GstAudioDecoderPrivate *priv = dec->priv;
1812   GstFlowReturn res = GST_FLOW_OK;
1813   GstClockTime timestamp;
1814   GList *walk;
1815
1816   walk = priv->decode;
1817
1818   GST_DEBUG_OBJECT (dec, "flushing buffers to decoder");
1819
1820   /* clear buffer and decoder state */
1821   gst_audio_decoder_flush (dec, FALSE);
1822
1823   while (walk) {
1824     GList *next;
1825     GstBuffer *buf = GST_BUFFER_CAST (walk->data);
1826
1827     GST_DEBUG_OBJECT (dec, "decoding buffer %p, ts %" GST_TIME_FORMAT,
1828         buf, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1829
1830     next = g_list_next (walk);
1831     /* decode buffer, resulting data prepended to output queue */
1832     gst_buffer_ref (buf);
1833     res = gst_audio_decoder_chain_forward (dec, buf);
1834
1835     /* if we generated output, we can discard the buffer, else we
1836      * keep it in the queue */
1837     if (priv->queued) {
1838       GST_DEBUG_OBJECT (dec, "decoded buffer to %p", priv->queued->data);
1839       priv->decode = g_list_delete_link (priv->decode, walk);
1840       gst_buffer_unref (buf);
1841     } else {
1842       GST_DEBUG_OBJECT (dec, "buffer did not decode, keeping");
1843     }
1844     walk = next;
1845   }
1846
1847   /* drain any aggregation (or otherwise) leftover */
1848   gst_audio_decoder_drain (dec);
1849
1850   /* now send queued data downstream */
1851   timestamp = GST_CLOCK_TIME_NONE;
1852   while (priv->queued) {
1853     GstBuffer *buf = GST_BUFFER_CAST (priv->queued->data);
1854     GstClockTime duration;
1855
1856     duration = GST_BUFFER_DURATION (buf);
1857
1858     /* duration should always be valid for raw audio */
1859     g_assert (GST_CLOCK_TIME_IS_VALID (duration));
1860
1861     /* interpolate (backward) if needed */
1862     if (G_LIKELY (timestamp != -1)) {
1863       if (timestamp > duration)
1864         timestamp -= duration;
1865       else
1866         timestamp = 0;
1867     }
1868
1869     if (!GST_BUFFER_TIMESTAMP_IS_VALID (buf)) {
1870       GST_LOG_OBJECT (dec, "applying reverse interpolated ts %"
1871           GST_TIME_FORMAT, GST_TIME_ARGS (timestamp));
1872       GST_BUFFER_TIMESTAMP (buf) = timestamp;
1873     } else {
1874       /* track otherwise */
1875       timestamp = GST_BUFFER_TIMESTAMP (buf);
1876       GST_LOG_OBJECT (dec, "tracking ts %" GST_TIME_FORMAT,
1877           GST_TIME_ARGS (timestamp));
1878     }
1879
1880     if (G_LIKELY (res == GST_FLOW_OK)) {
1881       GST_DEBUG_OBJECT (dec, "pushing buffer %p of size %" G_GSIZE_FORMAT ", "
1882           "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
1883           gst_buffer_get_size (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1884           GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1885       /* should be already, but let's be sure */
1886       buf = gst_buffer_make_writable (buf);
1887       /* avoid stray DISCONT from forward processing,
1888        * which have no meaning in reverse pushing */
1889       GST_BUFFER_FLAG_UNSET (buf, GST_BUFFER_FLAG_DISCONT);
1890       res = gst_audio_decoder_push_forward (dec, buf);
1891     } else {
1892       gst_buffer_unref (buf);
1893     }
1894
1895     priv->queued = g_list_delete_link (priv->queued, priv->queued);
1896   }
1897
1898   return res;
1899 }
1900
1901 static GstFlowReturn
1902 gst_audio_decoder_chain_reverse (GstAudioDecoder * dec, GstBuffer * buf)
1903 {
1904   GstAudioDecoderPrivate *priv = dec->priv;
1905   GstFlowReturn result = GST_FLOW_OK;
1906
1907   /* if we have a discont, move buffers to the decode list */
1908   if (!buf || GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT)) {
1909     GST_DEBUG_OBJECT (dec, "received discont");
1910     while (priv->gather) {
1911       GstBuffer *gbuf;
1912
1913       gbuf = GST_BUFFER_CAST (priv->gather->data);
1914       /* remove from the gather list */
1915       priv->gather = g_list_delete_link (priv->gather, priv->gather);
1916       /* copy to decode queue */
1917       priv->decode = g_list_prepend (priv->decode, gbuf);
1918     }
1919     /* decode stuff in the decode queue */
1920     gst_audio_decoder_flush_decode (dec);
1921   }
1922
1923   if (G_LIKELY (buf)) {
1924     GST_DEBUG_OBJECT (dec, "gathering buffer %p of size %" G_GSIZE_FORMAT ", "
1925         "time %" GST_TIME_FORMAT ", dur %" GST_TIME_FORMAT, buf,
1926         gst_buffer_get_size (buf), GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
1927         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1928
1929     /* add buffer to gather queue */
1930     priv->gather = g_list_prepend (priv->gather, buf);
1931   }
1932
1933   return result;
1934 }
1935
1936 static GstFlowReturn
1937 gst_audio_decoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1938 {
1939   GstAudioDecoder *dec;
1940   GstFlowReturn ret;
1941
1942   dec = GST_AUDIO_DECODER (parent);
1943
1944   GST_LOG_OBJECT (dec,
1945       "received buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1946       ", duration %" GST_TIME_FORMAT, gst_buffer_get_size (buffer),
1947       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1948       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1949
1950   GST_AUDIO_DECODER_STREAM_LOCK (dec);
1951
1952   if (G_UNLIKELY (dec->priv->ctx.input_caps == NULL && dec->priv->needs_format))
1953     goto not_negotiated;
1954
1955   dec->priv->ctx.had_input_data = TRUE;
1956
1957   if (!dec->priv->expecting_discont_buf &&
1958       GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT)) {
1959     gint64 samples, ts;
1960
1961     /* track present position */
1962     ts = dec->priv->base_ts;
1963     samples = dec->priv->samples;
1964
1965     GST_DEBUG_OBJECT (dec, "handling discont");
1966     gst_audio_decoder_flush (dec, FALSE);
1967     dec->priv->discont = TRUE;
1968
1969     /* buffer may claim DISCONT loudly, if it can't tell us where we are now,
1970      * we'll stick to where we were ...
1971      * Particularly useful/needed for upstream BYTE based */
1972     if (dec->input_segment.rate > 0.0
1973         && !GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1974       GST_DEBUG_OBJECT (dec, "... but restoring previous ts tracking");
1975       dec->priv->base_ts = ts;
1976       dec->priv->samples = samples;
1977     }
1978   }
1979   dec->priv->expecting_discont_buf = FALSE;
1980
1981   if (dec->input_segment.rate > 0.0)
1982     ret = gst_audio_decoder_chain_forward (dec, buffer);
1983   else
1984     ret = gst_audio_decoder_chain_reverse (dec, buffer);
1985
1986   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
1987
1988   return ret;
1989
1990   /* ERRORS */
1991 not_negotiated:
1992   {
1993     GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
1994     GST_ELEMENT_ERROR (dec, CORE, NEGOTIATION, (NULL),
1995         ("decoder not initialized"));
1996     gst_buffer_unref (buffer);
1997     return GST_FLOW_NOT_NEGOTIATED;
1998   }
1999 }
2000
2001 /* perform upstream byte <-> time conversion (duration, seeking)
2002  * if subclass allows and if enough data for moderately decent conversion */
2003 static inline gboolean
2004 gst_audio_decoder_do_byte (GstAudioDecoder * dec)
2005 {
2006   gboolean ret;
2007
2008   GST_OBJECT_LOCK (dec);
2009   ret = dec->priv->ctx.do_estimate_rate && dec->priv->ctx.info.bpf &&
2010       dec->priv->ctx.info.rate <= dec->priv->samples_out;
2011   GST_OBJECT_UNLOCK (dec);
2012
2013   return ret;
2014 }
2015
2016 /* Must be called holding the GST_AUDIO_DECODER_STREAM_LOCK */
2017 static gboolean
2018 gst_audio_decoder_negotiate_default_caps (GstAudioDecoder * dec)
2019 {
2020   GstCaps *caps, *templcaps;
2021   gint i;
2022   gint channels = 0;
2023   gint rate;
2024   guint64 channel_mask = 0;
2025   gint caps_size;
2026   GstStructure *structure;
2027   GstAudioInfo info;
2028
2029   templcaps = gst_pad_get_pad_template_caps (dec->srcpad);
2030   caps = gst_pad_peer_query_caps (dec->srcpad, templcaps);
2031   if (caps)
2032     gst_caps_unref (templcaps);
2033   else
2034     caps = templcaps;
2035   templcaps = NULL;
2036
2037   if (!caps || gst_caps_is_empty (caps) || gst_caps_is_any (caps))
2038     goto caps_error;
2039
2040   GST_LOG_OBJECT (dec, "peer caps  %" GST_PTR_FORMAT, caps);
2041
2042   /* before fixating, try to use whatever upstream provided */
2043   caps = gst_caps_make_writable (caps);
2044   caps_size = gst_caps_get_size (caps);
2045   if (dec->priv->ctx.input_caps) {
2046     GstCaps *sinkcaps = dec->priv->ctx.input_caps;
2047     GstStructure *structure = gst_caps_get_structure (sinkcaps, 0);
2048
2049     if (gst_structure_get_int (structure, "rate", &rate)) {
2050       for (i = 0; i < caps_size; i++) {
2051         gst_structure_set (gst_caps_get_structure (caps, i), "rate",
2052             G_TYPE_INT, rate, NULL);
2053       }
2054     }
2055
2056     if (gst_structure_get_int (structure, "channels", &channels)) {
2057       for (i = 0; i < caps_size; i++) {
2058         gst_structure_set (gst_caps_get_structure (caps, i), "channels",
2059             G_TYPE_INT, channels, NULL);
2060       }
2061     }
2062
2063     if (gst_structure_get (structure, "channel-mask", GST_TYPE_BITMASK,
2064             &channel_mask, NULL)) {
2065       for (i = 0; i < caps_size; i++) {
2066         gst_structure_set (gst_caps_get_structure (caps, i), "channel-mask",
2067             GST_TYPE_BITMASK, channel_mask, NULL);
2068       }
2069     }
2070   }
2071
2072   for (i = 0; i < caps_size; i++) {
2073     structure = gst_caps_get_structure (caps, i);
2074     if (gst_structure_has_field (structure, "channels"))
2075       gst_structure_fixate_field_nearest_int (structure,
2076           "channels", GST_AUDIO_DEF_CHANNELS);
2077     else
2078       gst_structure_set (structure, "channels", G_TYPE_INT,
2079           GST_AUDIO_DEF_CHANNELS, NULL);
2080     if (gst_structure_has_field (structure, "rate"))
2081       gst_structure_fixate_field_nearest_int (structure,
2082           "rate", GST_AUDIO_DEF_RATE);
2083     else
2084       gst_structure_set (structure, "rate", G_TYPE_INT, GST_AUDIO_DEF_RATE,
2085           NULL);
2086   }
2087   caps = gst_caps_fixate (caps);
2088   structure = gst_caps_get_structure (caps, 0);
2089
2090   /* Need to add a channel-mask if channels > 2 */
2091   gst_structure_get_int (structure, "channels", &channels);
2092   if (channels > 2 && !gst_structure_has_field (structure, "channel-mask")) {
2093     channel_mask = gst_audio_channel_get_fallback_mask (channels);
2094     if (channel_mask != 0) {
2095       gst_structure_set (structure, "channel-mask",
2096           GST_TYPE_BITMASK, channel_mask, NULL);
2097     } else {
2098       GST_WARNING_OBJECT (dec, "No default channel-mask for %d channels",
2099           channels);
2100     }
2101   }
2102
2103   if (!caps || !gst_audio_info_from_caps (&info, caps))
2104     goto caps_error;
2105
2106   GST_OBJECT_LOCK (dec);
2107   dec->priv->ctx.info = info;
2108   GST_OBJECT_UNLOCK (dec);
2109
2110   GST_INFO_OBJECT (dec,
2111       "Chose default caps %" GST_PTR_FORMAT " for initial gap", caps);
2112   gst_caps_unref (caps);
2113
2114   return TRUE;
2115
2116 caps_error:
2117   {
2118     if (caps)
2119       gst_caps_unref (caps);
2120     return FALSE;
2121   }
2122 }
2123
2124 static gboolean
2125 gst_audio_decoder_handle_gap (GstAudioDecoder * dec, GstEvent * event)
2126 {
2127   gboolean ret;
2128   GstClockTime timestamp, duration;
2129   gboolean needs_reconfigure = FALSE;
2130
2131   /* Ensure we have caps first */
2132   GST_AUDIO_DECODER_STREAM_LOCK (dec);
2133   if (!GST_AUDIO_INFO_IS_VALID (&dec->priv->ctx.info)) {
2134     if (!gst_audio_decoder_negotiate_default_caps (dec)) {
2135       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2136       GST_ELEMENT_ERROR (dec, STREAM, FORMAT, (NULL),
2137           ("Decoder output not negotiated before GAP event."));
2138       return FALSE;
2139     }
2140     needs_reconfigure = TRUE;
2141   }
2142   needs_reconfigure = gst_pad_check_reconfigure (dec->srcpad)
2143       || needs_reconfigure;
2144   if (G_UNLIKELY (dec->priv->ctx.output_format_changed || needs_reconfigure)) {
2145     if (!gst_audio_decoder_negotiate_unlocked (dec)) {
2146       GST_WARNING_OBJECT (dec, "Failed to negotiate with downstream");
2147       gst_pad_mark_reconfigure (dec->srcpad);
2148     }
2149   }
2150   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2151
2152   gst_event_parse_gap (event, &timestamp, &duration);
2153
2154   /* time progressed without data, see if we can fill the gap with
2155    * some concealment data */
2156   GST_DEBUG_OBJECT (dec,
2157       "gap event: plc %d, do_plc %d, position %" GST_TIME_FORMAT
2158       " duration %" GST_TIME_FORMAT,
2159       dec->priv->plc, dec->priv->ctx.do_plc,
2160       GST_TIME_ARGS (timestamp), GST_TIME_ARGS (duration));
2161
2162   if (dec->priv->plc && dec->priv->ctx.do_plc && dec->input_segment.rate > 0.0) {
2163     GstAudioDecoderClass *klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2164     GstBuffer *buf;
2165
2166     /* hand subclass empty frame with duration that needs covering */
2167     buf = gst_buffer_new ();
2168     GST_BUFFER_TIMESTAMP (buf) = timestamp;
2169     GST_BUFFER_DURATION (buf) = duration;
2170     /* best effort, not much error handling */
2171     gst_audio_decoder_handle_frame (dec, klass, buf);
2172     ret = TRUE;
2173     dec->priv->expecting_discont_buf = TRUE;
2174     gst_event_unref (event);
2175   } else {
2176     GstFlowReturn flowret;
2177
2178     /* sub-class doesn't know how to handle empty buffers,
2179      * so just try sending GAP downstream */
2180     flowret = check_pending_reconfigure (dec);
2181     if (flowret == GST_FLOW_OK) {
2182       send_pending_events (dec);
2183       ret = gst_audio_decoder_push_event (dec, event);
2184     } else {
2185       ret = FALSE;
2186     }
2187   }
2188   return ret;
2189 }
2190
2191 static GList *
2192 _flush_events (GstPad * pad, GList * events)
2193 {
2194   GList *tmp;
2195
2196   for (tmp = events; tmp; tmp = tmp->next) {
2197     if (GST_EVENT_TYPE (tmp->data) != GST_EVENT_EOS &&
2198         GST_EVENT_TYPE (tmp->data) != GST_EVENT_SEGMENT &&
2199         GST_EVENT_IS_STICKY (tmp->data)) {
2200       gst_pad_store_sticky_event (pad, GST_EVENT_CAST (tmp->data));
2201     }
2202     gst_event_unref (tmp->data);
2203   }
2204   g_list_free (events);
2205
2206   return NULL;
2207 }
2208
2209 static gboolean
2210 gst_audio_decoder_sink_eventfunc (GstAudioDecoder * dec, GstEvent * event)
2211 {
2212   gboolean ret;
2213
2214   switch (GST_EVENT_TYPE (event)) {
2215     case GST_EVENT_STREAM_START:
2216       GST_AUDIO_DECODER_STREAM_LOCK (dec);
2217       /* finish any data in current segment and clear the decoder
2218        * to be ready for new stream data */
2219       gst_audio_decoder_drain (dec);
2220       gst_audio_decoder_flush (dec, FALSE);
2221
2222       GST_DEBUG_OBJECT (dec, "received STREAM_START. Clearing taglist");
2223       /* Flush upstream tags after a STREAM_START */
2224       if (dec->priv->upstream_tags) {
2225         gst_tag_list_unref (dec->priv->upstream_tags);
2226         dec->priv->upstream_tags = NULL;
2227         dec->priv->taglist_changed = TRUE;
2228       }
2229       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2230
2231       ret = gst_audio_decoder_push_event (dec, event);
2232       break;
2233     case GST_EVENT_SEGMENT:
2234     {
2235       GstSegment seg;
2236       GstFormat format;
2237
2238       GST_AUDIO_DECODER_STREAM_LOCK (dec);
2239       gst_event_copy_segment (event, &seg);
2240
2241       format = seg.format;
2242       if (format == GST_FORMAT_TIME) {
2243         GST_DEBUG_OBJECT (dec, "received TIME SEGMENT %" GST_SEGMENT_FORMAT,
2244             &seg);
2245       } else {
2246         gint64 nstart;
2247         GST_DEBUG_OBJECT (dec, "received SEGMENT %" GST_SEGMENT_FORMAT, &seg);
2248         /* handle newsegment resulting from legacy simple seeking */
2249         /* note that we need to convert this whether or not enough data
2250          * to handle initial newsegment */
2251         if (dec->priv->ctx.do_estimate_rate &&
2252             gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, seg.start,
2253                 GST_FORMAT_TIME, &nstart)) {
2254           /* best attempt convert */
2255           /* as these are only estimates, stop is kept open-ended to avoid
2256            * premature cutting */
2257           GST_DEBUG_OBJECT (dec, "converted to TIME start %" GST_TIME_FORMAT,
2258               GST_TIME_ARGS (nstart));
2259           seg.format = GST_FORMAT_TIME;
2260           seg.start = nstart;
2261           seg.time = nstart;
2262           seg.stop = GST_CLOCK_TIME_NONE;
2263           /* replace event */
2264           gst_event_unref (event);
2265           event = gst_event_new_segment (&seg);
2266         } else {
2267           GST_DEBUG_OBJECT (dec, "unsupported format; ignoring");
2268           GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2269           gst_event_unref (event);
2270           ret = FALSE;
2271           break;
2272         }
2273       }
2274
2275       /* prepare for next segment */
2276       /* Use the segment start as a base timestamp
2277        * in case upstream does not come up with anything better
2278        * (e.g. upstream BYTE) */
2279       if (format != GST_FORMAT_TIME) {
2280         dec->priv->base_ts = seg.start;
2281         dec->priv->samples = 0;
2282       }
2283
2284       /* and follow along with segment */
2285       dec->priv->in_out_segment_sync = FALSE;
2286       dec->input_segment = seg;
2287       dec->priv->pending_events =
2288           g_list_append (dec->priv->pending_events, event);
2289       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2290
2291       ret = TRUE;
2292       break;
2293     }
2294     case GST_EVENT_GAP:
2295       ret = gst_audio_decoder_handle_gap (dec, event);
2296       break;
2297     case GST_EVENT_FLUSH_STOP:
2298       GST_AUDIO_DECODER_STREAM_LOCK (dec);
2299       /* prepare for fresh start */
2300       gst_audio_decoder_flush (dec, TRUE);
2301
2302       dec->priv->pending_events = _flush_events (dec->srcpad,
2303           dec->priv->pending_events);
2304       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2305
2306       /* Forward FLUSH_STOP, it is expected to be forwarded immediately
2307        * and no buffers are queued anyway. */
2308       ret = gst_audio_decoder_push_event (dec, event);
2309       break;
2310
2311     case GST_EVENT_SEGMENT_DONE:
2312       GST_AUDIO_DECODER_STREAM_LOCK (dec);
2313       gst_audio_decoder_drain (dec);
2314       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2315
2316       /* Forward SEGMENT_DONE because no buffer or serialized event might come after
2317        * SEGMENT_DONE and nothing could trigger another _finish_frame() call. */
2318       if (dec->priv->pending_events)
2319         send_pending_events (dec);
2320       ret = gst_audio_decoder_push_event (dec, event);
2321       break;
2322
2323     case GST_EVENT_EOS:
2324       GST_AUDIO_DECODER_STREAM_LOCK (dec);
2325       gst_audio_decoder_drain (dec);
2326       GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2327
2328       if (dec->priv->ctx.had_input_data && !dec->priv->ctx.had_output_data) {
2329         GST_ELEMENT_ERROR (dec, STREAM, DECODE,
2330             ("No valid frames decoded before end of stream"),
2331             ("no valid frames found"));
2332       }
2333
2334       /* Forward EOS because no buffer or serialized event will come after
2335        * EOS and nothing could trigger another _finish_frame() call. */
2336       if (dec->priv->pending_events)
2337         send_pending_events (dec);
2338       ret = gst_audio_decoder_push_event (dec, event);
2339       break;
2340
2341     case GST_EVENT_CAPS:
2342     {
2343       GstCaps *caps;
2344
2345       gst_event_parse_caps (event, &caps);
2346       ret = gst_audio_decoder_sink_setcaps (dec, caps);
2347       gst_event_unref (event);
2348       break;
2349     }
2350     case GST_EVENT_TAG:
2351     {
2352       GstTagList *tags;
2353
2354       gst_event_parse_tag (event, &tags);
2355
2356       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
2357         GST_AUDIO_DECODER_STREAM_LOCK (dec);
2358         if (dec->priv->upstream_tags != tags) {
2359           if (dec->priv->upstream_tags)
2360             gst_tag_list_unref (dec->priv->upstream_tags);
2361           dec->priv->upstream_tags = gst_tag_list_ref (tags);
2362           GST_INFO_OBJECT (dec, "upstream stream tags: %" GST_PTR_FORMAT, tags);
2363         }
2364         gst_event_unref (event);
2365         event = gst_audio_decoder_create_merged_tags_event (dec);
2366         dec->priv->taglist_changed = FALSE;
2367         GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2368
2369         /* No tags, go out of here instead of fall through */
2370         if (!event) {
2371           ret = TRUE;
2372           break;
2373         }
2374       }
2375
2376       /* fall through */
2377     }
2378     default:
2379       if (!GST_EVENT_IS_SERIALIZED (event)) {
2380         ret =
2381             gst_pad_event_default (dec->sinkpad, GST_OBJECT_CAST (dec), event);
2382       } else {
2383         GST_DEBUG_OBJECT (dec, "Enqueuing event %d, %s", GST_EVENT_TYPE (event),
2384             GST_EVENT_TYPE_NAME (event));
2385         GST_AUDIO_DECODER_STREAM_LOCK (dec);
2386         dec->priv->pending_events =
2387             g_list_append (dec->priv->pending_events, event);
2388         GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
2389         ret = TRUE;
2390       }
2391       break;
2392   }
2393   return ret;
2394 }
2395
2396 static gboolean
2397 gst_audio_decoder_sink_event (GstPad * pad, GstObject * parent,
2398     GstEvent * event)
2399 {
2400   GstAudioDecoder *dec;
2401   GstAudioDecoderClass *klass;
2402   gboolean ret;
2403
2404   dec = GST_AUDIO_DECODER (parent);
2405   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2406
2407   GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event),
2408       GST_EVENT_TYPE_NAME (event));
2409
2410   if (klass->sink_event)
2411     ret = klass->sink_event (dec, event);
2412   else {
2413     gst_event_unref (event);
2414     ret = FALSE;
2415   }
2416   return ret;
2417 }
2418
2419 static gboolean
2420 gst_audio_decoder_do_seek (GstAudioDecoder * dec, GstEvent * event)
2421 {
2422   GstSeekFlags flags;
2423   GstSeekType start_type, end_type;
2424   GstFormat format;
2425   gdouble rate;
2426   gint64 start, start_time, end_time;
2427   GstSegment seek_segment;
2428   guint32 seqnum;
2429
2430   gst_event_parse_seek (event, &rate, &format, &flags, &start_type,
2431       &start_time, &end_type, &end_time);
2432
2433   /* we'll handle plain open-ended flushing seeks with the simple approach */
2434   if (rate != 1.0) {
2435     GST_DEBUG_OBJECT (dec, "unsupported seek: rate");
2436     return FALSE;
2437   }
2438
2439   if (start_type != GST_SEEK_TYPE_SET) {
2440     GST_DEBUG_OBJECT (dec, "unsupported seek: start time");
2441     return FALSE;
2442   }
2443
2444   if ((end_type != GST_SEEK_TYPE_SET && end_type != GST_SEEK_TYPE_NONE) ||
2445       (end_type == GST_SEEK_TYPE_SET && end_time != GST_CLOCK_TIME_NONE)) {
2446     GST_DEBUG_OBJECT (dec, "unsupported seek: end time");
2447     return FALSE;
2448   }
2449
2450   if (!(flags & GST_SEEK_FLAG_FLUSH)) {
2451     GST_DEBUG_OBJECT (dec, "unsupported seek: not flushing");
2452     return FALSE;
2453   }
2454
2455   memcpy (&seek_segment, &dec->output_segment, sizeof (seek_segment));
2456   gst_segment_do_seek (&seek_segment, rate, format, flags, start_type,
2457       start_time, end_type, end_time, NULL);
2458   start_time = seek_segment.position;
2459
2460   if (!gst_pad_query_convert (dec->sinkpad, GST_FORMAT_TIME, start_time,
2461           GST_FORMAT_BYTES, &start)) {
2462     GST_DEBUG_OBJECT (dec, "conversion failed");
2463     return FALSE;
2464   }
2465
2466   seqnum = gst_event_get_seqnum (event);
2467   event = gst_event_new_seek (1.0, GST_FORMAT_BYTES, flags,
2468       GST_SEEK_TYPE_SET, start, GST_SEEK_TYPE_NONE, -1);
2469   gst_event_set_seqnum (event, seqnum);
2470
2471   GST_DEBUG_OBJECT (dec, "seeking to %" GST_TIME_FORMAT " at byte offset %"
2472       G_GINT64_FORMAT, GST_TIME_ARGS (start_time), start);
2473
2474   return gst_pad_push_event (dec->sinkpad, event);
2475 }
2476
2477 static gboolean
2478 gst_audio_decoder_src_eventfunc (GstAudioDecoder * dec, GstEvent * event)
2479 {
2480   gboolean res;
2481
2482   switch (GST_EVENT_TYPE (event)) {
2483     case GST_EVENT_SEEK:
2484     {
2485       GstFormat format;
2486       gdouble rate;
2487       GstSeekFlags flags;
2488       GstSeekType start_type, stop_type;
2489       gint64 start, stop;
2490       gint64 tstart, tstop;
2491       guint32 seqnum;
2492
2493       gst_event_parse_seek (event, &rate, &format, &flags, &start_type, &start,
2494           &stop_type, &stop);
2495       seqnum = gst_event_get_seqnum (event);
2496
2497       /* upstream gets a chance first */
2498       if ((res = gst_pad_push_event (dec->sinkpad, event)))
2499         break;
2500
2501       /* if upstream fails for a time seek, maybe we can help if allowed */
2502       if (format == GST_FORMAT_TIME) {
2503         if (gst_audio_decoder_do_byte (dec))
2504           res = gst_audio_decoder_do_seek (dec, event);
2505         break;
2506       }
2507
2508       /* ... though a non-time seek can be aided as well */
2509       /* First bring the requested format to time */
2510       if (!(res =
2511               gst_pad_query_convert (dec->srcpad, format, start,
2512                   GST_FORMAT_TIME, &tstart)))
2513         goto convert_error;
2514       if (!(res =
2515               gst_pad_query_convert (dec->srcpad, format, stop, GST_FORMAT_TIME,
2516                   &tstop)))
2517         goto convert_error;
2518
2519       /* then seek with time on the peer */
2520       event = gst_event_new_seek (rate, GST_FORMAT_TIME,
2521           flags, start_type, tstart, stop_type, tstop);
2522       gst_event_set_seqnum (event, seqnum);
2523
2524       res = gst_pad_push_event (dec->sinkpad, event);
2525       break;
2526     }
2527     default:
2528       res = gst_pad_event_default (dec->srcpad, GST_OBJECT_CAST (dec), event);
2529       break;
2530   }
2531 done:
2532   return res;
2533
2534   /* ERRORS */
2535 convert_error:
2536   {
2537     GST_DEBUG_OBJECT (dec, "cannot convert start/stop for seek");
2538     goto done;
2539   }
2540 }
2541
2542 static gboolean
2543 gst_audio_decoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
2544 {
2545   GstAudioDecoder *dec;
2546   GstAudioDecoderClass *klass;
2547   gboolean ret;
2548
2549   dec = GST_AUDIO_DECODER (parent);
2550   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2551
2552   GST_DEBUG_OBJECT (dec, "received event %d, %s", GST_EVENT_TYPE (event),
2553       GST_EVENT_TYPE_NAME (event));
2554
2555   if (klass->src_event)
2556     ret = klass->src_event (dec, event);
2557   else {
2558     gst_event_unref (event);
2559     ret = FALSE;
2560   }
2561
2562   return ret;
2563 }
2564
2565 static gboolean
2566 gst_audio_decoder_decide_allocation_default (GstAudioDecoder * dec,
2567     GstQuery * query)
2568 {
2569   GstAllocator *allocator = NULL;
2570   GstAllocationParams params;
2571   gboolean update_allocator;
2572
2573   /* we got configuration from our peer or the decide_allocation method,
2574    * parse them */
2575   if (gst_query_get_n_allocation_params (query) > 0) {
2576     /* try the allocator */
2577     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2578     update_allocator = TRUE;
2579   } else {
2580     allocator = NULL;
2581     gst_allocation_params_init (&params);
2582     update_allocator = FALSE;
2583   }
2584
2585   if (update_allocator)
2586     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
2587   else
2588     gst_query_add_allocation_param (query, allocator, &params);
2589   if (allocator)
2590     gst_object_unref (allocator);
2591
2592   return TRUE;
2593 }
2594
2595 static gboolean
2596 gst_audio_decoder_propose_allocation_default (GstAudioDecoder * dec,
2597     GstQuery * query)
2598 {
2599   return TRUE;
2600 }
2601
2602 /**
2603  * gst_audio_decoder_proxy_getcaps:
2604  * @decoder: a #GstAudioDecoder
2605  * @caps: (allow-none): initial caps
2606  * @filter: (allow-none): filter caps
2607  *
2608  * Returns caps that express @caps (or sink template caps if @caps == NULL)
2609  * restricted to rate/channels/... combinations supported by downstream
2610  * elements.
2611  *
2612  * Returns: (transfer full): a #GstCaps owned by caller
2613  *
2614  * Since: 1.6
2615  */
2616 GstCaps *
2617 gst_audio_decoder_proxy_getcaps (GstAudioDecoder * decoder, GstCaps * caps,
2618     GstCaps * filter)
2619 {
2620   return __gst_audio_element_proxy_getcaps (GST_ELEMENT_CAST (decoder),
2621       GST_AUDIO_DECODER_SINK_PAD (decoder),
2622       GST_AUDIO_DECODER_SRC_PAD (decoder), caps, filter);
2623 }
2624
2625 static GstCaps *
2626 gst_audio_decoder_sink_getcaps (GstAudioDecoder * decoder, GstCaps * filter)
2627 {
2628   GstAudioDecoderClass *klass;
2629   GstCaps *caps;
2630
2631   klass = GST_AUDIO_DECODER_GET_CLASS (decoder);
2632
2633   if (klass->getcaps)
2634     caps = klass->getcaps (decoder, filter);
2635   else
2636     caps = gst_audio_decoder_proxy_getcaps (decoder, NULL, filter);
2637
2638   GST_LOG_OBJECT (decoder, "Returning caps %" GST_PTR_FORMAT, caps);
2639
2640   return caps;
2641 }
2642
2643 static gboolean
2644 gst_audio_decoder_sink_query_default (GstAudioDecoder * dec, GstQuery * query)
2645 {
2646   GstPad *pad = GST_AUDIO_DECODER_SINK_PAD (dec);
2647   gboolean res = FALSE;
2648
2649   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
2650
2651   switch (GST_QUERY_TYPE (query)) {
2652     case GST_QUERY_FORMATS:
2653     {
2654       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
2655       res = TRUE;
2656       break;
2657     }
2658     case GST_QUERY_CONVERT:
2659     {
2660       GstFormat src_fmt, dest_fmt;
2661       gint64 src_val, dest_val;
2662
2663       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
2664       GST_OBJECT_LOCK (dec);
2665       res = __gst_audio_encoded_audio_convert (&dec->priv->ctx.info,
2666           dec->priv->bytes_in, dec->priv->samples_out,
2667           src_fmt, src_val, &dest_fmt, &dest_val);
2668       GST_OBJECT_UNLOCK (dec);
2669       if (!res)
2670         goto error;
2671       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
2672       break;
2673     }
2674     case GST_QUERY_ALLOCATION:
2675     {
2676       GstAudioDecoderClass *klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2677
2678       if (klass->propose_allocation)
2679         res = klass->propose_allocation (dec, query);
2680       break;
2681     }
2682     case GST_QUERY_CAPS:{
2683       GstCaps *filter, *caps;
2684
2685       gst_query_parse_caps (query, &filter);
2686       caps = gst_audio_decoder_sink_getcaps (dec, filter);
2687       gst_query_set_caps_result (query, caps);
2688       gst_caps_unref (caps);
2689       res = TRUE;
2690       break;
2691     }
2692     case GST_QUERY_ACCEPT_CAPS:{
2693       if (dec->priv->use_default_pad_acceptcaps) {
2694         res =
2695             gst_pad_query_default (GST_AUDIO_DECODER_SINK_PAD (dec),
2696             GST_OBJECT_CAST (dec), query);
2697       } else {
2698         GstCaps *caps;
2699         GstCaps *allowed_caps;
2700         GstCaps *template_caps;
2701         gboolean accept;
2702
2703         gst_query_parse_accept_caps (query, &caps);
2704
2705         template_caps = gst_pad_get_pad_template_caps (pad);
2706         accept = gst_caps_is_subset (caps, template_caps);
2707         gst_caps_unref (template_caps);
2708
2709         if (accept) {
2710           allowed_caps = gst_pad_query_caps (GST_AUDIO_DECODER_SINK_PAD (dec),
2711               caps);
2712
2713           accept = gst_caps_can_intersect (caps, allowed_caps);
2714
2715           gst_caps_unref (allowed_caps);
2716         }
2717
2718         gst_query_set_accept_caps_result (query, accept);
2719         res = TRUE;
2720       }
2721       break;
2722     }
2723     case GST_QUERY_SEEKING:
2724     {
2725       GstFormat format;
2726
2727       /* non-TIME segments are discarded, so we won't seek that way either */
2728       gst_query_parse_seeking (query, &format, NULL, NULL, NULL);
2729       if (format != GST_FORMAT_TIME) {
2730         GST_DEBUG_OBJECT (dec, "discarding non-TIME SEEKING query");
2731         res = FALSE;
2732         break;
2733       }
2734       /* fall-through */
2735     }
2736     default:
2737       res = gst_pad_query_default (pad, GST_OBJECT_CAST (dec), query);
2738       break;
2739   }
2740
2741 error:
2742   return res;
2743 }
2744
2745 static gboolean
2746 gst_audio_decoder_sink_query (GstPad * pad, GstObject * parent,
2747     GstQuery * query)
2748 {
2749   GstAudioDecoderClass *dec_class;
2750   GstAudioDecoder *dec;
2751   gboolean ret = FALSE;
2752
2753   dec = GST_AUDIO_DECODER (parent);
2754   dec_class = GST_AUDIO_DECODER_GET_CLASS (dec);
2755
2756   GST_DEBUG_OBJECT (pad, "received query %" GST_PTR_FORMAT, query);
2757
2758   if (dec_class->sink_query)
2759     ret = dec_class->sink_query (dec, query);
2760
2761   return ret;
2762 }
2763
2764 /* FIXME ? are any of these queries (other than latency) a decoder's business ??
2765  * also, the conversion stuff might seem to make sense, but seems to not mind
2766  * segment stuff etc at all
2767  * Supposedly that's backward compatibility ... */
2768 static gboolean
2769 gst_audio_decoder_src_query_default (GstAudioDecoder * dec, GstQuery * query)
2770 {
2771   GstPad *pad = GST_AUDIO_DECODER_SRC_PAD (dec);
2772   gboolean res = FALSE;
2773
2774   GST_LOG_OBJECT (dec, "handling query: %" GST_PTR_FORMAT, query);
2775
2776   switch (GST_QUERY_TYPE (query)) {
2777     case GST_QUERY_DURATION:
2778     {
2779       GstFormat format;
2780
2781       /* upstream in any case */
2782       if ((res = gst_pad_query_default (pad, GST_OBJECT_CAST (dec), query)))
2783         break;
2784
2785       gst_query_parse_duration (query, &format, NULL);
2786       /* try answering TIME by converting from BYTE if subclass allows  */
2787       if (format == GST_FORMAT_TIME && gst_audio_decoder_do_byte (dec)) {
2788         gint64 value;
2789
2790         if (gst_pad_peer_query_duration (dec->sinkpad, GST_FORMAT_BYTES,
2791                 &value)) {
2792           GST_LOG_OBJECT (dec, "upstream size %" G_GINT64_FORMAT, value);
2793           if (gst_pad_query_convert (dec->sinkpad, GST_FORMAT_BYTES, value,
2794                   GST_FORMAT_TIME, &value)) {
2795             gst_query_set_duration (query, GST_FORMAT_TIME, value);
2796             res = TRUE;
2797           }
2798         }
2799       }
2800       break;
2801     }
2802     case GST_QUERY_POSITION:
2803     {
2804       GstFormat format;
2805       gint64 time, value;
2806
2807       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
2808         GST_LOG_OBJECT (dec, "returning peer response");
2809         break;
2810       }
2811
2812       /* Refuse BYTES format queries. If it made sense to
2813        * answer them, upstream would have already */
2814       gst_query_parse_position (query, &format, NULL);
2815
2816       if (format == GST_FORMAT_BYTES) {
2817         GST_LOG_OBJECT (dec, "Ignoring BYTES position query");
2818         break;
2819       }
2820
2821       /* we start from the last seen time */
2822       time = dec->output_segment.position;
2823       /* correct for the segment values */
2824       time =
2825           gst_segment_to_stream_time (&dec->output_segment, GST_FORMAT_TIME,
2826           time);
2827
2828       GST_LOG_OBJECT (dec,
2829           "query %p: our time: %" GST_TIME_FORMAT, query, GST_TIME_ARGS (time));
2830
2831       /* and convert to the final format */
2832       if (!(res = gst_pad_query_convert (pad, GST_FORMAT_TIME, time,
2833                   format, &value)))
2834         break;
2835
2836       gst_query_set_position (query, format, value);
2837
2838       GST_LOG_OBJECT (dec,
2839           "query %p: we return %" G_GINT64_FORMAT " (format %u)", query, value,
2840           format);
2841       break;
2842     }
2843     case GST_QUERY_FORMATS:
2844     {
2845       gst_query_set_formats (query, 3,
2846           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
2847       res = TRUE;
2848       break;
2849     }
2850     case GST_QUERY_CONVERT:
2851     {
2852       GstFormat src_fmt, dest_fmt;
2853       gint64 src_val, dest_val;
2854
2855       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
2856       GST_OBJECT_LOCK (dec);
2857       res = gst_audio_info_convert (&dec->priv->ctx.info,
2858           src_fmt, src_val, dest_fmt, &dest_val);
2859       GST_OBJECT_UNLOCK (dec);
2860       if (!res)
2861         break;
2862       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
2863       break;
2864     }
2865     case GST_QUERY_LATENCY:
2866     {
2867       if ((res = gst_pad_peer_query (dec->sinkpad, query))) {
2868         gboolean live;
2869         GstClockTime min_latency, max_latency;
2870
2871         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
2872         GST_DEBUG_OBJECT (dec, "Peer latency: live %d, min %"
2873             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
2874             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2875
2876         GST_OBJECT_LOCK (dec);
2877         /* add our latency */
2878         min_latency += dec->priv->ctx.min_latency;
2879         if (max_latency == -1 || dec->priv->ctx.max_latency == -1)
2880           max_latency = -1;
2881         else
2882           max_latency += dec->priv->ctx.max_latency;
2883         GST_OBJECT_UNLOCK (dec);
2884
2885         gst_query_set_latency (query, live, min_latency, max_latency);
2886       }
2887       break;
2888     }
2889     default:
2890       res = gst_pad_query_default (pad, GST_OBJECT_CAST (dec), query);
2891       break;
2892   }
2893
2894   return res;
2895 }
2896
2897 static gboolean
2898 gst_audio_decoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2899 {
2900   GstAudioDecoder *dec;
2901   GstAudioDecoderClass *dec_class;
2902   gboolean ret = FALSE;
2903
2904   dec = GST_AUDIO_DECODER (parent);
2905   dec_class = GST_AUDIO_DECODER_GET_CLASS (dec);
2906
2907   GST_DEBUG_OBJECT (pad, "received query %" GST_PTR_FORMAT, query);
2908
2909   if (dec_class->src_query)
2910     ret = dec_class->src_query (dec, query);
2911
2912   return ret;
2913 }
2914
2915 static gboolean
2916 gst_audio_decoder_stop (GstAudioDecoder * dec)
2917 {
2918   GstAudioDecoderClass *klass;
2919   gboolean ret = TRUE;
2920
2921   GST_DEBUG_OBJECT (dec, "gst_audio_decoder_stop");
2922
2923   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2924
2925   if (klass->stop) {
2926     ret = klass->stop (dec);
2927   }
2928
2929   /* clean up */
2930   gst_audio_decoder_reset (dec, TRUE);
2931
2932   if (ret)
2933     dec->priv->active = FALSE;
2934
2935   return ret;
2936 }
2937
2938 static gboolean
2939 gst_audio_decoder_start (GstAudioDecoder * dec)
2940 {
2941   GstAudioDecoderClass *klass;
2942   gboolean ret = TRUE;
2943
2944   GST_DEBUG_OBJECT (dec, "gst_audio_decoder_start");
2945
2946   klass = GST_AUDIO_DECODER_GET_CLASS (dec);
2947
2948   /* arrange clean state */
2949   gst_audio_decoder_reset (dec, TRUE);
2950
2951   if (klass->start) {
2952     ret = klass->start (dec);
2953   }
2954
2955   if (ret)
2956     dec->priv->active = TRUE;
2957
2958   return ret;
2959 }
2960
2961 static void
2962 gst_audio_decoder_get_property (GObject * object, guint prop_id,
2963     GValue * value, GParamSpec * pspec)
2964 {
2965   GstAudioDecoder *dec;
2966
2967   dec = GST_AUDIO_DECODER (object);
2968
2969   switch (prop_id) {
2970     case PROP_LATENCY:
2971       g_value_set_int64 (value, dec->priv->latency);
2972       break;
2973     case PROP_TOLERANCE:
2974       g_value_set_int64 (value, dec->priv->tolerance);
2975       break;
2976     case PROP_PLC:
2977       g_value_set_boolean (value, dec->priv->plc);
2978       break;
2979     default:
2980       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2981       break;
2982   }
2983 }
2984
2985 static void
2986 gst_audio_decoder_set_property (GObject * object, guint prop_id,
2987     const GValue * value, GParamSpec * pspec)
2988 {
2989   GstAudioDecoder *dec;
2990
2991   dec = GST_AUDIO_DECODER (object);
2992
2993   switch (prop_id) {
2994     case PROP_LATENCY:
2995       dec->priv->latency = g_value_get_int64 (value);
2996       break;
2997     case PROP_TOLERANCE:
2998       dec->priv->tolerance = g_value_get_int64 (value);
2999       break;
3000     case PROP_PLC:
3001       dec->priv->plc = g_value_get_boolean (value);
3002       break;
3003     default:
3004       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
3005       break;
3006   }
3007 }
3008
3009 static GstStateChangeReturn
3010 gst_audio_decoder_change_state (GstElement * element, GstStateChange transition)
3011 {
3012   GstAudioDecoder *codec;
3013   GstAudioDecoderClass *klass;
3014   GstStateChangeReturn ret;
3015
3016   codec = GST_AUDIO_DECODER (element);
3017   klass = GST_AUDIO_DECODER_GET_CLASS (codec);
3018
3019   switch (transition) {
3020     case GST_STATE_CHANGE_NULL_TO_READY:
3021       if (klass->open) {
3022         if (!klass->open (codec))
3023           goto open_failed;
3024       }
3025       break;
3026     case GST_STATE_CHANGE_READY_TO_PAUSED:
3027       if (!gst_audio_decoder_start (codec)) {
3028         goto start_failed;
3029       }
3030       break;
3031     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
3032       break;
3033     default:
3034       break;
3035   }
3036
3037   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
3038
3039   switch (transition) {
3040     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
3041       break;
3042     case GST_STATE_CHANGE_PAUSED_TO_READY:
3043       if (!gst_audio_decoder_stop (codec)) {
3044         goto stop_failed;
3045       }
3046       break;
3047     case GST_STATE_CHANGE_READY_TO_NULL:
3048       if (klass->close) {
3049         if (!klass->close (codec))
3050           goto close_failed;
3051       }
3052       break;
3053     default:
3054       break;
3055   }
3056
3057   return ret;
3058
3059 start_failed:
3060   {
3061     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to start codec"));
3062     return GST_STATE_CHANGE_FAILURE;
3063   }
3064 stop_failed:
3065   {
3066     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to stop codec"));
3067     return GST_STATE_CHANGE_FAILURE;
3068   }
3069 open_failed:
3070   {
3071     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to open codec"));
3072     return GST_STATE_CHANGE_FAILURE;
3073   }
3074 close_failed:
3075   {
3076     GST_ELEMENT_ERROR (codec, LIBRARY, INIT, (NULL), ("Failed to close codec"));
3077     return GST_STATE_CHANGE_FAILURE;
3078   }
3079 }
3080
3081 GstFlowReturn
3082 _gst_audio_decoder_error (GstAudioDecoder * dec, gint weight,
3083     GQuark domain, gint code, gchar * txt, gchar * dbg, const gchar * file,
3084     const gchar * function, gint line)
3085 {
3086   if (txt)
3087     GST_WARNING_OBJECT (dec, "error: %s", txt);
3088   if (dbg)
3089     GST_WARNING_OBJECT (dec, "error: %s", dbg);
3090   dec->priv->error_count += weight;
3091   dec->priv->discont = TRUE;
3092   if (dec->priv->ctx.max_errors >= 0
3093       && dec->priv->ctx.max_errors < dec->priv->error_count) {
3094     gst_element_message_full (GST_ELEMENT (dec), GST_MESSAGE_ERROR, domain,
3095         code, txt, dbg, file, function, line);
3096     return GST_FLOW_ERROR;
3097   } else {
3098     g_free (txt);
3099     g_free (dbg);
3100     return GST_FLOW_OK;
3101   }
3102 }
3103
3104 /**
3105  * gst_audio_decoder_get_audio_info:
3106  * @dec: a #GstAudioDecoder
3107  *
3108  * Returns: a #GstAudioInfo describing the input audio format
3109  */
3110 GstAudioInfo *
3111 gst_audio_decoder_get_audio_info (GstAudioDecoder * dec)
3112 {
3113   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), NULL);
3114
3115   return &dec->priv->ctx.info;
3116 }
3117
3118 /**
3119  * gst_audio_decoder_set_plc_aware:
3120  * @dec: a #GstAudioDecoder
3121  * @plc: new plc state
3122  *
3123  * Indicates whether or not subclass handles packet loss concealment (plc).
3124  */
3125 void
3126 gst_audio_decoder_set_plc_aware (GstAudioDecoder * dec, gboolean plc)
3127 {
3128   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3129
3130   dec->priv->ctx.do_plc = plc;
3131 }
3132
3133 /**
3134  * gst_audio_decoder_get_plc_aware:
3135  * @dec: a #GstAudioDecoder
3136  *
3137  * Returns: currently configured plc handling
3138  */
3139 gint
3140 gst_audio_decoder_get_plc_aware (GstAudioDecoder * dec)
3141 {
3142   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3143
3144   return dec->priv->ctx.do_plc;
3145 }
3146
3147 /**
3148  * gst_audio_decoder_set_estimate_rate:
3149  * @dec: a #GstAudioDecoder
3150  * @enabled: whether to enable byte to time conversion
3151  *
3152  * Allows baseclass to perform byte to time estimated conversion.
3153  */
3154 void
3155 gst_audio_decoder_set_estimate_rate (GstAudioDecoder * dec, gboolean enabled)
3156 {
3157   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3158
3159   dec->priv->ctx.do_estimate_rate = enabled;
3160 }
3161
3162 /**
3163  * gst_audio_decoder_get_estimate_rate:
3164  * @dec: a #GstAudioDecoder
3165  *
3166  * Returns: currently configured byte to time conversion setting
3167  */
3168 gint
3169 gst_audio_decoder_get_estimate_rate (GstAudioDecoder * dec)
3170 {
3171   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3172
3173   return dec->priv->ctx.do_estimate_rate;
3174 }
3175
3176 /**
3177  * gst_audio_decoder_get_delay:
3178  * @dec: a #GstAudioDecoder
3179  *
3180  * Returns: currently configured decoder delay
3181  */
3182 gint
3183 gst_audio_decoder_get_delay (GstAudioDecoder * dec)
3184 {
3185   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3186
3187   return dec->priv->ctx.delay;
3188 }
3189
3190 /**
3191  * gst_audio_decoder_set_max_errors:
3192  * @dec: a #GstAudioDecoder
3193  * @num: max tolerated errors
3194  *
3195  * Sets numbers of tolerated decoder errors, where a tolerated one is then only
3196  * warned about, but more than tolerated will lead to fatal error. You can set
3197  * -1 for never returning fatal errors. Default is set to
3198  * GST_AUDIO_DECODER_MAX_ERRORS.
3199  */
3200 void
3201 gst_audio_decoder_set_max_errors (GstAudioDecoder * dec, gint num)
3202 {
3203   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3204
3205   dec->priv->ctx.max_errors = num;
3206 }
3207
3208 /**
3209  * gst_audio_decoder_get_max_errors:
3210  * @dec: a #GstAudioDecoder
3211  *
3212  * Returns: currently configured decoder tolerated error count.
3213  */
3214 gint
3215 gst_audio_decoder_get_max_errors (GstAudioDecoder * dec)
3216 {
3217   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3218
3219   return dec->priv->ctx.max_errors;
3220 }
3221
3222 /**
3223  * gst_audio_decoder_set_latency:
3224  * @dec: a #GstAudioDecoder
3225  * @min: minimum latency
3226  * @max: maximum latency
3227  *
3228  * Sets decoder latency.
3229  */
3230 void
3231 gst_audio_decoder_set_latency (GstAudioDecoder * dec,
3232     GstClockTime min, GstClockTime max)
3233 {
3234   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3235   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min));
3236   g_return_if_fail (min <= max);
3237
3238   GST_OBJECT_LOCK (dec);
3239   dec->priv->ctx.min_latency = min;
3240   dec->priv->ctx.max_latency = max;
3241   GST_OBJECT_UNLOCK (dec);
3242
3243   /* post latency message on the bus */
3244   gst_element_post_message (GST_ELEMENT (dec),
3245       gst_message_new_latency (GST_OBJECT (dec)));
3246 }
3247
3248 /**
3249  * gst_audio_decoder_get_latency:
3250  * @dec: a #GstAudioDecoder
3251  * @min: (out) (allow-none): a pointer to storage to hold minimum latency
3252  * @max: (out) (allow-none): a pointer to storage to hold maximum latency
3253  *
3254  * Sets the variables pointed to by @min and @max to the currently configured
3255  * latency.
3256  */
3257 void
3258 gst_audio_decoder_get_latency (GstAudioDecoder * dec,
3259     GstClockTime * min, GstClockTime * max)
3260 {
3261   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3262
3263   GST_OBJECT_LOCK (dec);
3264   if (min)
3265     *min = dec->priv->ctx.min_latency;
3266   if (max)
3267     *max = dec->priv->ctx.max_latency;
3268   GST_OBJECT_UNLOCK (dec);
3269 }
3270
3271 /**
3272  * gst_audio_decoder_get_parse_state:
3273  * @dec: a #GstAudioDecoder
3274  * @sync: (out) (optional): a pointer to a variable to hold the current sync state
3275  * @eos: (out) (optional): a pointer to a variable to hold the current eos state
3276  *
3277  * Return current parsing (sync and eos) state.
3278  */
3279 void
3280 gst_audio_decoder_get_parse_state (GstAudioDecoder * dec,
3281     gboolean * sync, gboolean * eos)
3282 {
3283   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3284
3285   if (sync)
3286     *sync = dec->priv->ctx.sync;
3287   if (eos)
3288     *eos = dec->priv->ctx.eos;
3289 }
3290
3291 /**
3292  * gst_audio_decoder_set_allocation_caps:
3293  * @dec: a #GstAudioDecoder
3294  * @allocation_caps: (allow-none): a #GstCaps or %NULL
3295  *
3296  * Sets a caps in allocation query which are different from the set
3297  * pad's caps. Use this function before calling
3298  * gst_audio_decoder_negotiate(). Setting to %NULL the allocation
3299  * query will use the caps from the pad.
3300  *
3301  * Since: 1.10
3302  */
3303 void
3304 gst_audio_decoder_set_allocation_caps (GstAudioDecoder * dec,
3305     GstCaps * allocation_caps)
3306 {
3307   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3308
3309   gst_caps_replace (&dec->priv->ctx.allocation_caps, allocation_caps);
3310 }
3311
3312 /**
3313  * gst_audio_decoder_set_plc:
3314  * @dec: a #GstAudioDecoder
3315  * @enabled: new state
3316  *
3317  * Enable or disable decoder packet loss concealment, provided subclass
3318  * and codec are capable and allow handling plc.
3319  *
3320  * MT safe.
3321  */
3322 void
3323 gst_audio_decoder_set_plc (GstAudioDecoder * dec, gboolean enabled)
3324 {
3325   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3326
3327   GST_LOG_OBJECT (dec, "enabled: %d", enabled);
3328
3329   GST_OBJECT_LOCK (dec);
3330   dec->priv->plc = enabled;
3331   GST_OBJECT_UNLOCK (dec);
3332 }
3333
3334 /**
3335  * gst_audio_decoder_get_plc:
3336  * @dec: a #GstAudioDecoder
3337  *
3338  * Queries decoder packet loss concealment handling.
3339  *
3340  * Returns: TRUE if packet loss concealment is enabled.
3341  *
3342  * MT safe.
3343  */
3344 gboolean
3345 gst_audio_decoder_get_plc (GstAudioDecoder * dec)
3346 {
3347   gboolean result;
3348
3349   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
3350
3351   GST_OBJECT_LOCK (dec);
3352   result = dec->priv->plc;
3353   GST_OBJECT_UNLOCK (dec);
3354
3355   return result;
3356 }
3357
3358 /**
3359  * gst_audio_decoder_set_min_latency:
3360  * @dec: a #GstAudioDecoder
3361  * @num: new minimum latency
3362  *
3363  * Sets decoder minimum aggregation latency.
3364  *
3365  * MT safe.
3366  */
3367 void
3368 gst_audio_decoder_set_min_latency (GstAudioDecoder * dec, GstClockTime num)
3369 {
3370   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3371
3372   GST_OBJECT_LOCK (dec);
3373   dec->priv->latency = num;
3374   GST_OBJECT_UNLOCK (dec);
3375 }
3376
3377 /**
3378  * gst_audio_decoder_get_min_latency:
3379  * @dec: a #GstAudioDecoder
3380  *
3381  * Queries decoder's latency aggregation.
3382  *
3383  * Returns: aggregation latency.
3384  *
3385  * MT safe.
3386  */
3387 GstClockTime
3388 gst_audio_decoder_get_min_latency (GstAudioDecoder * dec)
3389 {
3390   GstClockTime result;
3391
3392   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
3393
3394   GST_OBJECT_LOCK (dec);
3395   result = dec->priv->latency;
3396   GST_OBJECT_UNLOCK (dec);
3397
3398   return result;
3399 }
3400
3401 /**
3402  * gst_audio_decoder_set_tolerance:
3403  * @dec: a #GstAudioDecoder
3404  * @tolerance: new tolerance
3405  *
3406  * Configures decoder audio jitter tolerance threshold.
3407  *
3408  * MT safe.
3409  */
3410 void
3411 gst_audio_decoder_set_tolerance (GstAudioDecoder * dec, GstClockTime tolerance)
3412 {
3413   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3414
3415   GST_OBJECT_LOCK (dec);
3416   dec->priv->tolerance = tolerance;
3417   GST_OBJECT_UNLOCK (dec);
3418 }
3419
3420 /**
3421  * gst_audio_decoder_get_tolerance:
3422  * @dec: a #GstAudioDecoder
3423  *
3424  * Queries current audio jitter tolerance threshold.
3425  *
3426  * Returns: decoder audio jitter tolerance threshold.
3427  *
3428  * MT safe.
3429  */
3430 GstClockTime
3431 gst_audio_decoder_get_tolerance (GstAudioDecoder * dec)
3432 {
3433   GstClockTime result;
3434
3435   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3436
3437   GST_OBJECT_LOCK (dec);
3438   result = dec->priv->tolerance;
3439   GST_OBJECT_UNLOCK (dec);
3440
3441   return result;
3442 }
3443
3444 /**
3445  * gst_audio_decoder_set_drainable:
3446  * @dec: a #GstAudioDecoder
3447  * @enabled: new state
3448  *
3449  * Configures decoder drain handling.  If drainable, subclass might
3450  * be handed a NULL buffer to have it return any leftover decoded data.
3451  * Otherwise, it is not considered so capable and will only ever be passed
3452  * real data.
3453  *
3454  * MT safe.
3455  */
3456 void
3457 gst_audio_decoder_set_drainable (GstAudioDecoder * dec, gboolean enabled)
3458 {
3459   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3460
3461   GST_OBJECT_LOCK (dec);
3462   dec->priv->drainable = enabled;
3463   GST_OBJECT_UNLOCK (dec);
3464 }
3465
3466 /**
3467  * gst_audio_decoder_get_drainable:
3468  * @dec: a #GstAudioDecoder
3469  *
3470  * Queries decoder drain handling.
3471  *
3472  * Returns: TRUE if drainable handling is enabled.
3473  *
3474  * MT safe.
3475  */
3476 gboolean
3477 gst_audio_decoder_get_drainable (GstAudioDecoder * dec)
3478 {
3479   gboolean result;
3480
3481   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), 0);
3482
3483   GST_OBJECT_LOCK (dec);
3484   result = dec->priv->drainable;
3485   GST_OBJECT_UNLOCK (dec);
3486
3487   return result;
3488 }
3489
3490 /**
3491  * gst_audio_decoder_set_needs_format:
3492  * @dec: a #GstAudioDecoder
3493  * @enabled: new state
3494  *
3495  * Configures decoder format needs.  If enabled, subclass needs to be
3496  * negotiated with format caps before it can process any data.  It will then
3497  * never be handed any data before it has been configured.
3498  * Otherwise, it might be handed data without having been configured and
3499  * is then expected being able to do so either by default
3500  * or based on the input data.
3501  *
3502  * MT safe.
3503  */
3504 void
3505 gst_audio_decoder_set_needs_format (GstAudioDecoder * dec, gboolean enabled)
3506 {
3507   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3508
3509   GST_OBJECT_LOCK (dec);
3510   dec->priv->needs_format = enabled;
3511   GST_OBJECT_UNLOCK (dec);
3512 }
3513
3514 /**
3515  * gst_audio_decoder_get_needs_format:
3516  * @dec: a #GstAudioDecoder
3517  *
3518  * Queries decoder required format handling.
3519  *
3520  * Returns: TRUE if required format handling is enabled.
3521  *
3522  * MT safe.
3523  */
3524 gboolean
3525 gst_audio_decoder_get_needs_format (GstAudioDecoder * dec)
3526 {
3527   gboolean result;
3528
3529   g_return_val_if_fail (GST_IS_AUDIO_DECODER (dec), FALSE);
3530
3531   GST_OBJECT_LOCK (dec);
3532   result = dec->priv->needs_format;
3533   GST_OBJECT_UNLOCK (dec);
3534
3535   return result;
3536 }
3537
3538 /**
3539  * gst_audio_decoder_merge_tags:
3540  * @dec: a #GstAudioDecoder
3541  * @tags: (allow-none): a #GstTagList to merge, or NULL
3542  * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
3543  *
3544  * Sets the audio decoder tags and how they should be merged with any
3545  * upstream stream tags. This will override any tags previously-set
3546  * with gst_audio_decoder_merge_tags().
3547  *
3548  * Note that this is provided for convenience, and the subclass is
3549  * not required to use this and can still do tag handling on its own.
3550  */
3551 void
3552 gst_audio_decoder_merge_tags (GstAudioDecoder * dec,
3553     const GstTagList * tags, GstTagMergeMode mode)
3554 {
3555   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3556   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
3557   g_return_if_fail (mode != GST_TAG_MERGE_UNDEFINED);
3558
3559   GST_AUDIO_DECODER_STREAM_LOCK (dec);
3560   if (dec->priv->taglist != tags) {
3561     if (dec->priv->taglist) {
3562       gst_tag_list_unref (dec->priv->taglist);
3563       dec->priv->taglist = NULL;
3564       dec->priv->decoder_tags_merge_mode = GST_TAG_MERGE_KEEP_ALL;
3565     }
3566     if (tags) {
3567       dec->priv->taglist = gst_tag_list_ref ((GstTagList *) tags);
3568       dec->priv->decoder_tags_merge_mode = mode;
3569     }
3570
3571     GST_DEBUG_OBJECT (dec, "setting decoder tags to %" GST_PTR_FORMAT, tags);
3572     dec->priv->taglist_changed = TRUE;
3573   }
3574   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
3575 }
3576
3577 /**
3578  * gst_audio_decoder_allocate_output_buffer:
3579  * @dec: a #GstAudioDecoder
3580  * @size: size of the buffer
3581  *
3582  * Helper function that allocates a buffer to hold an audio frame
3583  * for @dec's current output format.
3584  *
3585  * Returns: (transfer full): allocated buffer
3586  */
3587 GstBuffer *
3588 gst_audio_decoder_allocate_output_buffer (GstAudioDecoder * dec, gsize size)
3589 {
3590   GstBuffer *buffer = NULL;
3591   gboolean needs_reconfigure = FALSE;
3592
3593   g_return_val_if_fail (size > 0, NULL);
3594
3595   GST_DEBUG ("alloc src buffer");
3596
3597   GST_AUDIO_DECODER_STREAM_LOCK (dec);
3598
3599   needs_reconfigure = gst_pad_check_reconfigure (dec->srcpad);
3600   if (G_UNLIKELY (dec->priv->ctx.output_format_changed ||
3601           (GST_AUDIO_INFO_IS_VALID (&dec->priv->ctx.info)
3602               && needs_reconfigure))) {
3603     if (!gst_audio_decoder_negotiate_unlocked (dec)) {
3604       GST_INFO_OBJECT (dec, "Failed to negotiate, fallback allocation");
3605       gst_pad_mark_reconfigure (dec->srcpad);
3606       goto fallback;
3607     }
3608   }
3609
3610   buffer =
3611       gst_buffer_new_allocate (dec->priv->ctx.allocator, size,
3612       &dec->priv->ctx.params);
3613   if (!buffer) {
3614     GST_INFO_OBJECT (dec, "couldn't allocate output buffer");
3615     goto fallback;
3616   }
3617
3618   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
3619
3620   return buffer;
3621 fallback:
3622   buffer = gst_buffer_new_allocate (NULL, size, NULL);
3623   GST_AUDIO_DECODER_STREAM_UNLOCK (dec);
3624
3625   return buffer;
3626 }
3627
3628 /**
3629  * gst_audio_decoder_get_allocator:
3630  * @dec: a #GstAudioDecoder
3631  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
3632  * used
3633  * @params: (out) (allow-none) (transfer full): the
3634  * #GstAllocationParams of @allocator
3635  *
3636  * Lets #GstAudioDecoder sub-classes to know the memory @allocator
3637  * used by the base class and its @params.
3638  *
3639  * Unref the @allocator after use it.
3640  */
3641 void
3642 gst_audio_decoder_get_allocator (GstAudioDecoder * dec,
3643     GstAllocator ** allocator, GstAllocationParams * params)
3644 {
3645   g_return_if_fail (GST_IS_AUDIO_DECODER (dec));
3646
3647   if (allocator)
3648     *allocator = dec->priv->ctx.allocator ?
3649         gst_object_ref (dec->priv->ctx.allocator) : NULL;
3650
3651   if (params)
3652     *params = dec->priv->ctx.params;
3653 }
3654
3655 /**
3656  * gst_audio_decoder_set_use_default_pad_acceptcaps:
3657  * @decoder: a #GstAudioDecoder
3658  * @use: if the default pad accept-caps query handling should be used
3659  *
3660  * Lets #GstAudioDecoder sub-classes decide if they want the sink pad
3661  * to use the default pad query handler to reply to accept-caps queries.
3662  *
3663  * By setting this to true it is possible to further customize the default
3664  * handler with %GST_PAD_SET_ACCEPT_INTERSECT and
3665  * %GST_PAD_SET_ACCEPT_TEMPLATE
3666  *
3667  * Since: 1.6
3668  */
3669 void
3670 gst_audio_decoder_set_use_default_pad_acceptcaps (GstAudioDecoder * decoder,
3671     gboolean use)
3672 {
3673   decoder->priv->use_default_pad_acceptcaps = use;
3674 }