27a4f0a5978fd4b92ef00e0923ac1c2f3dfdde99
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstaudioencoder.c
1 /* GStreamer
2  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
3  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
4  *   Contact: Stefan Kost <stefan.kost@nokia.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gstaudioencoder
24  * @short_description: Base class for audio encoders
25  * @see_also: #GstBaseTransform
26  *
27  * This base class is for audio encoders turning raw audio samples into
28  * encoded audio data.
29  *
30  * GstAudioEncoder and subclass should cooperate as follows.
31  * <orderedlist>
32  * <listitem>
33  *   <itemizedlist><title>Configuration</title>
34  *   <listitem><para>
35  *     Initially, GstAudioEncoder calls @start when the encoder element
36  *     is activated, which allows subclass to perform any global setup.
37  *   </para></listitem>
38  *   <listitem><para>
39  *     GstAudioEncoder calls @set_format to inform subclass of the format
40  *     of input audio data that it is about to receive.  Subclass should
41  *     setup for encoding and configure various base class parameters
42  *     appropriately, notably those directing desired input data handling.
43  *     While unlikely, it might be called more than once, if changing input
44  *     parameters require reconfiguration.
45  *   </para></listitem>
46  *   <listitem><para>
47  *     GstAudioEncoder calls @stop at end of all processing.
48  *   </para></listitem>
49  *   </itemizedlist>
50  * </listitem>
51  * As of configuration stage, and throughout processing, GstAudioEncoder
52  * maintains various parameters that provide required context,
53  * e.g. describing the format of input audio data.
54  * Conversely, subclass can and should configure these context parameters
55  * to inform base class of its expectation w.r.t. buffer handling.
56  * <listitem>
57  *   <itemizedlist>
58  *   <title>Data processing</title>
59  *     <listitem><para>
60  *       Base class gathers input sample data (as directed by the context's
61  *       frame_samples and frame_max) and provides this to subclass' @handle_frame.
62  *     </para></listitem>
63  *     <listitem><para>
64  *       If codec processing results in encoded data, subclass should call
65  *       @gst_audio_encoder_finish_frame to have encoded data pushed
66  *       downstream.  Alternatively, it might also call to indicate dropped
67  *       (non-encoded) samples.
68  *     </para></listitem>
69  *     <listitem><para>
70  *       Just prior to actually pushing a buffer downstream,
71  *       it is passed to @pre_push.
72  *     </para></listitem>
73  *     <listitem><para>
74  *       During the parsing process GstAudioEncoderClass will handle both
75  *       srcpad and sinkpad events. Sink events will be passed to subclass
76  *       if @event callback has been provided.
77  *     </para></listitem>
78  *   </itemizedlist>
79  * </listitem>
80  * <listitem>
81  *   <itemizedlist><title>Shutdown phase</title>
82  *   <listitem><para>
83  *     GstAudioEncoder class calls @stop to inform the subclass that data
84  *     parsing will be stopped.
85  *   </para></listitem>
86  *   </itemizedlist>
87  * </listitem>
88  * </orderedlist>
89  *
90  * Subclass is responsible for providing pad template caps for
91  * source and sink pads. The pads need to be named "sink" and "src". It also 
92  * needs to set the fixed caps on srcpad, when the format is ensured.  This
93  * is typically when base class calls subclass' @set_format function, though
94  * it might be delayed until calling @gst_audio_encoder_finish_frame.
95  *
96  * In summary, above process should have subclass concentrating on
97  * codec data processing while leaving other matters to base class,
98  * such as most notably timestamp handling.  While it may exert more control
99  * in this area (see e.g. @pre_push), it is very much not recommended.
100  *
101  * In particular, base class will either favor tracking upstream timestamps
102  * (at the possible expense of jitter) or aim to arrange for a perfect stream of
103  * output timestamps, depending on #GstAudioEncoder:perfect-timestamp.
104  * However, in the latter case, the input may not be so perfect or ideal, which
105  * is handled as follows.  An input timestamp is compared with the expected
106  * timestamp as dictated by input sample stream and if the deviation is less
107  * than #GstAudioEncoder:tolerance, the deviation is discarded.
108  * Otherwise, it is considered a discontuinity and subsequent output timestamp
109  * is resynced to the new position after performing configured discontinuity
110  * processing.  In the non-perfect-timestamp case, an upstream variation
111  * exceeding tolerance only leads to marking DISCONT on subsequent outgoing
112  * (while timestamps are adjusted to upstream regardless of variation).
113  * While DISCONT is also marked in the perfect-timestamp case, this one
114  * optionally (see #GstAudioEncoder:hard-resync)
115  * performs some additional steps, such as clipping of (early) input samples
116  * or draining all currently remaining input data, depending on the direction
117  * of the discontuinity.
118  *
119  * If perfect timestamps are arranged, it is also possible to request baseclass
120  * (usually set by subclass) to provide additional buffer metadata (in OFFSET
121  * and OFFSET_END) fields according to granule defined semantics currently
122  * needed by oggmux.  Specifically, OFFSET is set to granulepos (= sample count
123  * including buffer) and OFFSET_END to corresponding timestamp (as determined
124  * by same sample count and sample rate).
125  *
126  * Things that subclass need to take care of:
127  * <itemizedlist>
128  *   <listitem><para>Provide pad templates</para></listitem>
129  *   <listitem><para>
130  *      Set source pad caps when appropriate
131  *   </para></listitem>
132  *   <listitem><para>
133  *      Inform base class of buffer processing needs using context's
134  *      frame_samples and frame_bytes.
135  *   </para></listitem>
136  *   <listitem><para>
137  *      Set user-configurable properties to sane defaults for format and
138  *      implementing codec at hand, e.g. those controlling timestamp behaviour
139  *      and discontinuity processing.
140  *   </para></listitem>
141  *   <listitem><para>
142  *      Accept data in @handle_frame and provide encoded results to
143  *      @gst_audio_encoder_finish_frame.
144  *   </para></listitem>
145  * </itemizedlist>
146  *
147  */
148
149 #ifdef HAVE_CONFIG_H
150 #  include "config.h"
151 #endif
152
153 #include "gstaudioencoder.h"
154 #include <gst/base/gstadapter.h>
155 #include <gst/audio/audio.h>
156 #include <gst/pbutils/descriptions.h>
157
158 #include <stdlib.h>
159 #include <string.h>
160
161
162 GST_DEBUG_CATEGORY_STATIC (gst_audio_encoder_debug);
163 #define GST_CAT_DEFAULT gst_audio_encoder_debug
164
165 #define GST_AUDIO_ENCODER_GET_PRIVATE(obj)  \
166     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_AUDIO_ENCODER, \
167         GstAudioEncoderPrivate))
168
169 enum
170 {
171   PROP_0,
172   PROP_PERFECT_TS,
173   PROP_GRANULE,
174   PROP_HARD_RESYNC,
175   PROP_TOLERANCE
176 };
177
178 #define DEFAULT_PERFECT_TS   FALSE
179 #define DEFAULT_GRANULE      FALSE
180 #define DEFAULT_HARD_RESYNC  FALSE
181 #define DEFAULT_TOLERANCE    40000000
182 #define DEFAULT_HARD_MIN     FALSE
183 #define DEFAULT_DRAINABLE    TRUE
184
185 typedef struct _GstAudioEncoderContext
186 {
187   /* input */
188   GstAudioInfo info;
189
190   /* output */
191   GstCaps *caps;
192   gboolean output_caps_changed;
193   gint frame_samples_min, frame_samples_max;
194   gint frame_max;
195   gint lookahead;
196   /* MT-protected (with LOCK) */
197   GstClockTime min_latency;
198   GstClockTime max_latency;
199
200   GList *headers;
201   gboolean new_headers;
202
203   GstAllocator *allocator;
204   GstAllocationParams params;
205 } GstAudioEncoderContext;
206
207 struct _GstAudioEncoderPrivate
208 {
209   /* activation status */
210   gboolean active;
211
212   /* input base/first ts as basis for output ts;
213    * kept nearly constant for perfect_ts,
214    * otherwise resyncs to upstream ts */
215   GstClockTime base_ts;
216   /* corresponding base granulepos */
217   gint64 base_gp;
218   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
219   guint64 samples;
220
221   /* currently collected sample data */
222   GstAdapter *adapter;
223   /* offset in adapter up to which already supplied to encoder */
224   gint offset;
225   /* mark outgoing discont */
226   gboolean discont;
227   /* to guess duration of drained data */
228   GstClockTime last_duration;
229
230   /* subclass provided data in processing round */
231   gboolean got_data;
232   /* subclass gave all it could already */
233   gboolean drained;
234   /* subclass currently being forcibly drained */
235   gboolean force;
236   /* need to handle changed input caps */
237   gboolean do_caps;
238
239   /* output bps estimatation */
240   /* global in samples seen */
241   guint64 samples_in;
242   /* global bytes sent out */
243   guint64 bytes_out;
244
245   /* context storage */
246   GstAudioEncoderContext ctx;
247
248   /* properties */
249   gint64 tolerance;
250   gboolean perfect_ts;
251   gboolean hard_resync;
252   gboolean granule;
253   gboolean hard_min;
254   gboolean drainable;
255
256   /* pending tags */
257   GstTagList *tags;
258   gboolean tags_changed;
259   /* pending serialized sink events, will be sent from finish_frame() */
260   GList *pending_events;
261 };
262
263
264 static GstElementClass *parent_class = NULL;
265
266 static void gst_audio_encoder_class_init (GstAudioEncoderClass * klass);
267 static void gst_audio_encoder_init (GstAudioEncoder * parse,
268     GstAudioEncoderClass * klass);
269
270 GType
271 gst_audio_encoder_get_type (void)
272 {
273   static GType audio_encoder_type = 0;
274
275   if (!audio_encoder_type) {
276     static const GTypeInfo audio_encoder_info = {
277       sizeof (GstAudioEncoderClass),
278       (GBaseInitFunc) NULL,
279       (GBaseFinalizeFunc) NULL,
280       (GClassInitFunc) gst_audio_encoder_class_init,
281       NULL,
282       NULL,
283       sizeof (GstAudioEncoder),
284       0,
285       (GInstanceInitFunc) gst_audio_encoder_init,
286     };
287     const GInterfaceInfo preset_interface_info = {
288       NULL,                     /* interface_init */
289       NULL,                     /* interface_finalize */
290       NULL                      /* interface_data */
291     };
292
293     audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT,
294         "GstAudioEncoder", &audio_encoder_info, G_TYPE_FLAG_ABSTRACT);
295
296     g_type_add_interface_static (audio_encoder_type, GST_TYPE_PRESET,
297         &preset_interface_info);
298   }
299   return audio_encoder_type;
300 }
301
302 static void gst_audio_encoder_finalize (GObject * object);
303 static void gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full);
304
305 static void gst_audio_encoder_set_property (GObject * object,
306     guint prop_id, const GValue * value, GParamSpec * pspec);
307 static void gst_audio_encoder_get_property (GObject * object,
308     guint prop_id, GValue * value, GParamSpec * pspec);
309
310 static gboolean gst_audio_encoder_sink_activate_mode (GstPad * pad,
311     GstObject * parent, GstPadMode mode, gboolean active);
312
313 static GstCaps *gst_audio_encoder_getcaps_default (GstAudioEncoder * enc,
314     GstCaps * filter);
315
316 static gboolean gst_audio_encoder_sink_event_default (GstAudioEncoder * enc,
317     GstEvent * event);
318 static gboolean gst_audio_encoder_src_event_default (GstAudioEncoder * enc,
319     GstEvent * event);
320 static gboolean gst_audio_encoder_sink_event (GstPad * pad, GstObject * parent,
321     GstEvent * event);
322 static gboolean gst_audio_encoder_src_event (GstPad * pad, GstObject * parent,
323     GstEvent * event);
324 static gboolean gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc,
325     GstCaps * caps);
326 static GstFlowReturn gst_audio_encoder_chain (GstPad * pad, GstObject * parent,
327     GstBuffer * buffer);
328 static gboolean gst_audio_encoder_src_query (GstPad * pad, GstObject * parent,
329     GstQuery * query);
330 static gboolean gst_audio_encoder_sink_query (GstPad * pad, GstObject * parent,
331     GstQuery * query);
332 static GstStateChangeReturn gst_audio_encoder_change_state (GstElement *
333     element, GstStateChange transition);
334
335 static gboolean gst_audio_encoder_decide_allocation_default (GstAudioEncoder *
336     enc, GstQuery * query);
337 static gboolean gst_audio_encoder_propose_allocation_default (GstAudioEncoder *
338     enc, GstQuery * query);
339 static gboolean gst_audio_encoder_negotiate_default (GstAudioEncoder * enc);
340
341 static void
342 gst_audio_encoder_class_init (GstAudioEncoderClass * klass)
343 {
344   GObjectClass *gobject_class;
345   GstElementClass *gstelement_class;
346
347   gobject_class = G_OBJECT_CLASS (klass);
348   gstelement_class = GST_ELEMENT_CLASS (klass);
349   parent_class = g_type_class_peek_parent (klass);
350
351   GST_DEBUG_CATEGORY_INIT (gst_audio_encoder_debug, "audioencoder", 0,
352       "audio encoder base class");
353
354   g_type_class_add_private (klass, sizeof (GstAudioEncoderPrivate));
355
356   gobject_class->set_property = gst_audio_encoder_set_property;
357   gobject_class->get_property = gst_audio_encoder_get_property;
358
359   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_audio_encoder_finalize);
360
361   /* properties */
362   g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
363       g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps",
364           "Favour perfect timestamps over tracking upstream timestamps",
365           DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
366   g_object_class_install_property (gobject_class, PROP_GRANULE,
367       g_param_spec_boolean ("mark-granule", "Granule Marking",
368           "Apply granule semantics to buffer metadata (implies perfect-timestamp)",
369           DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
370   g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
371       g_param_spec_boolean ("hard-resync", "Hard Resync",
372           "Perform clipping and sample flushing upon discontinuity",
373           DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
374   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
375       g_param_spec_int64 ("tolerance", "Tolerance",
376           "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
377           0, G_MAXINT64, DEFAULT_TOLERANCE,
378           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
379
380   gstelement_class->change_state =
381       GST_DEBUG_FUNCPTR (gst_audio_encoder_change_state);
382
383   klass->getcaps = gst_audio_encoder_getcaps_default;
384   klass->sink_event = gst_audio_encoder_sink_event_default;
385   klass->src_event = gst_audio_encoder_src_event_default;
386   klass->propose_allocation = gst_audio_encoder_propose_allocation_default;
387   klass->decide_allocation = gst_audio_encoder_decide_allocation_default;
388   klass->negotiate = gst_audio_encoder_negotiate_default;
389 }
390
391 static void
392 gst_audio_encoder_init (GstAudioEncoder * enc, GstAudioEncoderClass * bclass)
393 {
394   GstPadTemplate *pad_template;
395
396   GST_DEBUG_OBJECT (enc, "gst_audio_encoder_init");
397
398   enc->priv = GST_AUDIO_ENCODER_GET_PRIVATE (enc);
399
400   /* only push mode supported */
401   pad_template =
402       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
403   g_return_if_fail (pad_template != NULL);
404   enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
405   gst_pad_set_event_function (enc->sinkpad,
406       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_event));
407   gst_pad_set_query_function (enc->sinkpad,
408       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_query));
409   gst_pad_set_chain_function (enc->sinkpad,
410       GST_DEBUG_FUNCPTR (gst_audio_encoder_chain));
411   gst_pad_set_activatemode_function (enc->sinkpad,
412       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_activate_mode));
413   gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
414
415   GST_DEBUG_OBJECT (enc, "sinkpad created");
416
417   /* and we don't mind upstream traveling stuff that much ... */
418   pad_template =
419       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
420   g_return_if_fail (pad_template != NULL);
421   enc->srcpad = gst_pad_new_from_template (pad_template, "src");
422   gst_pad_set_event_function (enc->srcpad,
423       GST_DEBUG_FUNCPTR (gst_audio_encoder_src_event));
424   gst_pad_set_query_function (enc->srcpad,
425       GST_DEBUG_FUNCPTR (gst_audio_encoder_src_query));
426   gst_pad_use_fixed_caps (enc->srcpad);
427   gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
428   GST_DEBUG_OBJECT (enc, "src created");
429
430   enc->priv->adapter = gst_adapter_new ();
431
432   g_rec_mutex_init (&enc->stream_lock);
433
434   /* property default */
435   enc->priv->granule = DEFAULT_GRANULE;
436   enc->priv->perfect_ts = DEFAULT_PERFECT_TS;
437   enc->priv->hard_resync = DEFAULT_HARD_RESYNC;
438   enc->priv->tolerance = DEFAULT_TOLERANCE;
439   enc->priv->hard_min = DEFAULT_HARD_MIN;
440   enc->priv->drainable = DEFAULT_DRAINABLE;
441
442   /* init state */
443   gst_audio_encoder_reset (enc, TRUE);
444   GST_DEBUG_OBJECT (enc, "init ok");
445 }
446
447 static void
448 gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full)
449 {
450   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
451
452   GST_LOG_OBJECT (enc, "reset full %d", full);
453
454   if (full) {
455     enc->priv->active = FALSE;
456     enc->priv->samples_in = 0;
457     enc->priv->bytes_out = 0;
458
459     g_list_foreach (enc->priv->ctx.headers, (GFunc) gst_buffer_unref, NULL);
460     g_list_free (enc->priv->ctx.headers);
461     enc->priv->ctx.headers = NULL;
462     enc->priv->ctx.new_headers = FALSE;
463
464     gst_caps_replace (&enc->priv->ctx.caps, NULL);
465     memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx));
466     gst_audio_info_init (&enc->priv->ctx.info);
467
468     if (enc->priv->tags)
469       gst_tag_list_unref (enc->priv->tags);
470     enc->priv->tags = NULL;
471     enc->priv->tags_changed = FALSE;
472
473     g_list_foreach (enc->priv->pending_events, (GFunc) gst_event_unref, NULL);
474     g_list_free (enc->priv->pending_events);
475     enc->priv->pending_events = NULL;
476
477     if (enc->priv->ctx.allocator)
478       gst_object_unref (enc->priv->ctx.allocator);
479     enc->priv->ctx.allocator = NULL;
480   }
481
482   gst_segment_init (&enc->input_segment, GST_FORMAT_TIME);
483   gst_segment_init (&enc->output_segment, GST_FORMAT_TIME);
484
485   gst_adapter_clear (enc->priv->adapter);
486   enc->priv->got_data = FALSE;
487   enc->priv->drained = TRUE;
488   enc->priv->offset = 0;
489   enc->priv->base_ts = GST_CLOCK_TIME_NONE;
490   enc->priv->base_gp = -1;
491   enc->priv->samples = 0;
492   enc->priv->discont = FALSE;
493
494   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
495 }
496
497 static void
498 gst_audio_encoder_finalize (GObject * object)
499 {
500   GstAudioEncoder *enc = GST_AUDIO_ENCODER (object);
501
502   g_object_unref (enc->priv->adapter);
503
504   g_rec_mutex_clear (&enc->stream_lock);
505
506   G_OBJECT_CLASS (parent_class)->finalize (object);
507 }
508
509 static GstStateChangeReturn
510 gst_audio_encoder_change_state (GstElement * element, GstStateChange transition)
511 {
512   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
513   GstAudioEncoder *enc = GST_AUDIO_ENCODER (element);
514   GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
515
516   switch (transition) {
517     case GST_STATE_CHANGE_NULL_TO_READY:
518       if (klass->open) {
519         if (!klass->open (enc))
520           goto open_failed;
521       }
522     default:
523       break;
524   }
525
526   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
527
528   switch (transition) {
529     case GST_STATE_CHANGE_READY_TO_NULL:
530       if (klass->close) {
531         if (!klass->close (enc))
532           goto close_failed;
533       }
534     default:
535       break;
536   }
537
538   return ret;
539
540 open_failed:
541   {
542     GST_ELEMENT_ERROR (enc, LIBRARY, INIT, (NULL), ("Failed to open codec"));
543     return GST_STATE_CHANGE_FAILURE;
544   }
545 close_failed:
546   {
547     GST_ELEMENT_ERROR (enc, LIBRARY, INIT, (NULL), ("Failed to close codec"));
548     return GST_STATE_CHANGE_FAILURE;
549   }
550 }
551
552 static gboolean
553 gst_audio_encoder_push_event (GstAudioEncoder * enc, GstEvent * event)
554 {
555   switch (GST_EVENT_TYPE (event)) {
556     case GST_EVENT_SEGMENT:{
557       GstSegment seg;
558
559       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
560       gst_event_copy_segment (event, &seg);
561
562       GST_DEBUG_OBJECT (enc, "starting segment %" GST_SEGMENT_FORMAT, &seg);
563
564       enc->output_segment = seg;
565       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
566       break;
567     }
568     default:
569       break;
570   }
571
572   return gst_pad_push_event (enc->srcpad, event);
573 }
574
575 /**
576  * gst_audio_encoder_finish_frame:
577  * @enc: a #GstAudioEncoder
578  * @buffer: encoded data
579  * @samples: number of samples (per channel) represented by encoded data
580  *
581  * Collects encoded data and pushes encoded data downstream.
582  * Source pad caps must be set when this is called.
583  *
584  * If @samples < 0, then best estimate is all samples provided to encoder
585  * (subclass) so far.  @buf may be NULL, in which case next number of @samples
586  * are considered discarded, e.g. as a result of discontinuous transmission,
587  * and a discontinuity is marked.
588  *
589  * Note that samples received in gst_audio_encoder_handle_frame()
590  * may be invalidated by a call to this function.
591  *
592  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
593  */
594 GstFlowReturn
595 gst_audio_encoder_finish_frame (GstAudioEncoder * enc, GstBuffer * buf,
596     gint samples)
597 {
598   GstAudioEncoderClass *klass;
599   GstAudioEncoderPrivate *priv;
600   GstAudioEncoderContext *ctx;
601   GstFlowReturn ret = GST_FLOW_OK;
602
603   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
604   priv = enc->priv;
605   ctx = &enc->priv->ctx;
606
607   /* subclass should not hand us no data */
608   g_return_val_if_fail (buf == NULL || gst_buffer_get_size (buf) > 0,
609       GST_FLOW_ERROR);
610
611   /* subclass should know what it is producing by now */
612   if (!ctx->caps)
613     goto no_caps;
614
615   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
616
617   GST_LOG_OBJECT (enc,
618       "accepting %" G_GSIZE_FORMAT " bytes encoded data as %d samples",
619       buf ? gst_buffer_get_size (buf) : -1, samples);
620
621   if (G_UNLIKELY (ctx->output_caps_changed
622           || gst_pad_check_reconfigure (enc->srcpad))) {
623     if (!gst_audio_encoder_negotiate (enc)) {
624       ret = GST_FLOW_NOT_NEGOTIATED;
625       goto exit;
626     }
627   }
628
629   /* mark subclass still alive and providing */
630   if (G_LIKELY (buf))
631     priv->got_data = TRUE;
632
633   if (priv->pending_events) {
634     GList *pending_events, *l;
635
636     pending_events = priv->pending_events;
637     priv->pending_events = NULL;
638
639     GST_DEBUG_OBJECT (enc, "Pushing pending events");
640     for (l = pending_events; l; l = l->next)
641       gst_audio_encoder_push_event (enc, l->data);
642     g_list_free (pending_events);
643   }
644
645   /* send after pending events, which likely includes newsegment event */
646   if (G_UNLIKELY (enc->priv->tags && enc->priv->tags_changed)) {
647 #if 0
648     GstCaps *caps;
649 #endif
650
651     /* add codec info to pending tags */
652 #if 0
653     if (!enc->priv->tags)
654       enc->priv->tags = gst_tag_list_new ();
655     enc->priv->tags = gst_tag_list_make_writable (enc->priv->tags);
656     caps = gst_pad_get_current_caps (enc->srcpad);
657     gst_pb_utils_add_codec_description_to_tag_list (enc->priv->tags,
658         GST_TAG_CODEC, caps);
659     gst_pb_utils_add_codec_description_to_tag_list (enc->priv->tags,
660         GST_TAG_AUDIO_CODEC, caps);
661 #endif
662     GST_DEBUG_OBJECT (enc, "sending tags %" GST_PTR_FORMAT, enc->priv->tags);
663     gst_audio_encoder_push_event (enc,
664         gst_event_new_tag (gst_tag_list_ref (enc->priv->tags)));
665     enc->priv->tags_changed = FALSE;
666   }
667
668   /* remove corresponding samples from input */
669   if (samples < 0)
670     samples = (enc->priv->offset / ctx->info.bpf);
671
672   if (G_LIKELY (samples)) {
673     /* track upstream ts if so configured */
674     if (!enc->priv->perfect_ts) {
675       guint64 ts, distance;
676
677       ts = gst_adapter_prev_timestamp (priv->adapter, &distance);
678       g_assert (distance % ctx->info.bpf == 0);
679       distance /= ctx->info.bpf;
680       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
681           GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
682       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
683           GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
684       /* when draining adapter might be empty and no ts to offer */
685       if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
686         GstClockTimeDiff diff;
687         GstClockTime old_ts, next_ts;
688
689         /* passed into another buffer;
690          * mild check for discontinuity and only mark if so */
691         next_ts = ts +
692             gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate);
693         old_ts = priv->base_ts +
694             gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
695         diff = GST_CLOCK_DIFF (next_ts, old_ts);
696         GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
697         /* only mark discontinuity if beyond tolerance */
698         if (G_UNLIKELY (diff < -enc->priv->tolerance ||
699                 diff > enc->priv->tolerance)) {
700           GST_DEBUG_OBJECT (enc, "marked discont");
701           priv->discont = TRUE;
702         }
703         if (diff > GST_SECOND / ctx->info.rate / 2 ||
704             diff < -GST_SECOND / ctx->info.rate / 2) {
705           GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
706               " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
707           /* re-sync to upstream ts */
708           priv->base_ts = ts;
709           priv->samples = distance;
710         } else {
711           GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter");
712         }
713       }
714     }
715     /* advance sample view */
716     if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) {
717       if (G_LIKELY (!priv->force)) {
718         /* no way we can let this pass */
719         g_assert_not_reached ();
720         /* really no way */
721         goto overflow;
722       } else {
723         priv->offset = 0;
724         if (samples * ctx->info.bpf >= gst_adapter_available (priv->adapter))
725           gst_adapter_clear (priv->adapter);
726         else
727           gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
728       }
729     } else {
730       gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
731       priv->offset -= samples * ctx->info.bpf;
732       /* avoid subsequent stray prev_ts */
733       if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
734         gst_adapter_clear (priv->adapter);
735     }
736     /* sample count advanced below after buffer handling */
737   }
738
739   /* collect output */
740   if (G_LIKELY (buf)) {
741     gsize size;
742
743     /* Pushing headers first */
744     if (G_UNLIKELY (priv->ctx.new_headers)) {
745       GList *tmp;
746
747       GST_DEBUG_OBJECT (enc, "Sending headers");
748
749       for (tmp = priv->ctx.headers; tmp; tmp = tmp->next) {
750         GstBuffer *tmpbuf = gst_buffer_ref (tmp->data);
751
752         tmpbuf = gst_buffer_make_writable (tmpbuf);
753         size = gst_buffer_get_size (tmpbuf);
754
755         if (G_UNLIKELY (priv->discont)) {
756           GST_LOG_OBJECT (enc, "marking discont");
757           GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
758           priv->discont = FALSE;
759         }
760
761         /* Ogg codecs like Vorbis use offset/offset-end in a special
762          * way and both should be 0 for these codecs */
763         if (priv->base_gp >= 0) {
764           GST_BUFFER_OFFSET (tmpbuf) = 0;
765           GST_BUFFER_OFFSET_END (tmpbuf) = 0;
766         } else {
767           GST_BUFFER_OFFSET (tmpbuf) = priv->bytes_out;
768           GST_BUFFER_OFFSET_END (tmpbuf) = priv->bytes_out + size;
769         }
770
771         priv->bytes_out += size;
772
773         gst_pad_push (enc->srcpad, tmpbuf);
774       }
775       priv->ctx.new_headers = FALSE;
776     }
777
778     size = gst_buffer_get_size (buf);
779
780     GST_LOG_OBJECT (enc, "taking %" G_GSIZE_FORMAT " bytes for output", size);
781     buf = gst_buffer_make_writable (buf);
782
783     /* decorate */
784     if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
785       /* FIXME ? lookahead could lead to weird ts and duration ?
786        * (particularly if not in perfect mode) */
787       /* mind sample rounding and produce perfect output */
788       GST_BUFFER_TIMESTAMP (buf) = priv->base_ts +
789           gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
790           ctx->info.rate);
791       GST_DEBUG_OBJECT (enc, "out samples %d", samples);
792       if (G_LIKELY (samples > 0)) {
793         priv->samples += samples;
794         GST_BUFFER_DURATION (buf) = priv->base_ts +
795             gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
796             ctx->info.rate) - GST_BUFFER_TIMESTAMP (buf);
797         priv->last_duration = GST_BUFFER_DURATION (buf);
798       } else {
799         /* duration forecast in case of handling remainder;
800          * the last one is probably like the previous one ... */
801         GST_BUFFER_DURATION (buf) = priv->last_duration;
802       }
803       if (priv->base_gp >= 0) {
804         /* pamper oggmux */
805         /* FIXME: in longer run, muxer should take care of this ... */
806         /* offset_end = granulepos for ogg muxer */
807         GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
808             enc->priv->ctx.lookahead;
809         /* offset = timestamp corresponding to granulepos for ogg muxer */
810         GST_BUFFER_OFFSET (buf) =
811             GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
812             ctx->info.rate);
813       } else {
814         GST_BUFFER_OFFSET (buf) = priv->bytes_out;
815         GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + size;
816       }
817     }
818
819     priv->bytes_out += size;
820
821     if (G_UNLIKELY (priv->discont)) {
822       GST_LOG_OBJECT (enc, "marking discont");
823       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
824       priv->discont = FALSE;
825     }
826
827     if (klass->pre_push) {
828       /* last chance for subclass to do some dirty stuff */
829       ret = klass->pre_push (enc, &buf);
830       if (ret != GST_FLOW_OK || !buf) {
831         GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
832             gst_flow_get_name (ret), buf);
833
834         if (buf)
835           gst_buffer_unref (buf);
836         goto exit;
837       }
838     }
839
840     GST_LOG_OBJECT (enc,
841         "pushing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
842         ", duration %" GST_TIME_FORMAT, size,
843         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
844         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
845
846     ret = gst_pad_push (enc->srcpad, buf);
847     GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
848   } else {
849     /* merely advance samples, most work for that already done above */
850     priv->samples += samples;
851   }
852
853 exit:
854   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
855
856   return ret;
857
858   /* ERRORS */
859 no_caps:
860   {
861     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, ("no caps set"), (NULL));
862     if (buf)
863       gst_buffer_unref (buf);
864     return GST_FLOW_ERROR;
865   }
866 overflow:
867   {
868     GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
869         ("received more encoded samples %d than provided %d",
870             samples, priv->offset / ctx->info.bpf), (NULL));
871     if (buf)
872       gst_buffer_unref (buf);
873     ret = GST_FLOW_ERROR;
874     goto exit;
875   }
876 }
877
878  /* adapter tracking idea:
879   * - start of adapter corresponds with what has already been encoded
880   * (i.e. really returned by encoder subclass)
881   * - start + offset is what needs to be fed to subclass next */
882 static GstFlowReturn
883 gst_audio_encoder_push_buffers (GstAudioEncoder * enc, gboolean force)
884 {
885   GstAudioEncoderClass *klass;
886   GstAudioEncoderPrivate *priv;
887   GstAudioEncoderContext *ctx;
888   gint av, need;
889   GstBuffer *buf;
890   GstFlowReturn ret = GST_FLOW_OK;
891
892   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
893
894   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
895
896   priv = enc->priv;
897   ctx = &enc->priv->ctx;
898
899   while (ret == GST_FLOW_OK) {
900
901     buf = NULL;
902     av = gst_adapter_available (priv->adapter);
903
904     g_assert (priv->offset <= av);
905     av -= priv->offset;
906
907     need =
908         ctx->frame_samples_min >
909         0 ? ctx->frame_samples_min * ctx->info.bpf : av;
910     GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d", av, need,
911         force);
912
913     if ((need > av) || !av) {
914       if (G_UNLIKELY (force)) {
915         priv->force = TRUE;
916         need = av;
917       } else {
918         break;
919       }
920     } else {
921       priv->force = FALSE;
922     }
923
924     if (ctx->frame_samples_max > 0)
925       need = MIN (av, ctx->frame_samples_max * ctx->info.bpf);
926
927     if (ctx->frame_samples_min == ctx->frame_samples_max) {
928       /* if we have some extra metadata,
929        * provide for integer multiple of frames to allow for better granularity
930        * of processing */
931       if (ctx->frame_samples_min > 0 && need) {
932         if (ctx->frame_max > 1)
933           need = need * MIN ((av / need), ctx->frame_max);
934         else if (ctx->frame_max == 0)
935           need = need * (av / need);
936       }
937     }
938
939     priv->got_data = FALSE;
940     if (G_LIKELY (need)) {
941       const guint8 *data;
942
943       data = gst_adapter_map (priv->adapter, priv->offset + need);
944       buf =
945           gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
946           (gpointer) data, priv->offset + need, priv->offset, need, NULL, NULL);
947     } else if (!priv->drainable) {
948       GST_DEBUG_OBJECT (enc, "non-drainable and no more data");
949       goto finish;
950     }
951
952     GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
953         need, priv->offset);
954
955     /* mark this already as consumed,
956      * which it should be when subclass gives us data in exchange for samples */
957     priv->offset += need;
958     priv->samples_in += need / ctx->info.bpf;
959
960     /* subclass might not want to be bothered with leftover data,
961      * so take care of that here if so, otherwise pass along */
962     if (G_UNLIKELY (priv->force && priv->hard_min && buf)) {
963       GST_DEBUG_OBJECT (enc, "bypassing subclass with leftover");
964       ret = gst_audio_encoder_finish_frame (enc, NULL, -1);
965     } else {
966       ret = klass->handle_frame (enc, buf);
967     }
968
969     if (G_LIKELY (buf)) {
970       gst_buffer_unref (buf);
971       gst_adapter_unmap (priv->adapter);
972     }
973
974   finish:
975     /* no data to feed, no leftover provided, then bail out */
976     if (G_UNLIKELY (!buf && !priv->got_data)) {
977       priv->drained = TRUE;
978       GST_LOG_OBJECT (enc, "no more data drained from subclass");
979       break;
980     }
981   }
982
983   return ret;
984 }
985
986 static GstFlowReturn
987 gst_audio_encoder_drain (GstAudioEncoder * enc)
988 {
989   GST_DEBUG_OBJECT (enc, "draining");
990   if (enc->priv->drained)
991     return GST_FLOW_OK;
992   else {
993     GST_DEBUG_OBJECT (enc, "... really");
994     return gst_audio_encoder_push_buffers (enc, TRUE);
995   }
996 }
997
998 static void
999 gst_audio_encoder_set_base_gp (GstAudioEncoder * enc)
1000 {
1001   GstClockTime ts;
1002
1003   if (!enc->priv->granule)
1004     return;
1005
1006   /* use running time for granule */
1007   /* incoming data is clipped, so a valid input should yield a valid output */
1008   ts = gst_segment_to_running_time (&enc->input_segment, GST_FORMAT_TIME,
1009       enc->priv->base_ts);
1010   if (GST_CLOCK_TIME_IS_VALID (ts)) {
1011     enc->priv->base_gp =
1012         GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate);
1013     GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
1014   } else {
1015     /* should reasonably have a valid base,
1016      * otherwise start at 0 if we did not already start there earlier */
1017     if (enc->priv->base_gp < 0) {
1018       enc->priv->base_gp = 0;
1019       GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
1020           enc->priv->base_gp);
1021     }
1022   }
1023 }
1024
1025 static GstFlowReturn
1026 gst_audio_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1027 {
1028   GstAudioEncoder *enc;
1029   GstAudioEncoderPrivate *priv;
1030   GstAudioEncoderContext *ctx;
1031   GstFlowReturn ret = GST_FLOW_OK;
1032   gboolean discont;
1033   gsize size;
1034
1035   enc = GST_AUDIO_ENCODER (parent);
1036
1037   priv = enc->priv;
1038   ctx = &enc->priv->ctx;
1039
1040   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1041
1042   if (G_UNLIKELY (priv->do_caps)) {
1043     GstCaps *caps = gst_pad_get_current_caps (enc->sinkpad);
1044     if (!caps)
1045       goto not_negotiated;
1046     if (!gst_audio_encoder_sink_setcaps (enc, caps)) {
1047       gst_caps_unref (caps);
1048       goto not_negotiated;
1049     }
1050     gst_caps_unref (caps);
1051     priv->do_caps = FALSE;
1052   }
1053
1054   /* should know what is coming by now */
1055   if (!ctx->info.bpf)
1056     goto not_negotiated;
1057
1058   size = gst_buffer_get_size (buffer);
1059
1060   GST_LOG_OBJECT (enc,
1061       "received buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1062       ", duration %" GST_TIME_FORMAT, size,
1063       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1064       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1065
1066   /* input shoud be whole number of sample frames */
1067   if (size % ctx->info.bpf)
1068     goto wrong_buffer;
1069
1070 #ifndef GST_DISABLE_GST_DEBUG
1071   {
1072     GstClockTime duration;
1073     GstClockTimeDiff diff;
1074
1075     /* verify buffer duration */
1076     duration = gst_util_uint64_scale (size, GST_SECOND,
1077         ctx->info.rate * ctx->info.bpf);
1078     diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
1079     if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
1080         (diff > GST_SECOND / ctx->info.rate / 2 ||
1081             diff < -GST_SECOND / ctx->info.rate / 2)) {
1082       GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
1083           GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
1084           GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
1085           GST_TIME_ARGS (duration));
1086     }
1087   }
1088 #endif
1089
1090   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1091   if (G_UNLIKELY (discont)) {
1092     GST_LOG_OBJECT (buffer, "marked discont");
1093     enc->priv->discont = discont;
1094   }
1095
1096   /* clip to segment */
1097   /* NOTE: slightly painful linking -laudio only for this one ... */
1098   buffer = gst_audio_buffer_clip (buffer, &enc->input_segment, ctx->info.rate,
1099       ctx->info.bpf);
1100   if (G_UNLIKELY (!buffer)) {
1101     GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
1102     goto done;
1103   }
1104
1105   size = gst_buffer_get_size (buffer);
1106
1107   GST_LOG_OBJECT (enc,
1108       "buffer after segment clipping has size %" G_GSIZE_FORMAT " with ts %"
1109       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT, size,
1110       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
1111       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1112
1113   if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
1114     priv->base_ts = GST_BUFFER_TIMESTAMP (buffer);
1115     GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
1116         GST_TIME_ARGS (priv->base_ts));
1117     gst_audio_encoder_set_base_gp (enc);
1118   }
1119
1120   /* check for continuity;
1121    * checked elsewhere in non-perfect case */
1122   if (enc->priv->perfect_ts) {
1123     GstClockTimeDiff diff = 0;
1124     GstClockTime next_ts = 0;
1125
1126     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
1127         GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
1128       guint64 samples;
1129
1130       samples = priv->samples +
1131           gst_adapter_available (priv->adapter) / ctx->info.bpf;
1132       next_ts = priv->base_ts +
1133           gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
1134       GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
1135           " samples past base_ts %" GST_TIME_FORMAT
1136           ", expected ts %" GST_TIME_FORMAT, samples,
1137           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
1138       diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer));
1139       GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
1140       /* if within tolerance,
1141        * discard buffer ts and carry on producing perfect stream,
1142        * otherwise clip or resync to ts */
1143       if (G_UNLIKELY (diff < -enc->priv->tolerance ||
1144               diff > enc->priv->tolerance)) {
1145         GST_DEBUG_OBJECT (enc, "marked discont");
1146         discont = TRUE;
1147       }
1148     }
1149
1150     /* do some fancy tweaking in hard resync case */
1151     if (discont && enc->priv->hard_resync) {
1152       if (diff < 0) {
1153         guint64 diff_bytes;
1154
1155         GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
1156             GST_TIME_FORMAT ".  Clipping buffer", GST_TIME_ARGS (next_ts));
1157
1158         diff_bytes =
1159             GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf;
1160         if (diff_bytes >= size) {
1161           gst_buffer_unref (buffer);
1162           goto done;
1163         }
1164         buffer = gst_buffer_make_writable (buffer);
1165         gst_buffer_resize (buffer, diff_bytes, size - diff_bytes);
1166
1167         GST_BUFFER_TIMESTAMP (buffer) += diff;
1168         /* care even less about duration after this */
1169       } else {
1170         /* drain stuff prior to resync */
1171         gst_audio_encoder_drain (enc);
1172       }
1173     }
1174     if (discont) {
1175       /* now re-sync ts */
1176       priv->base_ts += diff;
1177       gst_audio_encoder_set_base_gp (enc);
1178       priv->discont |= discont;
1179     }
1180   }
1181
1182   gst_adapter_push (enc->priv->adapter, buffer);
1183   /* new stuff, so we can push subclass again */
1184   enc->priv->drained = FALSE;
1185
1186   ret = gst_audio_encoder_push_buffers (enc, FALSE);
1187
1188 done:
1189   GST_LOG_OBJECT (enc, "chain leaving");
1190
1191   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1192
1193   return ret;
1194
1195   /* ERRORS */
1196 not_negotiated:
1197   {
1198     GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
1199         ("encoder not initialized"));
1200     gst_buffer_unref (buffer);
1201     ret = GST_FLOW_NOT_NEGOTIATED;
1202     goto done;
1203   }
1204 wrong_buffer:
1205   {
1206     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
1207         ("buffer size %" G_GSIZE_FORMAT " not a multiple of %d",
1208             gst_buffer_get_size (buffer), ctx->info.bpf));
1209     gst_buffer_unref (buffer);
1210     ret = GST_FLOW_ERROR;
1211     goto done;
1212   }
1213 }
1214
1215 static gboolean
1216 audio_info_is_equal (GstAudioInfo * from, GstAudioInfo * to)
1217 {
1218   if (from == to)
1219     return TRUE;
1220   if (from->finfo == NULL || to->finfo == NULL)
1221     return FALSE;
1222   if (GST_AUDIO_INFO_FORMAT (from) != GST_AUDIO_INFO_FORMAT (to))
1223     return FALSE;
1224   if (GST_AUDIO_INFO_RATE (from) != GST_AUDIO_INFO_RATE (to))
1225     return FALSE;
1226   if (GST_AUDIO_INFO_CHANNELS (from) != GST_AUDIO_INFO_CHANNELS (to))
1227     return FALSE;
1228   if (GST_AUDIO_INFO_CHANNELS (from) > 64)
1229     return TRUE;
1230   return (memcmp (from->position, to->position,
1231           GST_AUDIO_INFO_CHANNELS (from) * sizeof (to->position[0])) == 0);
1232 }
1233
1234 static gboolean
1235 gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc, GstCaps * caps)
1236 {
1237   GstAudioEncoderClass *klass;
1238   GstAudioEncoderContext *ctx;
1239   GstAudioInfo state;
1240   gboolean res = TRUE, changed = FALSE;
1241   guint old_rate;
1242
1243   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1244
1245   /* subclass must do something here ... */
1246   g_return_val_if_fail (klass->set_format != NULL, FALSE);
1247
1248   ctx = &enc->priv->ctx;
1249
1250   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1251
1252   GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
1253
1254   if (!gst_caps_is_fixed (caps))
1255     goto refuse_caps;
1256
1257   /* adjust ts tracking to new sample rate */
1258   old_rate = GST_AUDIO_INFO_RATE (&ctx->info);
1259   if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) {
1260     enc->priv->base_ts +=
1261         GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate);
1262     enc->priv->samples = 0;
1263   }
1264
1265   if (!gst_audio_info_from_caps (&state, caps))
1266     goto refuse_caps;
1267
1268   changed = !audio_info_is_equal (&state, &ctx->info);
1269
1270   if (changed) {
1271     GstClockTime old_min_latency;
1272     GstClockTime old_max_latency;
1273
1274     /* drain any pending old data stuff */
1275     gst_audio_encoder_drain (enc);
1276
1277     /* context defaults */
1278     enc->priv->ctx.frame_samples_min = 0;
1279     enc->priv->ctx.frame_samples_max = 0;
1280     enc->priv->ctx.frame_max = 0;
1281     enc->priv->ctx.lookahead = 0;
1282
1283     /* element might report latency */
1284     GST_OBJECT_LOCK (enc);
1285     old_min_latency = ctx->min_latency;
1286     old_max_latency = ctx->max_latency;
1287     GST_OBJECT_UNLOCK (enc);
1288
1289     if (klass->set_format)
1290       res = klass->set_format (enc, &state);
1291
1292     if (res)
1293       ctx->info = state;
1294
1295     /* invalidate state to ensure no casual carrying on */
1296     if (!res) {
1297       GST_DEBUG_OBJECT (enc, "subclass did not accept format");
1298       gst_audio_info_init (&state);
1299       goto exit;
1300     }
1301
1302     /* notify if new latency */
1303     GST_OBJECT_LOCK (enc);
1304     if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) ||
1305         (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) {
1306       GST_OBJECT_UNLOCK (enc);
1307       /* post latency message on the bus */
1308       gst_element_post_message (GST_ELEMENT (enc),
1309           gst_message_new_latency (GST_OBJECT (enc)));
1310       GST_OBJECT_LOCK (enc);
1311     }
1312     GST_OBJECT_UNLOCK (enc);
1313   } else {
1314     GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
1315   }
1316
1317 exit:
1318
1319   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1320
1321   return res;
1322
1323   /* ERRORS */
1324 refuse_caps:
1325   {
1326     GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
1327     goto exit;
1328   }
1329 }
1330
1331
1332 /**
1333  * gst_audio_encoder_proxy_getcaps:
1334  * @enc: a #GstAudioEncoder
1335  * @caps: initial caps
1336  * @filter: filter caps
1337  *
1338  * Returns caps that express @caps (or sink template caps if @caps == NULL)
1339  * restricted to channel/rate combinations supported by downstream elements
1340  * (e.g. muxers).
1341  *
1342  * Returns: a #GstCaps owned by caller
1343  */
1344 GstCaps *
1345 gst_audio_encoder_proxy_getcaps (GstAudioEncoder * enc, GstCaps * caps,
1346     GstCaps * filter)
1347 {
1348   GstCaps *templ_caps = NULL;
1349   GstCaps *allowed = NULL;
1350   GstCaps *fcaps, *filter_caps;
1351   gint i, j;
1352
1353   /* we want to be able to communicate to upstream elements like audioconvert
1354    * and audioresample any rate/channel restrictions downstream (e.g. muxer
1355    * only accepting certain sample rates) */
1356   templ_caps =
1357       caps ? gst_caps_ref (caps) : gst_pad_get_pad_template_caps (enc->sinkpad);
1358   allowed = gst_pad_get_allowed_caps (enc->srcpad);
1359   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
1360     fcaps = templ_caps;
1361     goto done;
1362   }
1363
1364   GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps);
1365   GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
1366
1367   filter_caps = gst_caps_new_empty ();
1368
1369   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
1370     GQuark q_name;
1371
1372     q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
1373
1374     /* pick rate + channel fields from allowed caps */
1375     for (j = 0; j < gst_caps_get_size (allowed); j++) {
1376       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
1377       const GValue *val;
1378       GstStructure *s;
1379
1380       s = gst_structure_new_id_empty (q_name);
1381       if ((val = gst_structure_get_value (allowed_s, "rate")))
1382         gst_structure_set_value (s, "rate", val);
1383       if ((val = gst_structure_get_value (allowed_s, "channels")))
1384         gst_structure_set_value (s, "channels", val);
1385       /* following might also make sense for some encoded formats,
1386        * e.g. wavpack */
1387       if ((val = gst_structure_get_value (allowed_s, "channel-mask")))
1388         gst_structure_set_value (s, "channel-mask", val);
1389
1390       filter_caps = gst_caps_merge_structure (filter_caps, s);
1391     }
1392   }
1393
1394   fcaps = gst_caps_intersect (filter_caps, templ_caps);
1395   gst_caps_unref (filter_caps);
1396   gst_caps_unref (templ_caps);
1397
1398   if (filter) {
1399     GST_LOG_OBJECT (enc, "intersecting with %" GST_PTR_FORMAT, filter);
1400     filter_caps = gst_caps_intersect_full (filter, fcaps,
1401         GST_CAPS_INTERSECT_FIRST);
1402     gst_caps_unref (fcaps);
1403     fcaps = filter_caps;
1404   }
1405
1406 done:
1407   gst_caps_replace (&allowed, NULL);
1408
1409   GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
1410
1411   return fcaps;
1412 }
1413
1414 static GstCaps *
1415 gst_audio_encoder_getcaps_default (GstAudioEncoder * enc, GstCaps * filter)
1416 {
1417   GstCaps *caps;
1418
1419   caps = gst_audio_encoder_proxy_getcaps (enc, NULL, filter);
1420   GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1421
1422   return caps;
1423 }
1424
1425 static gboolean
1426 gst_audio_encoder_sink_event_default (GstAudioEncoder * enc, GstEvent * event)
1427 {
1428   GstAudioEncoderClass *klass;
1429   gboolean res;
1430
1431   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1432
1433   switch (GST_EVENT_TYPE (event)) {
1434     case GST_EVENT_SEGMENT:
1435     {
1436       GstSegment seg;
1437
1438       gst_event_copy_segment (event, &seg);
1439
1440       if (seg.format == GST_FORMAT_TIME) {
1441         GST_DEBUG_OBJECT (enc, "received TIME SEGMENT %" GST_SEGMENT_FORMAT,
1442             &seg);
1443       } else {
1444         GST_DEBUG_OBJECT (enc, "received SEGMENT %" GST_SEGMENT_FORMAT, &seg);
1445         GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1446         res = TRUE;
1447         break;
1448       }
1449
1450       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1451       /* finish current segment */
1452       gst_audio_encoder_drain (enc);
1453       /* reset partially for new segment */
1454       gst_audio_encoder_reset (enc, FALSE);
1455       /* and follow along with segment */
1456       enc->input_segment = seg;
1457
1458       enc->priv->pending_events =
1459           g_list_append (enc->priv->pending_events, event);
1460       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1461
1462       res = TRUE;
1463       break;
1464     }
1465
1466     case GST_EVENT_FLUSH_START:
1467       res = gst_audio_encoder_push_event (enc, event);
1468       break;
1469
1470     case GST_EVENT_FLUSH_STOP:
1471       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1472       /* discard any pending stuff */
1473       /* TODO route through drain ?? */
1474       if (!enc->priv->drained && klass->flush)
1475         klass->flush (enc);
1476       /* and get (re)set for the sequel */
1477       gst_audio_encoder_reset (enc, FALSE);
1478
1479       g_list_foreach (enc->priv->pending_events, (GFunc) gst_event_unref, NULL);
1480       g_list_free (enc->priv->pending_events);
1481       enc->priv->pending_events = NULL;
1482       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1483
1484       res = gst_audio_encoder_push_event (enc, event);
1485       break;
1486
1487     case GST_EVENT_EOS:
1488       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1489       gst_audio_encoder_drain (enc);
1490       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1491
1492       /* forward immediately because no buffer or serialized event
1493        * will come after EOS and nothing could trigger another
1494        * _finish_frame() call. */
1495       res = gst_audio_encoder_push_event (enc, event);
1496       break;
1497
1498     case GST_EVENT_CAPS:
1499     {
1500       GstCaps *caps;
1501
1502       gst_event_parse_caps (event, &caps);
1503       enc->priv->do_caps = TRUE;
1504       res = TRUE;
1505       gst_event_unref (event);
1506       break;
1507     }
1508
1509     case GST_EVENT_TAG:
1510     {
1511       GstTagList *tags;
1512
1513       gst_event_parse_tag (event, &tags);
1514
1515       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1516         tags = gst_tag_list_copy (tags);
1517
1518         /* FIXME: make generic based on GST_TAG_FLAG_ENCODED */
1519         gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1520         gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1521         gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
1522         gst_tag_list_remove_tag (tags, GST_TAG_SUBTITLE_CODEC);
1523         gst_tag_list_remove_tag (tags, GST_TAG_CONTAINER_FORMAT);
1524         gst_tag_list_remove_tag (tags, GST_TAG_BITRATE);
1525         gst_tag_list_remove_tag (tags, GST_TAG_NOMINAL_BITRATE);
1526         gst_tag_list_remove_tag (tags, GST_TAG_MAXIMUM_BITRATE);
1527         gst_tag_list_remove_tag (tags, GST_TAG_MINIMUM_BITRATE);
1528         gst_tag_list_remove_tag (tags, GST_TAG_ENCODER);
1529         gst_tag_list_remove_tag (tags, GST_TAG_ENCODER_VERSION);
1530
1531         gst_audio_encoder_merge_tags (enc, tags, GST_TAG_MERGE_REPLACE);
1532         gst_tag_list_unref (tags);
1533         gst_event_unref (event);
1534         event = NULL;
1535         res = TRUE;
1536         break;
1537       }
1538       /* fall through */
1539     }
1540
1541     default:
1542       /* Forward non-serialized events immediately. */
1543       if (!GST_EVENT_IS_SERIALIZED (event)) {
1544         res =
1545             gst_pad_event_default (enc->sinkpad, GST_OBJECT_CAST (enc), event);
1546       } else {
1547         GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1548         enc->priv->pending_events =
1549             g_list_append (enc->priv->pending_events, event);
1550         GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1551         res = TRUE;
1552       }
1553       break;
1554   }
1555   return res;
1556 }
1557
1558 static gboolean
1559 gst_audio_encoder_sink_event (GstPad * pad, GstObject * parent,
1560     GstEvent * event)
1561 {
1562   GstAudioEncoder *enc;
1563   GstAudioEncoderClass *klass;
1564   gboolean ret;
1565
1566   enc = GST_AUDIO_ENCODER (parent);
1567   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1568
1569   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1570       GST_EVENT_TYPE_NAME (event));
1571
1572   if (klass->sink_event)
1573     ret = klass->sink_event (enc, event);
1574   else {
1575     gst_event_unref (event);
1576     ret = FALSE;
1577   }
1578
1579   GST_DEBUG_OBJECT (enc, "event result %d", ret);
1580
1581   return ret;
1582 }
1583
1584 static gboolean
1585 gst_audio_encoder_sink_query (GstPad * pad, GstObject * parent,
1586     GstQuery * query)
1587 {
1588   gboolean res = FALSE;
1589   GstAudioEncoder *enc;
1590
1591   enc = GST_AUDIO_ENCODER (parent);
1592
1593   switch (GST_QUERY_TYPE (query)) {
1594     case GST_QUERY_FORMATS:
1595     {
1596       gst_query_set_formats (query, 3,
1597           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1598       res = TRUE;
1599       break;
1600     }
1601     case GST_QUERY_CONVERT:
1602     {
1603       GstFormat src_fmt, dest_fmt;
1604       gint64 src_val, dest_val;
1605
1606       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1607       if (!(res = gst_audio_info_convert (&enc->priv->ctx.info,
1608                   src_fmt, src_val, dest_fmt, &dest_val)))
1609         goto error;
1610       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1611       res = TRUE;
1612       break;
1613     }
1614     case GST_QUERY_CAPS:
1615     {
1616       GstCaps *filter, *caps;
1617       GstAudioEncoderClass *klass;
1618
1619       gst_query_parse_caps (query, &filter);
1620
1621       klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1622       if (klass->getcaps) {
1623         caps = klass->getcaps (enc, filter);
1624         gst_query_set_caps_result (query, caps);
1625         gst_caps_unref (caps);
1626         res = TRUE;
1627       }
1628       break;
1629     }
1630     case GST_QUERY_ALLOCATION:
1631     {
1632       GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1633
1634       if (klass->propose_allocation)
1635         res = klass->propose_allocation (enc, query);
1636       break;
1637     }
1638     default:
1639       res = gst_pad_query_default (pad, parent, query);
1640       break;
1641   }
1642
1643 error:
1644   return res;
1645 }
1646
1647 static gboolean
1648 gst_audio_encoder_src_event_default (GstAudioEncoder * enc, GstEvent * event)
1649 {
1650   gboolean res;
1651
1652   switch (GST_EVENT_TYPE (event)) {
1653     default:
1654       res = gst_pad_event_default (enc->srcpad, GST_OBJECT_CAST (enc), event);
1655       break;
1656   }
1657   return res;
1658 }
1659
1660 static gboolean
1661 gst_audio_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1662 {
1663   GstAudioEncoder *enc;
1664   GstAudioEncoderClass *klass;
1665   gboolean ret;
1666
1667   enc = GST_AUDIO_ENCODER (parent);
1668   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1669
1670   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1671       GST_EVENT_TYPE_NAME (event));
1672
1673   if (klass->src_event)
1674     ret = klass->src_event (enc, event);
1675   else {
1676     gst_event_unref (event);
1677     ret = FALSE;
1678   }
1679
1680   return ret;
1681 }
1682
1683 static gboolean
1684 gst_audio_encoder_decide_allocation_default (GstAudioEncoder * enc,
1685     GstQuery * query)
1686 {
1687   GstAllocator *allocator = NULL;
1688   GstAllocationParams params;
1689   gboolean update_allocator;
1690
1691   /* we got configuration from our peer or the decide_allocation method,
1692    * parse them */
1693   if (gst_query_get_n_allocation_params (query) > 0) {
1694     /* try the allocator */
1695     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1696     update_allocator = TRUE;
1697   } else {
1698     allocator = NULL;
1699     gst_allocation_params_init (&params);
1700     update_allocator = FALSE;
1701   }
1702
1703   if (update_allocator)
1704     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
1705   else
1706     gst_query_add_allocation_param (query, allocator, &params);
1707   if (allocator)
1708     gst_object_unref (allocator);
1709
1710   return TRUE;
1711 }
1712
1713 static gboolean
1714 gst_audio_encoder_propose_allocation_default (GstAudioEncoder * enc,
1715     GstQuery * query)
1716 {
1717   return TRUE;
1718 }
1719
1720 /*
1721  * gst_audio_encoded_audio_convert:
1722  * @fmt: audio format of the encoded audio
1723  * @bytes: number of encoded bytes
1724  * @samples: number of encoded samples
1725  * @src_format: source format
1726  * @src_value: source value
1727  * @dest_format: destination format
1728  * @dest_value: destination format
1729  *
1730  * Helper function to convert @src_value in @src_format to @dest_value in
1731  * @dest_format for encoded audio data.  Conversion is possible between
1732  * BYTE and TIME format by using estimated bitrate based on
1733  * @samples and @bytes (and @fmt).
1734  */
1735 /* FIXME: make gst_audio_encoded_audio_convert() public? */
1736 static gboolean
1737 gst_audio_encoded_audio_convert (GstAudioInfo * fmt,
1738     gint64 bytes, gint64 samples, GstFormat src_format,
1739     gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
1740 {
1741   gboolean res = FALSE;
1742
1743   g_return_val_if_fail (dest_format != NULL, FALSE);
1744   g_return_val_if_fail (dest_value != NULL, FALSE);
1745
1746   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
1747           src_value == -1)) {
1748     if (dest_value)
1749       *dest_value = src_value;
1750     return TRUE;
1751   }
1752
1753   if (samples == 0 || bytes == 0 || fmt->rate == 0) {
1754     GST_DEBUG ("not enough metadata yet to convert");
1755     goto exit;
1756   }
1757
1758   bytes *= fmt->rate;
1759
1760   switch (src_format) {
1761     case GST_FORMAT_BYTES:
1762       switch (*dest_format) {
1763         case GST_FORMAT_TIME:
1764           *dest_value = gst_util_uint64_scale (src_value,
1765               GST_SECOND * samples, bytes);
1766           res = TRUE;
1767           break;
1768         default:
1769           res = FALSE;
1770       }
1771       break;
1772     case GST_FORMAT_TIME:
1773       switch (*dest_format) {
1774         case GST_FORMAT_BYTES:
1775           *dest_value = gst_util_uint64_scale (src_value, bytes,
1776               samples * GST_SECOND);
1777           res = TRUE;
1778           break;
1779         default:
1780           res = FALSE;
1781       }
1782       break;
1783     default:
1784       res = FALSE;
1785   }
1786
1787 exit:
1788   return res;
1789 }
1790
1791 /* FIXME ? are any of these queries (other than latency) an encoder's business
1792  * also, the conversion stuff might seem to make sense, but seems to not mind
1793  * segment stuff etc at all
1794  * Supposedly that's backward compatibility ... */
1795 static gboolean
1796 gst_audio_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
1797 {
1798   GstAudioEncoder *enc;
1799   gboolean res = FALSE;
1800
1801   enc = GST_AUDIO_ENCODER (parent);
1802
1803   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1804
1805   switch (GST_QUERY_TYPE (query)) {
1806     case GST_QUERY_POSITION:
1807     {
1808       GstFormat fmt, req_fmt;
1809       gint64 pos, val;
1810
1811       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1812         GST_LOG_OBJECT (enc, "returning peer response");
1813         break;
1814       }
1815
1816       gst_query_parse_position (query, &req_fmt, NULL);
1817       fmt = GST_FORMAT_TIME;
1818       if (!(res = gst_pad_peer_query_position (enc->sinkpad, fmt, &pos)))
1819         break;
1820
1821       if ((res =
1822               gst_pad_peer_query_convert (enc->sinkpad, fmt, pos, req_fmt,
1823                   &val))) {
1824         gst_query_set_position (query, req_fmt, val);
1825       }
1826       break;
1827     }
1828     case GST_QUERY_DURATION:
1829     {
1830       GstFormat fmt, req_fmt;
1831       gint64 dur, val;
1832
1833       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1834         GST_LOG_OBJECT (enc, "returning peer response");
1835         break;
1836       }
1837
1838       gst_query_parse_duration (query, &req_fmt, NULL);
1839       fmt = GST_FORMAT_TIME;
1840       if (!(res = gst_pad_peer_query_duration (enc->sinkpad, fmt, &dur)))
1841         break;
1842
1843       if ((res =
1844               gst_pad_peer_query_convert (enc->sinkpad, fmt, dur, req_fmt,
1845                   &val))) {
1846         gst_query_set_duration (query, req_fmt, val);
1847       }
1848       break;
1849     }
1850     case GST_QUERY_FORMATS:
1851     {
1852       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1853       res = TRUE;
1854       break;
1855     }
1856     case GST_QUERY_CONVERT:
1857     {
1858       GstFormat src_fmt, dest_fmt;
1859       gint64 src_val, dest_val;
1860
1861       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1862       if (!(res = gst_audio_encoded_audio_convert (&enc->priv->ctx.info,
1863                   enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
1864                   &dest_fmt, &dest_val)))
1865         break;
1866       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1867       break;
1868     }
1869     case GST_QUERY_LATENCY:
1870     {
1871       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1872         gboolean live;
1873         GstClockTime min_latency, max_latency;
1874
1875         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1876         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1877             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1878             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1879
1880         GST_OBJECT_LOCK (enc);
1881         /* add our latency */
1882         if (min_latency != -1)
1883           min_latency += enc->priv->ctx.min_latency;
1884         if (max_latency != -1)
1885           max_latency += enc->priv->ctx.max_latency;
1886         GST_OBJECT_UNLOCK (enc);
1887
1888         gst_query_set_latency (query, live, min_latency, max_latency);
1889       }
1890       break;
1891     }
1892     default:
1893       res = gst_pad_query_default (pad, parent, query);
1894       break;
1895   }
1896
1897   return res;
1898 }
1899
1900 static void
1901 gst_audio_encoder_set_property (GObject * object, guint prop_id,
1902     const GValue * value, GParamSpec * pspec)
1903 {
1904   GstAudioEncoder *enc;
1905
1906   enc = GST_AUDIO_ENCODER (object);
1907
1908   switch (prop_id) {
1909     case PROP_PERFECT_TS:
1910       if (enc->priv->granule && !g_value_get_boolean (value))
1911         GST_WARNING_OBJECT (enc, "perfect-timestamp can not be set FALSE "
1912             "while granule handling is enabled");
1913       else
1914         enc->priv->perfect_ts = g_value_get_boolean (value);
1915       break;
1916     case PROP_HARD_RESYNC:
1917       enc->priv->hard_resync = g_value_get_boolean (value);
1918       break;
1919     case PROP_TOLERANCE:
1920       enc->priv->tolerance = g_value_get_int64 (value);
1921       break;
1922     default:
1923       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1924       break;
1925   }
1926 }
1927
1928 static void
1929 gst_audio_encoder_get_property (GObject * object, guint prop_id,
1930     GValue * value, GParamSpec * pspec)
1931 {
1932   GstAudioEncoder *enc;
1933
1934   enc = GST_AUDIO_ENCODER (object);
1935
1936   switch (prop_id) {
1937     case PROP_PERFECT_TS:
1938       g_value_set_boolean (value, enc->priv->perfect_ts);
1939       break;
1940     case PROP_GRANULE:
1941       g_value_set_boolean (value, enc->priv->granule);
1942       break;
1943     case PROP_HARD_RESYNC:
1944       g_value_set_boolean (value, enc->priv->hard_resync);
1945       break;
1946     case PROP_TOLERANCE:
1947       g_value_set_int64 (value, enc->priv->tolerance);
1948       break;
1949     default:
1950       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1951       break;
1952   }
1953 }
1954
1955 static gboolean
1956 gst_audio_encoder_activate (GstAudioEncoder * enc, gboolean active)
1957 {
1958   GstAudioEncoderClass *klass;
1959   gboolean result = TRUE;
1960
1961   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1962
1963   g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE);
1964
1965   GST_DEBUG_OBJECT (enc, "activate %d", active);
1966
1967   if (active) {
1968
1969     if (enc->priv->tags)
1970       gst_tag_list_unref (enc->priv->tags);
1971     enc->priv->tags = gst_tag_list_new_empty ();
1972     enc->priv->tags_changed = FALSE;
1973
1974     if (!enc->priv->active && klass->start)
1975       result = klass->start (enc);
1976   } else {
1977     /* We must make sure streaming has finished before resetting things
1978      * and calling the ::stop vfunc */
1979     GST_PAD_STREAM_LOCK (enc->sinkpad);
1980     GST_PAD_STREAM_UNLOCK (enc->sinkpad);
1981
1982     if (enc->priv->active && klass->stop)
1983       result = klass->stop (enc);
1984
1985     /* clean up */
1986     gst_audio_encoder_reset (enc, TRUE);
1987   }
1988   GST_DEBUG_OBJECT (enc, "activate return: %d", result);
1989   return result;
1990 }
1991
1992
1993 static gboolean
1994 gst_audio_encoder_sink_activate_mode (GstPad * pad, GstObject * parent,
1995     GstPadMode mode, gboolean active)
1996 {
1997   gboolean result = TRUE;
1998   GstAudioEncoder *enc;
1999
2000   enc = GST_AUDIO_ENCODER (parent);
2001
2002   GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
2003
2004   result = gst_audio_encoder_activate (enc, active);
2005
2006   if (result)
2007     enc->priv->active = active;
2008
2009   GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
2010
2011   return result;
2012 }
2013
2014 /**
2015  * gst_audio_encoder_get_audio_info:
2016  * @enc: a #GstAudioEncoder
2017  *
2018  * Returns: a #GstAudioInfo describing the input audio format
2019  */
2020 GstAudioInfo *
2021 gst_audio_encoder_get_audio_info (GstAudioEncoder * enc)
2022 {
2023   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), NULL);
2024
2025   return &enc->priv->ctx.info;
2026 }
2027
2028 /**
2029  * gst_audio_encoder_set_frame_samples_min:
2030  * @enc: a #GstAudioEncoder
2031  * @num: number of samples per frame
2032  *
2033  * Sets number of samples (per channel) subclass needs to be handed,
2034  * at least or will be handed all available if 0.
2035  *
2036  * If an exact number of samples is required, gst_audio_encoder_set_frame_samples_max()
2037  * must be called with the same number.
2038  */
2039 void
2040 gst_audio_encoder_set_frame_samples_min (GstAudioEncoder * enc, gint num)
2041 {
2042   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2043
2044   enc->priv->ctx.frame_samples_min = num;
2045 }
2046
2047 /**
2048  * gst_audio_encoder_get_frame_samples_min:
2049  * @enc: a #GstAudioEncoder
2050  *
2051  * Returns: currently minimum requested samples per frame
2052  */
2053 gint
2054 gst_audio_encoder_get_frame_samples_min (GstAudioEncoder * enc)
2055 {
2056   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2057
2058   return enc->priv->ctx.frame_samples_min;
2059 }
2060
2061 /**
2062  * gst_audio_encoder_set_frame_samples_max:
2063  * @enc: a #GstAudioEncoder
2064  * @num: number of samples per frame
2065  *
2066  * Sets number of samples (per channel) subclass needs to be handed,
2067  * at most or will be handed all available if 0.
2068  *
2069  * If an exact number of samples is required, gst_audio_encoder_set_frame_samples_min()
2070  * must be called with the same number.
2071  */
2072 void
2073 gst_audio_encoder_set_frame_samples_max (GstAudioEncoder * enc, gint num)
2074 {
2075   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2076
2077   enc->priv->ctx.frame_samples_max = num;
2078 }
2079
2080 /**
2081  * gst_audio_encoder_get_frame_samples_max:
2082  * @enc: a #GstAudioEncoder
2083  *
2084  * Returns: currently maximum requested samples per frame
2085  */
2086 gint
2087 gst_audio_encoder_get_frame_samples_max (GstAudioEncoder * enc)
2088 {
2089   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2090
2091   return enc->priv->ctx.frame_samples_max;
2092 }
2093
2094 /**
2095  * gst_audio_encoder_set_frame_max:
2096  * @enc: a #GstAudioEncoder
2097  * @num: number of frames
2098  *
2099  * Sets max number of frames accepted at once (assumed minimally 1).
2100  * Requires @frame_samples_min and @frame_samples_max to be the equal.
2101  */
2102 void
2103 gst_audio_encoder_set_frame_max (GstAudioEncoder * enc, gint num)
2104 {
2105   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2106
2107   enc->priv->ctx.frame_max = num;
2108 }
2109
2110 /**
2111  * gst_audio_encoder_get_frame_max:
2112  * @enc: a #GstAudioEncoder
2113  *
2114  * Returns: currently configured maximum handled frames
2115  */
2116 gint
2117 gst_audio_encoder_get_frame_max (GstAudioEncoder * enc)
2118 {
2119   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2120
2121   return enc->priv->ctx.frame_max;
2122 }
2123
2124 /**
2125  * gst_audio_encoder_set_lookahead:
2126  * @enc: a #GstAudioEncoder
2127  * @num: lookahead
2128  *
2129  * Sets encoder lookahead (in units of input rate samples)
2130  */
2131 void
2132 gst_audio_encoder_set_lookahead (GstAudioEncoder * enc, gint num)
2133 {
2134   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2135
2136   enc->priv->ctx.lookahead = num;
2137 }
2138
2139 /**
2140  * gst_audio_encoder_get_lookahead:
2141  * @enc: a #GstAudioEncoder
2142  *
2143  * Returns: currently configured encoder lookahead
2144  */
2145 gint
2146 gst_audio_encoder_get_lookahead (GstAudioEncoder * enc)
2147 {
2148   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2149
2150   return enc->priv->ctx.lookahead;
2151 }
2152
2153 /**
2154  * gst_audio_encoder_set_latency:
2155  * @enc: a #GstAudioEncoder
2156  * @min: minimum latency
2157  * @max: maximum latency
2158  *
2159  * Sets encoder latency.
2160  */
2161 void
2162 gst_audio_encoder_set_latency (GstAudioEncoder * enc,
2163     GstClockTime min, GstClockTime max)
2164 {
2165   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2166
2167   GST_OBJECT_LOCK (enc);
2168   enc->priv->ctx.min_latency = min;
2169   enc->priv->ctx.max_latency = max;
2170   GST_OBJECT_UNLOCK (enc);
2171 }
2172
2173 /**
2174  * gst_audio_encoder_get_latency:
2175  * @enc: a #GstAudioEncoder
2176  * @min: (out) (allow-none): a pointer to storage to hold minimum latency
2177  * @max: (out) (allow-none): a pointer to storage to hold maximum latency
2178  *
2179  * Sets the variables pointed to by @min and @max to the currently configured
2180  * latency.
2181  */
2182 void
2183 gst_audio_encoder_get_latency (GstAudioEncoder * enc,
2184     GstClockTime * min, GstClockTime * max)
2185 {
2186   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2187
2188   GST_OBJECT_LOCK (enc);
2189   if (min)
2190     *min = enc->priv->ctx.min_latency;
2191   if (max)
2192     *max = enc->priv->ctx.max_latency;
2193   GST_OBJECT_UNLOCK (enc);
2194 }
2195
2196 /**
2197  * gst_audio_encoder_set_headers:
2198  * @enc: a #GstAudioEncoder
2199  * @headers: (transfer full) (element-type Gst.Buffer): a list of
2200  *   #GstBuffer containing the codec header
2201  *
2202  * Set the codec headers to be sent downstream whenever requested.
2203  */
2204 void
2205 gst_audio_encoder_set_headers (GstAudioEncoder * enc, GList * headers)
2206 {
2207   GST_DEBUG_OBJECT (enc, "new headers %p", headers);
2208
2209   if (enc->priv->ctx.headers) {
2210     g_list_foreach (enc->priv->ctx.headers, (GFunc) gst_buffer_unref, NULL);
2211     g_list_free (enc->priv->ctx.headers);
2212   }
2213   enc->priv->ctx.headers = headers;
2214   enc->priv->ctx.new_headers = TRUE;
2215 }
2216
2217 /**
2218  * gst_audio_encoder_set_mark_granule:
2219  * @enc: a #GstAudioEncoder
2220  * @enabled: new state
2221  *
2222  * Enable or disable encoder granule handling.
2223  *
2224  * MT safe.
2225  */
2226 void
2227 gst_audio_encoder_set_mark_granule (GstAudioEncoder * enc, gboolean enabled)
2228 {
2229   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2230
2231   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2232
2233   GST_OBJECT_LOCK (enc);
2234   enc->priv->granule = enabled;
2235   GST_OBJECT_UNLOCK (enc);
2236 }
2237
2238 /**
2239  * gst_audio_encoder_get_mark_granule:
2240  * @enc: a #GstAudioEncoder
2241  *
2242  * Queries if the encoder will handle granule marking.
2243  *
2244  * Returns: TRUE if granule marking is enabled.
2245  *
2246  * MT safe.
2247  */
2248 gboolean
2249 gst_audio_encoder_get_mark_granule (GstAudioEncoder * enc)
2250 {
2251   gboolean result;
2252
2253   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2254
2255   GST_OBJECT_LOCK (enc);
2256   result = enc->priv->granule;
2257   GST_OBJECT_UNLOCK (enc);
2258
2259   return result;
2260 }
2261
2262 /**
2263  * gst_audio_encoder_set_perfect_timestamp:
2264  * @enc: a #GstAudioEncoder
2265  * @enabled: new state
2266  *
2267  * Enable or disable encoder perfect output timestamp preference.
2268  *
2269  * MT safe.
2270  */
2271 void
2272 gst_audio_encoder_set_perfect_timestamp (GstAudioEncoder * enc,
2273     gboolean enabled)
2274 {
2275   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2276
2277   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2278
2279   GST_OBJECT_LOCK (enc);
2280   enc->priv->perfect_ts = enabled;
2281   GST_OBJECT_UNLOCK (enc);
2282 }
2283
2284 /**
2285  * gst_audio_encoder_get_perfect_timestamp:
2286  * @enc: a #GstAudioEncoder
2287  *
2288  * Queries encoder perfect timestamp behaviour.
2289  *
2290  * Returns: TRUE if perfect timestamp setting enabled.
2291  *
2292  * MT safe.
2293  */
2294 gboolean
2295 gst_audio_encoder_get_perfect_timestamp (GstAudioEncoder * enc)
2296 {
2297   gboolean result;
2298
2299   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2300
2301   GST_OBJECT_LOCK (enc);
2302   result = enc->priv->perfect_ts;
2303   GST_OBJECT_UNLOCK (enc);
2304
2305   return result;
2306 }
2307
2308 /**
2309  * gst_audio_encoder_set_hard_sync:
2310  * @enc: a #GstAudioEncoder
2311  * @enabled: new state
2312  *
2313  * Sets encoder hard resync handling.
2314  *
2315  * MT safe.
2316  */
2317 void
2318 gst_audio_encoder_set_hard_resync (GstAudioEncoder * enc, gboolean enabled)
2319 {
2320   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2321
2322   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2323
2324   GST_OBJECT_LOCK (enc);
2325   enc->priv->hard_resync = enabled;
2326   GST_OBJECT_UNLOCK (enc);
2327 }
2328
2329 /**
2330  * gst_audio_encoder_get_hard_sync:
2331  * @enc: a #GstAudioEncoder
2332  *
2333  * Queries encoder's hard resync setting.
2334  *
2335  * Returns: TRUE if hard resync is enabled.
2336  *
2337  * MT safe.
2338  */
2339 gboolean
2340 gst_audio_encoder_get_hard_resync (GstAudioEncoder * enc)
2341 {
2342   gboolean result;
2343
2344   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2345
2346   GST_OBJECT_LOCK (enc);
2347   result = enc->priv->hard_resync;
2348   GST_OBJECT_UNLOCK (enc);
2349
2350   return result;
2351 }
2352
2353 /**
2354  * gst_audio_encoder_set_tolerance:
2355  * @enc: a #GstAudioEncoder
2356  * @tolerance: new tolerance
2357  *
2358  * Configures encoder audio jitter tolerance threshold.
2359  *
2360  * MT safe.
2361  */
2362 void
2363 gst_audio_encoder_set_tolerance (GstAudioEncoder * enc, GstClockTime tolerance)
2364 {
2365   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2366
2367   GST_OBJECT_LOCK (enc);
2368   enc->priv->tolerance = tolerance;
2369   GST_OBJECT_UNLOCK (enc);
2370 }
2371
2372 /**
2373  * gst_audio_encoder_get_tolerance:
2374  * @enc: a #GstAudioEncoder
2375  *
2376  * Queries current audio jitter tolerance threshold.
2377  *
2378  * Returns: encoder audio jitter tolerance threshold.
2379  *
2380  * MT safe.
2381  */
2382 GstClockTime
2383 gst_audio_encoder_get_tolerance (GstAudioEncoder * enc)
2384 {
2385   GstClockTime result;
2386
2387   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2388
2389   GST_OBJECT_LOCK (enc);
2390   result = enc->priv->tolerance;
2391   GST_OBJECT_UNLOCK (enc);
2392
2393   return result;
2394 }
2395
2396 /**
2397  * gst_audio_encoder_set_hard_min:
2398  * @enc: a #GstAudioEncoder
2399  * @enabled: new state
2400  *
2401  * Configures encoder hard minimum handling.  If enabled, subclass
2402  * will never be handed less samples than it configured, which otherwise
2403  * might occur near end-of-data handling.  Instead, the leftover samples
2404  * will simply be discarded.
2405  *
2406  * MT safe.
2407  */
2408 void
2409 gst_audio_encoder_set_hard_min (GstAudioEncoder * enc, gboolean enabled)
2410 {
2411   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2412
2413   GST_OBJECT_LOCK (enc);
2414   enc->priv->hard_min = enabled;
2415   GST_OBJECT_UNLOCK (enc);
2416 }
2417
2418 /**
2419  * gst_audio_encoder_get_hard_min:
2420  * @enc: a #GstAudioEncoder
2421  *
2422  * Queries encoder hard minimum handling.
2423  *
2424  * Returns: TRUE if hard minimum handling is enabled.
2425  *
2426  * MT safe.
2427  */
2428 gboolean
2429 gst_audio_encoder_get_hard_min (GstAudioEncoder * enc)
2430 {
2431   gboolean result;
2432
2433   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2434
2435   GST_OBJECT_LOCK (enc);
2436   result = enc->priv->hard_min;
2437   GST_OBJECT_UNLOCK (enc);
2438
2439   return result;
2440 }
2441
2442 /**
2443  * gst_audio_encoder_set_drainable:
2444  * @enc: a #GstAudioEncoder
2445  * @enabled: new state
2446  *
2447  * Configures encoder drain handling.  If drainable, subclass might
2448  * be handed a NULL buffer to have it return any leftover encoded data.
2449  * Otherwise, it is not considered so capable and will only ever be passed
2450  * real data.
2451  *
2452  * MT safe.
2453  */
2454 void
2455 gst_audio_encoder_set_drainable (GstAudioEncoder * enc, gboolean enabled)
2456 {
2457   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2458
2459   GST_OBJECT_LOCK (enc);
2460   enc->priv->drainable = enabled;
2461   GST_OBJECT_UNLOCK (enc);
2462 }
2463
2464 /**
2465  * gst_audio_encoder_get_drainable:
2466  * @enc: a #GstAudioEncoder
2467  *
2468  * Queries encoder drain handling.
2469  *
2470  * Returns: TRUE if drainable handling is enabled.
2471  *
2472  * MT safe.
2473  */
2474 gboolean
2475 gst_audio_encoder_get_drainable (GstAudioEncoder * enc)
2476 {
2477   gboolean result;
2478
2479   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2480
2481   GST_OBJECT_LOCK (enc);
2482   result = enc->priv->drainable;
2483   GST_OBJECT_UNLOCK (enc);
2484
2485   return result;
2486 }
2487
2488 /**
2489  * gst_audio_encoder_merge_tags:
2490  * @enc: a #GstAudioEncoder
2491  * @tags: a #GstTagList to merge
2492  * @mode: the #GstTagMergeMode to use
2493  *
2494  * Adds tags to so-called pending tags, which will be processed
2495  * before pushing out data downstream.
2496  *
2497  * Note that this is provided for convenience, and the subclass is
2498  * not required to use this and can still do tag handling on its own,
2499  * although it should be aware that baseclass already takes care
2500  * of the usual CODEC/AUDIO_CODEC tags.
2501  *
2502  * MT safe.
2503  */
2504 void
2505 gst_audio_encoder_merge_tags (GstAudioEncoder * enc,
2506     const GstTagList * tags, GstTagMergeMode mode)
2507 {
2508   GstTagList *otags;
2509
2510   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2511   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2512
2513   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2514   if (tags)
2515     GST_DEBUG_OBJECT (enc, "merging tags %" GST_PTR_FORMAT, tags);
2516   otags = enc->priv->tags;
2517   enc->priv->tags = gst_tag_list_merge (enc->priv->tags, tags, mode);
2518   if (otags)
2519     gst_tag_list_unref (otags);
2520   enc->priv->tags_changed = TRUE;
2521   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2522 }
2523
2524 static gboolean
2525 gst_audio_encoder_negotiate_default (GstAudioEncoder * enc)
2526 {
2527   GstAudioEncoderClass *klass;
2528   gboolean res = FALSE;
2529   GstQuery *query = NULL;
2530   GstAllocator *allocator;
2531   GstAllocationParams params;
2532   GstCaps *caps;
2533
2534   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2535   g_return_val_if_fail (GST_IS_CAPS (enc->priv->ctx.caps), FALSE);
2536
2537   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2538
2539   caps = enc->priv->ctx.caps;
2540
2541   GST_DEBUG_OBJECT (enc, "Setting srcpad caps %" GST_PTR_FORMAT, caps);
2542
2543   res = gst_pad_set_caps (enc->srcpad, caps);
2544   if (!res)
2545     goto done;
2546   enc->priv->ctx.output_caps_changed = FALSE;
2547
2548   query = gst_query_new_allocation (caps, TRUE);
2549   if (!gst_pad_peer_query (enc->srcpad, query)) {
2550     GST_DEBUG_OBJECT (enc, "didn't get downstream ALLOCATION hints");
2551   }
2552
2553   g_assert (klass->decide_allocation != NULL);
2554   res = klass->decide_allocation (enc, query);
2555
2556   GST_DEBUG_OBJECT (enc, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, res,
2557       query);
2558
2559   if (!res)
2560     goto no_decide_allocation;
2561
2562   /* we got configuration from our peer or the decide_allocation method,
2563    * parse them */
2564   if (gst_query_get_n_allocation_params (query) > 0) {
2565     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2566   } else {
2567     allocator = NULL;
2568     gst_allocation_params_init (&params);
2569   }
2570
2571   if (enc->priv->ctx.allocator)
2572     gst_object_unref (enc->priv->ctx.allocator);
2573   enc->priv->ctx.allocator = allocator;
2574   enc->priv->ctx.params = params;
2575
2576 done:
2577   if (query)
2578     gst_query_unref (query);
2579
2580   return res;
2581
2582   /* ERRORS */
2583 no_decide_allocation:
2584   {
2585     GST_WARNING_OBJECT (enc, "Subclass failed to decide allocation");
2586     goto done;
2587   }
2588 }
2589
2590 /**
2591  * gst_audio_encoder_negotiate:
2592  * @enc: a #GstAudioEncoder
2593  *
2594  * Negotiate with downstreame elements to currently configured #GstCaps.
2595  *
2596  * Returns: #TRUE if the negotiation succeeded, else #FALSE.
2597  */
2598 gboolean
2599 gst_audio_encoder_negotiate (GstAudioEncoder * enc)
2600 {
2601   GstAudioEncoderClass *klass;
2602   gboolean ret = TRUE;
2603
2604   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2605
2606   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2607
2608   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2609   if (klass->negotiate)
2610     ret = klass->negotiate (enc);
2611   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2612
2613   return ret;
2614 }
2615
2616 /*
2617  * gst_audio_encoder_set_output_format:
2618  * @enc: a #GstAudioEncoder
2619  * @caps: #GstCaps
2620  *
2621  * Configure output caps on the srcpad of @enc.
2622  *
2623  * Returns: %TRUE on success.
2624  **/
2625 gboolean
2626 gst_audio_encoder_set_output_format (GstAudioEncoder * enc, GstCaps * caps)
2627 {
2628   gboolean res = TRUE;
2629   GstCaps *templ_caps;
2630
2631   GST_DEBUG_OBJECT (enc, "Setting srcpad caps %" GST_PTR_FORMAT, caps);
2632
2633   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2634   if (!gst_caps_is_fixed (caps))
2635     goto refuse_caps;
2636
2637   /* Only allow caps that are a subset of the template caps */
2638   templ_caps = gst_pad_get_pad_template_caps (enc->srcpad);
2639   if (!gst_caps_is_subset (caps, templ_caps)) {
2640     gst_caps_unref (templ_caps);
2641     goto refuse_caps;
2642   }
2643   gst_caps_unref (templ_caps);
2644
2645   gst_caps_replace (&enc->priv->ctx.caps, caps);
2646   enc->priv->ctx.output_caps_changed = TRUE;
2647
2648 done:
2649   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2650
2651   return res;
2652
2653   /* ERRORS */
2654 refuse_caps:
2655   {
2656     GST_WARNING_OBJECT (enc, "refused caps %" GST_PTR_FORMAT, caps);
2657     res = FALSE;
2658     goto done;
2659   }
2660 }
2661
2662 /**
2663  * gst_audio_encoder_allocate_output_buffer:
2664  * @enc: a #GstAudioEncoder
2665  * @size: size of the buffer
2666  *
2667  * Helper function that allocates a buffer to hold an encoded audio frame
2668  * for @enc's current output format.
2669  *
2670  * Returns: (transfer full): allocated buffer
2671  */
2672 GstBuffer *
2673 gst_audio_encoder_allocate_output_buffer (GstAudioEncoder * enc, gsize size)
2674 {
2675   GstBuffer *buffer = NULL;
2676
2677   g_return_val_if_fail (size > 0, NULL);
2678
2679   GST_DEBUG ("alloc src buffer");
2680
2681   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2682
2683   if (G_UNLIKELY (enc->priv->ctx.output_caps_changed || (enc->priv->ctx.caps
2684               && gst_pad_check_reconfigure (enc->srcpad)))) {
2685     if (!gst_audio_encoder_negotiate (enc))
2686       goto done;
2687   }
2688
2689   buffer =
2690       gst_buffer_new_allocate (enc->priv->ctx.allocator, size,
2691       &enc->priv->ctx.params);
2692
2693 done:
2694   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2695
2696   return buffer;
2697 }
2698
2699 /**
2700  * gst_audio_encoder_get_allocator:
2701  * @enc: a #GstAudioEncoder
2702  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
2703  * used
2704  * @params: (out) (allow-none) (transfer full): the
2705  * #GstAllocatorParams of @allocator
2706  *
2707  * Lets #GstAudioEncoder sub-classes to know the memory @allocator
2708  * used by the base class and its @params.
2709  *
2710  * Unref the @allocator after use it.
2711  */
2712 void
2713 gst_audio_encoder_get_allocator (GstAudioEncoder * enc,
2714     GstAllocator ** allocator, GstAllocationParams * params)
2715 {
2716   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2717
2718   if (allocator)
2719     *allocator = enc->priv->ctx.allocator ?
2720         gst_object_ref (enc->priv->ctx.allocator) : NULL;
2721
2722   if (params)
2723     *params = enc->priv->ctx.params;
2724 }