Merge branch 'master' into 0.11
[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  * @since: 0.10.36
27  *
28  * This base class is for audio encoders turning raw audio samples into
29  * encoded audio data.
30  *
31  * GstAudioEncoder and subclass should cooperate as follows.
32  * <orderedlist>
33  * <listitem>
34  *   <itemizedlist><title>Configuration</title>
35  *   <listitem><para>
36  *     Initially, GstAudioEncoder calls @start when the encoder element
37  *     is activated, which allows subclass to perform any global setup.
38  *   </para></listitem>
39  *   <listitem><para>
40  *     GstAudioEncoder calls @set_format to inform subclass of the format
41  *     of input audio data that it is about to receive.  Subclass should
42  *     setup for encoding and configure various base class parameters
43  *     appropriately, notably those directing desired input data handling.
44  *     While unlikely, it might be called more than once, if changing input
45  *     parameters require reconfiguration.
46  *   </para></listitem>
47  *   <listitem><para>
48  *     GstAudioEncoder calls @stop at end of all processing.
49  *   </para></listitem>
50  *   </itemizedlist>
51  * </listitem>
52  * As of configuration stage, and throughout processing, GstAudioEncoder
53  * maintains various parameters that provide required context,
54  * e.g. describing the format of input audio data.
55  * Conversely, subclass can and should configure these context parameters
56  * to inform base class of its expectation w.r.t. buffer handling.
57  * <listitem>
58  *   <itemizedlist>
59  *   <title>Data processing</title>
60  *     <listitem><para>
61  *       Base class gathers input sample data (as directed by the context's
62  *       frame_samples and frame_max) and provides this to subclass' @handle_frame.
63  *     </para></listitem>
64  *     <listitem><para>
65  *       If codec processing results in encoded data, subclass should call
66  *       @gst_audio_encoder_finish_frame to have encoded data pushed
67  *       downstream.  Alternatively, it might also call to indicate dropped
68  *       (non-encoded) samples.
69  *     </para></listitem>
70  *     <listitem><para>
71  *       Just prior to actually pushing a buffer downstream,
72  *       it is passed to @pre_push.
73  *     </para></listitem>
74  *     <listitem><para>
75  *       During the parsing process GstAudioEncoderClass will handle both
76  *       srcpad and sinkpad events. Sink events will be passed to subclass
77  *       if @event callback has been provided.
78  *     </para></listitem>
79  *   </itemizedlist>
80  * </listitem>
81  * <listitem>
82  *   <itemizedlist><title>Shutdown phase</title>
83  *   <listitem><para>
84  *     GstAudioEncoder class calls @stop to inform the subclass that data
85  *     parsing will be stopped.
86  *   </para></listitem>
87  *   </itemizedlist>
88  * </listitem>
89  * </orderedlist>
90  *
91  * Subclass is responsible for providing pad template caps for
92  * source and sink pads. The pads need to be named "sink" and "src". It also 
93  * needs to set the fixed caps on srcpad, when the format is ensured.  This
94  * is typically when base class calls subclass' @set_format function, though
95  * it might be delayed until calling @gst_audio_encoder_finish_frame.
96  *
97  * In summary, above process should have subclass concentrating on
98  * codec data processing while leaving other matters to base class,
99  * such as most notably timestamp handling.  While it may exert more control
100  * in this area (see e.g. @pre_push), it is very much not recommended.
101  *
102  * In particular, base class will either favor tracking upstream timestamps
103  * (at the possible expense of jitter) or aim to arrange for a perfect stream of
104  * output timestamps, depending on #GstAudioEncoder:perfect-timestamp.
105  * However, in the latter case, the input may not be so perfect or ideal, which
106  * is handled as follows.  An input timestamp is compared with the expected
107  * timestamp as dictated by input sample stream and if the deviation is less
108  * than #GstAudioEncoder:tolerance, the deviation is discarded.
109  * Otherwise, it is considered a discontuinity and subsequent output timestamp
110  * is resynced to the new position after performing configured discontinuity
111  * processing.  In the non-perfect-timestamp case, an upstream variation
112  * exceeding tolerance only leads to marking DISCONT on subsequent outgoing
113  * (while timestamps are adjusted to upstream regardless of variation).
114  * While DISCONT is also marked in the perfect-timestamp case, this one
115  * optionally (see #GstAudioEncoder:hard-resync)
116  * performs some additional steps, such as clipping of (early) input samples
117  * or draining all currently remaining input data, depending on the direction
118  * of the discontuinity.
119  *
120  * If perfect timestamps are arranged, it is also possible to request baseclass
121  * (usually set by subclass) to provide additional buffer metadata (in OFFSET
122  * and OFFSET_END) fields according to granule defined semantics currently
123  * needed by oggmux.  Specifically, OFFSET is set to granulepos (= sample count
124  * including buffer) and OFFSET_END to corresponding timestamp (as determined
125  * by same sample count and sample rate).
126  *
127  * Things that subclass need to take care of:
128  * <itemizedlist>
129  *   <listitem><para>Provide pad templates</para></listitem>
130  *   <listitem><para>
131  *      Set source pad caps when appropriate
132  *   </para></listitem>
133  *   <listitem><para>
134  *      Inform base class of buffer processing needs using context's
135  *      frame_samples and frame_bytes.
136  *   </para></listitem>
137  *   <listitem><para>
138  *      Set user-configurable properties to sane defaults for format and
139  *      implementing codec at hand, e.g. those controlling timestamp behaviour
140  *      and discontinuity processing.
141  *   </para></listitem>
142  *   <listitem><para>
143  *      Accept data in @handle_frame and provide encoded results to
144  *      @gst_audio_encoder_finish_frame.
145  *   </para></listitem>
146  * </itemizedlist>
147  *
148  */
149
150 #ifdef HAVE_CONFIG_H
151 #  include "config.h"
152 #endif
153
154 #include "gstaudioencoder.h"
155 #include <gst/base/gstadapter.h>
156 #include <gst/audio/audio.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
183 typedef struct _GstAudioEncoderContext
184 {
185   /* input */
186   GstAudioInfo info;
187
188   /* output */
189   gint frame_samples;
190   gint frame_max;
191   gint lookahead;
192   /* MT-protected (with LOCK) */
193   GstClockTime min_latency;
194   GstClockTime max_latency;
195 } GstAudioEncoderContext;
196
197 struct _GstAudioEncoderPrivate
198 {
199   /* activation status */
200   gboolean active;
201
202   /* input base/first ts as basis for output ts;
203    * kept nearly constant for perfect_ts,
204    * otherwise resyncs to upstream ts */
205   GstClockTime base_ts;
206   /* corresponding base granulepos */
207   gint64 base_gp;
208   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
209   guint64 samples;
210
211   /* currently collected sample data */
212   GstAdapter *adapter;
213   /* offset in adapter up to which already supplied to encoder */
214   gint offset;
215   /* mark outgoing discont */
216   gboolean discont;
217   /* to guess duration of drained data */
218   GstClockTime last_duration;
219
220   /* subclass provided data in processing round */
221   gboolean got_data;
222   /* subclass gave all it could already */
223   gboolean drained;
224   /* subclass currently being forcibly drained */
225   gboolean force;
226
227   /* output bps estimatation */
228   /* global in samples seen */
229   guint64 samples_in;
230   /* global bytes sent out */
231   guint64 bytes_out;
232
233   /* context storage */
234   GstAudioEncoderContext ctx;
235
236   /* properties */
237   gint64 tolerance;
238   gboolean perfect_ts;
239   gboolean hard_resync;
240   gboolean granule;
241 };
242
243
244 static GstElementClass *parent_class = NULL;
245
246 static void gst_audio_encoder_class_init (GstAudioEncoderClass * klass);
247 static void gst_audio_encoder_init (GstAudioEncoder * parse,
248     GstAudioEncoderClass * klass);
249
250 GType
251 gst_audio_encoder_get_type (void)
252 {
253   static GType audio_encoder_type = 0;
254
255   if (!audio_encoder_type) {
256     static const GTypeInfo audio_encoder_info = {
257       sizeof (GstAudioEncoderClass),
258       (GBaseInitFunc) NULL,
259       (GBaseFinalizeFunc) NULL,
260       (GClassInitFunc) gst_audio_encoder_class_init,
261       NULL,
262       NULL,
263       sizeof (GstAudioEncoder),
264       0,
265       (GInstanceInitFunc) gst_audio_encoder_init,
266     };
267     const GInterfaceInfo preset_interface_info = {
268       NULL,                     /* interface_init */
269       NULL,                     /* interface_finalize */
270       NULL                      /* interface_data */
271     };
272
273     audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT,
274         "GstAudioEncoder", &audio_encoder_info, G_TYPE_FLAG_ABSTRACT);
275
276     g_type_add_interface_static (audio_encoder_type, GST_TYPE_PRESET,
277         &preset_interface_info);
278   }
279   return audio_encoder_type;
280 }
281
282 static void gst_audio_encoder_finalize (GObject * object);
283 static void gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full);
284
285 static void gst_audio_encoder_set_property (GObject * object,
286     guint prop_id, const GValue * value, GParamSpec * pspec);
287 static void gst_audio_encoder_get_property (GObject * object,
288     guint prop_id, GValue * value, GParamSpec * pspec);
289
290 static gboolean gst_audio_encoder_sink_activate_push (GstPad * pad,
291     gboolean active);
292
293 static gboolean gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event);
294 static gboolean gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc,
295     GstCaps * caps);
296 static GstFlowReturn gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer);
297 static gboolean gst_audio_encoder_src_query (GstPad * pad, GstQuery * query);
298 static gboolean gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query);
299 static const GstQueryType *gst_audio_encoder_get_query_types (GstPad * pad);
300 static GstCaps *gst_audio_encoder_sink_getcaps (GstPad * pad, GstCaps * filter);
301
302 static void
303 gst_audio_encoder_class_init (GstAudioEncoderClass * klass)
304 {
305   GObjectClass *gobject_class;
306
307   gobject_class = G_OBJECT_CLASS (klass);
308   parent_class = g_type_class_peek_parent (klass);
309
310   GST_DEBUG_CATEGORY_INIT (gst_audio_encoder_debug, "audioencoder", 0,
311       "audio encoder base class");
312
313   g_type_class_add_private (klass, sizeof (GstAudioEncoderPrivate));
314
315   gobject_class->set_property = gst_audio_encoder_set_property;
316   gobject_class->get_property = gst_audio_encoder_get_property;
317
318   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_audio_encoder_finalize);
319
320   /* properties */
321   g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
322       g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps",
323           "Favour perfect timestamps over tracking upstream timestamps",
324           DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325   g_object_class_install_property (gobject_class, PROP_GRANULE,
326       g_param_spec_boolean ("mark-granule", "Granule Marking",
327           "Apply granule semantics to buffer metadata (implies perfect-timestamp)",
328           DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
329   g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
330       g_param_spec_boolean ("hard-resync", "Hard Resync",
331           "Perform clipping and sample flushing upon discontinuity",
332           DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
333   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
334       g_param_spec_int64 ("tolerance", "Tolerance",
335           "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
336           0, G_MAXINT64, DEFAULT_TOLERANCE,
337           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338 }
339
340 static void
341 gst_audio_encoder_init (GstAudioEncoder * enc, GstAudioEncoderClass * bclass)
342 {
343   GstPadTemplate *pad_template;
344
345   GST_DEBUG_OBJECT (enc, "gst_audio_encoder_init");
346
347   enc->priv = GST_AUDIO_ENCODER_GET_PRIVATE (enc);
348
349   /* only push mode supported */
350   pad_template =
351       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
352   g_return_if_fail (pad_template != NULL);
353   enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
354   gst_pad_set_event_function (enc->sinkpad,
355       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_event));
356   gst_pad_set_getcaps_function (enc->sinkpad,
357       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_getcaps));
358   gst_pad_set_query_function (enc->sinkpad,
359       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_query));
360   gst_pad_set_chain_function (enc->sinkpad,
361       GST_DEBUG_FUNCPTR (gst_audio_encoder_chain));
362   gst_pad_set_activatepush_function (enc->sinkpad,
363       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_activate_push));
364   gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
365
366   GST_DEBUG_OBJECT (enc, "sinkpad created");
367
368   /* and we don't mind upstream traveling stuff that much ... */
369   pad_template =
370       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
371   g_return_if_fail (pad_template != NULL);
372   enc->srcpad = gst_pad_new_from_template (pad_template, "src");
373   gst_pad_set_query_function (enc->srcpad,
374       GST_DEBUG_FUNCPTR (gst_audio_encoder_src_query));
375   gst_pad_set_query_type_function (enc->srcpad,
376       GST_DEBUG_FUNCPTR (gst_audio_encoder_get_query_types));
377   gst_pad_use_fixed_caps (enc->srcpad);
378   gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
379   GST_DEBUG_OBJECT (enc, "src created");
380
381   enc->priv->adapter = gst_adapter_new ();
382
383   /* property default */
384   enc->priv->granule = DEFAULT_GRANULE;
385   enc->priv->perfect_ts = DEFAULT_PERFECT_TS;
386   enc->priv->hard_resync = DEFAULT_HARD_RESYNC;
387   enc->priv->tolerance = DEFAULT_TOLERANCE;
388
389   /* init state */
390   gst_audio_encoder_reset (enc, TRUE);
391   GST_DEBUG_OBJECT (enc, "init ok");
392 }
393
394 static void
395 gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full)
396 {
397   GST_OBJECT_LOCK (enc);
398
399   if (full) {
400     enc->priv->active = FALSE;
401     enc->priv->samples_in = 0;
402     enc->priv->bytes_out = 0;
403     gst_audio_info_init (&enc->priv->ctx.info);
404     memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx));
405   }
406
407   gst_segment_init (&enc->segment, GST_FORMAT_TIME);
408
409   gst_adapter_clear (enc->priv->adapter);
410   enc->priv->got_data = FALSE;
411   enc->priv->drained = TRUE;
412   enc->priv->offset = 0;
413   enc->priv->base_ts = GST_CLOCK_TIME_NONE;
414   enc->priv->base_gp = -1;
415   enc->priv->samples = 0;
416   enc->priv->discont = FALSE;
417
418   GST_OBJECT_UNLOCK (enc);
419 }
420
421 static void
422 gst_audio_encoder_finalize (GObject * object)
423 {
424   GstAudioEncoder *enc = GST_AUDIO_ENCODER (object);
425
426   g_object_unref (enc->priv->adapter);
427
428   G_OBJECT_CLASS (parent_class)->finalize (object);
429 }
430
431 /**
432  * gst_audio_encoder_finish_frame:
433  * @enc: a #GstAudioEncoder
434  * @buffer: encoded data
435  * @samples: number of samples (per channel) represented by encoded data
436  *
437  * Collects encoded data and/or pushes encoded data downstream.
438  * Source pad caps must be set when this is called.  Depending on the nature
439  * of the (framing of) the format, subclass can decide whether to push
440  * encoded data directly or to collect various "frames" in a single buffer.
441  * Note that the latter behaviour is recommended whenever the format is allowed,
442  * as it incurs no additional latency and avoids otherwise generating a
443  * a multitude of (small) output buffers.  If not explicitly pushed,
444  * any available encoded data is pushed at the end of each processing cycle,
445  * i.e. which encodes as much data as available input data allows.
446  *
447  * If @samples < 0, then best estimate is all samples provided to encoder
448  * (subclass) so far.  @buf may be NULL, in which case next number of @samples
449  * are considered discarded, e.g. as a result of discontinuous transmission,
450  * and a discontinuity is marked (note that @buf == NULL => push == TRUE).
451  *
452  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
453  *
454  * Since: 0.10.36
455  */
456 GstFlowReturn
457 gst_audio_encoder_finish_frame (GstAudioEncoder * enc, GstBuffer * buf,
458     gint samples)
459 {
460   GstAudioEncoderClass *klass;
461   GstAudioEncoderPrivate *priv;
462   GstAudioEncoderContext *ctx;
463   GstFlowReturn ret = GST_FLOW_OK;
464
465   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
466   priv = enc->priv;
467   ctx = &enc->priv->ctx;
468
469   /* subclass should know what it is producing by now */
470   g_return_val_if_fail (gst_pad_has_current_caps (enc->srcpad), GST_FLOW_ERROR);
471   /* subclass should not hand us no data */
472   g_return_val_if_fail (buf == NULL || gst_buffer_get_size (buf) > 0,
473       GST_FLOW_ERROR);
474
475   GST_LOG_OBJECT (enc, "accepting %d bytes encoded data as %d samples",
476       buf ? gst_buffer_get_size (buf) : -1, samples);
477
478   /* mark subclass still alive and providing */
479   priv->got_data = TRUE;
480
481   /* remove corresponding samples from input */
482   if (samples < 0)
483     samples = (enc->priv->offset / ctx->info.bpf);
484
485   if (G_LIKELY (samples)) {
486     /* track upstream ts if so configured */
487     if (!enc->priv->perfect_ts) {
488       guint64 ts, distance;
489
490       ts = gst_adapter_prev_timestamp (priv->adapter, &distance);
491       g_assert (distance % ctx->info.bpf == 0);
492       distance /= ctx->info.bpf;
493       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
494           GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
495       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
496           GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
497       /* when draining adapter might be empty and no ts to offer */
498       if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
499         GstClockTimeDiff diff;
500         GstClockTime old_ts, next_ts;
501
502         /* passed into another buffer;
503          * mild check for discontinuity and only mark if so */
504         next_ts = ts +
505             gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate);
506         old_ts = priv->base_ts +
507             gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
508         diff = GST_CLOCK_DIFF (next_ts, old_ts);
509         GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
510         /* only mark discontinuity if beyond tolerance */
511         if (G_UNLIKELY (diff < -enc->priv->tolerance ||
512                 diff > enc->priv->tolerance)) {
513           GST_DEBUG_OBJECT (enc, "marked discont");
514           priv->discont = TRUE;
515         }
516         if (diff > GST_SECOND / ctx->info.rate / 2 ||
517             diff < -GST_SECOND / ctx->info.rate / 2) {
518           GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
519               " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
520           /* re-sync to upstream ts */
521           priv->base_ts = ts;
522           priv->samples = distance;
523         } else {
524           GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter");
525         }
526       }
527     }
528     /* advance sample view */
529     if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) {
530       if (G_LIKELY (!priv->force)) {
531         /* no way we can let this pass */
532         g_assert_not_reached ();
533         /* really no way */
534         goto overflow;
535       } else {
536         priv->offset = 0;
537         if (samples * ctx->info.bpf >= gst_adapter_available (priv->adapter))
538           gst_adapter_clear (priv->adapter);
539         else
540           gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
541       }
542     } else {
543       gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
544       priv->offset -= samples * ctx->info.bpf;
545       /* avoid subsequent stray prev_ts */
546       if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
547         gst_adapter_clear (priv->adapter);
548     }
549     /* sample count advanced below after buffer handling */
550   }
551
552   /* collect output */
553   if (G_LIKELY (buf)) {
554     gsize size;
555
556     size = gst_buffer_get_size (buf);
557
558     GST_LOG_OBJECT (enc, "taking %d bytes for output", size);
559     buf = gst_buffer_make_writable (buf);
560
561     /* decorate */
562     if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
563       /* FIXME ? lookahead could lead to weird ts and duration ?
564        * (particularly if not in perfect mode) */
565       /* mind sample rounding and produce perfect output */
566       GST_BUFFER_TIMESTAMP (buf) = priv->base_ts +
567           gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
568           ctx->info.rate);
569       GST_DEBUG_OBJECT (enc, "out samples %d", samples);
570       if (G_LIKELY (samples > 0)) {
571         priv->samples += samples;
572         GST_BUFFER_DURATION (buf) = priv->base_ts +
573             gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
574             ctx->info.rate) - GST_BUFFER_TIMESTAMP (buf);
575         priv->last_duration = GST_BUFFER_DURATION (buf);
576       } else {
577         /* duration forecast in case of handling remainder;
578          * the last one is probably like the previous one ... */
579         GST_BUFFER_DURATION (buf) = priv->last_duration;
580       }
581       if (priv->base_gp >= 0) {
582         /* pamper oggmux */
583         /* FIXME: in longer run, muxer should take care of this ... */
584         /* offset_end = granulepos for ogg muxer */
585         GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
586             enc->priv->ctx.lookahead;
587         /* offset = timestamp corresponding to granulepos for ogg muxer */
588         GST_BUFFER_OFFSET (buf) =
589             GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
590             ctx->info.rate);
591       } else {
592         GST_BUFFER_OFFSET (buf) = priv->bytes_out;
593         GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + size;
594       }
595     }
596
597     priv->bytes_out += size;
598
599     if (G_UNLIKELY (priv->discont)) {
600       GST_LOG_OBJECT (enc, "marking discont");
601       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
602       priv->discont = FALSE;
603     }
604
605     if (klass->pre_push) {
606       /* last chance for subclass to do some dirty stuff */
607       ret = klass->pre_push (enc, &buf);
608       if (ret != GST_FLOW_OK || !buf) {
609         GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
610             gst_flow_get_name (ret), buf);
611         if (buf)
612           gst_buffer_unref (buf);
613         goto exit;
614       }
615     }
616
617     GST_LOG_OBJECT (enc, "pushing buffer of size %d with ts %" GST_TIME_FORMAT
618         ", duration %" GST_TIME_FORMAT, size,
619         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
620         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
621
622     ret = gst_pad_push (enc->srcpad, buf);
623     GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
624   } else {
625     /* merely advance samples, most work for that already done above */
626     priv->samples += samples;
627   }
628
629 exit:
630   return ret;
631
632   /* ERRORS */
633 overflow:
634   {
635     GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
636         ("received more encoded samples %d than provided %d",
637             samples, priv->offset / ctx->info.bpf), (NULL));
638     if (buf)
639       gst_buffer_unref (buf);
640     return GST_FLOW_ERROR;
641   }
642 }
643
644  /* adapter tracking idea:
645   * - start of adapter corresponds with what has already been encoded
646   * (i.e. really returned by encoder subclass)
647   * - start + offset is what needs to be fed to subclass next */
648 static GstFlowReturn
649 gst_audio_encoder_push_buffers (GstAudioEncoder * enc, gboolean force)
650 {
651   GstAudioEncoderClass *klass;
652   GstAudioEncoderPrivate *priv;
653   GstAudioEncoderContext *ctx;
654   gint av, need;
655   GstBuffer *buf;
656   GstFlowReturn ret = GST_FLOW_OK;
657
658   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
659
660   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
661
662   priv = enc->priv;
663   ctx = &enc->priv->ctx;
664
665   while (ret == GST_FLOW_OK) {
666
667     buf = NULL;
668     av = gst_adapter_available (priv->adapter);
669
670     g_assert (priv->offset <= av);
671     av -= priv->offset;
672
673     need = ctx->frame_samples > 0 ? ctx->frame_samples * ctx->info.bpf : av;
674     GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d",
675         av, need, force);
676
677     if ((need > av) || !av) {
678       if (G_UNLIKELY (force)) {
679         priv->force = TRUE;
680         need = av;
681       } else {
682         break;
683       }
684     } else {
685       priv->force = FALSE;
686     }
687
688     /* if we have some extra metadata,
689      * provide for integer multiple of frames to allow for better granularity
690      * of processing */
691     if (ctx->frame_samples > 0 && need) {
692       if (ctx->frame_max > 1)
693         need = need * MIN ((av / need), ctx->frame_max);
694       else if (ctx->frame_max == 0)
695         need = need * (av / need);
696     }
697
698     if (need) {
699       const guint8 *data;
700
701       data = gst_adapter_map (priv->adapter, priv->offset + need);
702       buf =
703           gst_buffer_new_wrapped_full ((gpointer) data, NULL, priv->offset,
704           need);
705     }
706
707     GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
708         need, priv->offset);
709
710     /* mark this already as consumed,
711      * which it should be when subclass gives us data in exchange for samples */
712     priv->offset += need;
713     priv->samples_in += need / ctx->info.bpf;
714
715     priv->got_data = FALSE;
716     ret = klass->handle_frame (enc, buf);
717
718     if (G_LIKELY (buf)) {
719       gst_buffer_unref (buf);
720       gst_adapter_unmap (priv->adapter, 0);
721     }
722
723     /* no data to feed, no leftover provided, then bail out */
724     if (G_UNLIKELY (!buf && !priv->got_data)) {
725       priv->drained = TRUE;
726       GST_LOG_OBJECT (enc, "no more data drained from subclass");
727       break;
728     }
729   }
730
731   return ret;
732 }
733
734 static GstFlowReturn
735 gst_audio_encoder_drain (GstAudioEncoder * enc)
736 {
737   if (enc->priv->drained)
738     return GST_FLOW_OK;
739   else
740     return gst_audio_encoder_push_buffers (enc, TRUE);
741 }
742
743 static void
744 gst_audio_encoder_set_base_gp (GstAudioEncoder * enc)
745 {
746   GstClockTime ts;
747
748   if (!enc->priv->granule)
749     return;
750
751   /* use running time for granule */
752   /* incoming data is clipped, so a valid input should yield a valid output */
753   ts = gst_segment_to_running_time (&enc->segment, GST_FORMAT_TIME,
754       enc->priv->base_ts);
755   if (GST_CLOCK_TIME_IS_VALID (ts)) {
756     enc->priv->base_gp =
757         GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate);
758     GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
759   } else {
760     /* should reasonably have a valid base,
761      * otherwise start at 0 if we did not already start there earlier */
762     if (enc->priv->base_gp < 0) {
763       enc->priv->base_gp = 0;
764       GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
765           enc->priv->base_gp);
766     }
767   }
768 }
769
770 static GstFlowReturn
771 gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer)
772 {
773   GstAudioEncoder *enc;
774   GstAudioEncoderPrivate *priv;
775   GstAudioEncoderContext *ctx;
776   GstFlowReturn ret = GST_FLOW_OK;
777   gboolean discont;
778   gsize size;
779
780   enc = GST_AUDIO_ENCODER (GST_OBJECT_PARENT (pad));
781
782   priv = enc->priv;
783   ctx = &enc->priv->ctx;
784
785   /* should know what is coming by now */
786   if (!ctx->info.bpf)
787     goto not_negotiated;
788
789   size = gst_buffer_get_size (buffer);
790
791   GST_LOG_OBJECT (enc,
792       "received buffer of size %d with ts %" GST_TIME_FORMAT
793       ", duration %" GST_TIME_FORMAT, size,
794       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
795       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
796
797   /* input shoud be whole number of sample frames */
798   if (size % ctx->info.bpf)
799     goto wrong_buffer;
800
801 #ifndef GST_DISABLE_GST_DEBUG
802   {
803     GstClockTime duration;
804     GstClockTimeDiff diff;
805
806     /* verify buffer duration */
807     duration = gst_util_uint64_scale (size, GST_SECOND,
808         ctx->info.rate * ctx->info.bpf);
809     diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
810     if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
811         (diff > GST_SECOND / ctx->info.rate / 2 ||
812             diff < -GST_SECOND / ctx->info.rate / 2)) {
813       GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
814           GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
815           GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
816           GST_TIME_ARGS (duration));
817     }
818   }
819 #endif
820
821   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
822   if (G_UNLIKELY (discont)) {
823     GST_LOG_OBJECT (buffer, "marked discont");
824     enc->priv->discont = discont;
825   }
826
827   /* clip to segment */
828   /* NOTE: slightly painful linking -laudio only for this one ... */
829   buffer = gst_audio_buffer_clip (buffer, &enc->segment, ctx->info.rate,
830       ctx->info.bpf);
831   if (G_UNLIKELY (!buffer)) {
832     GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
833     goto done;
834   }
835
836   size = gst_buffer_get_size (buffer);
837
838   GST_LOG_OBJECT (enc,
839       "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT
840       ", duration %" GST_TIME_FORMAT, size,
841       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
842       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
843
844   if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
845     priv->base_ts = GST_BUFFER_TIMESTAMP (buffer);
846     GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
847         GST_TIME_ARGS (priv->base_ts));
848     gst_audio_encoder_set_base_gp (enc);
849   }
850
851   /* check for continuity;
852    * checked elsewhere in non-perfect case */
853   if (enc->priv->perfect_ts) {
854     GstClockTimeDiff diff = 0;
855     GstClockTime next_ts = 0;
856
857     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
858         GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
859       guint64 samples;
860
861       samples = priv->samples +
862           gst_adapter_available (priv->adapter) / ctx->info.bpf;
863       next_ts = priv->base_ts +
864           gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
865       GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
866           " samples past base_ts %" GST_TIME_FORMAT
867           ", expected ts %" GST_TIME_FORMAT, samples,
868           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
869       diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer));
870       GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
871       /* if within tolerance,
872        * discard buffer ts and carry on producing perfect stream,
873        * otherwise clip or resync to ts */
874       if (G_UNLIKELY (diff < -enc->priv->tolerance ||
875               diff > enc->priv->tolerance)) {
876         GST_DEBUG_OBJECT (enc, "marked discont");
877         discont = TRUE;
878       }
879     }
880
881     /* do some fancy tweaking in hard resync case */
882     if (discont && enc->priv->hard_resync) {
883       if (diff < 0) {
884         guint64 diff_bytes;
885
886         GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
887             GST_TIME_FORMAT ".  Clipping buffer", GST_TIME_ARGS (next_ts));
888
889         diff_bytes =
890             GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf;
891         if (diff_bytes >= size) {
892           gst_buffer_unref (buffer);
893           goto done;
894         }
895         buffer = gst_buffer_make_writable (buffer);
896         gst_buffer_resize (buffer, diff_bytes, size - diff_bytes);
897
898         GST_BUFFER_TIMESTAMP (buffer) += diff;
899         /* care even less about duration after this */
900       } else {
901         /* drain stuff prior to resync */
902         gst_audio_encoder_drain (enc);
903       }
904     }
905     /* now re-sync ts */
906     priv->base_ts += diff;
907     gst_audio_encoder_set_base_gp (enc);
908     priv->discont |= discont;
909   }
910
911   gst_adapter_push (enc->priv->adapter, buffer);
912   /* new stuff, so we can push subclass again */
913   enc->priv->drained = FALSE;
914
915   ret = gst_audio_encoder_push_buffers (enc, FALSE);
916
917 done:
918   GST_LOG_OBJECT (enc, "chain leaving");
919   return ret;
920
921   /* ERRORS */
922 not_negotiated:
923   {
924     GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
925         ("encoder not initialized"));
926     gst_buffer_unref (buffer);
927     return GST_FLOW_NOT_NEGOTIATED;
928   }
929 wrong_buffer:
930   {
931     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
932         ("buffer size %d not a multiple of %d", gst_buffer_get_size (buffer),
933             ctx->info.bpf));
934     gst_buffer_unref (buffer);
935     return GST_FLOW_ERROR;
936   }
937 }
938
939 static gboolean
940 audio_info_is_equal (GstAudioInfo * from, GstAudioInfo * to)
941 {
942   if (from == to)
943     return TRUE;
944   if (from->finfo == NULL || to->finfo == NULL)
945     return FALSE;
946   if (GST_AUDIO_INFO_FORMAT (from) != GST_AUDIO_INFO_FORMAT (to))
947     return FALSE;
948   if (GST_AUDIO_INFO_RATE (from) != GST_AUDIO_INFO_RATE (to))
949     return FALSE;
950   if (GST_AUDIO_INFO_CHANNELS (from) != GST_AUDIO_INFO_CHANNELS (to))
951     return FALSE;
952   if (GST_AUDIO_INFO_CHANNELS (from) > 64)
953     return TRUE;
954   return memcmp (from->position, to->position,
955       GST_AUDIO_INFO_CHANNELS (from) * sizeof (to->position[0]));
956 }
957
958 static gboolean
959 gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc, GstCaps * caps)
960 {
961   GstAudioEncoderClass *klass;
962   GstAudioEncoderContext *ctx;
963   GstAudioInfo state;
964   gboolean res = TRUE, changed = FALSE;
965   guint old_rate;
966
967   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
968
969   /* subclass must do something here ... */
970   g_return_val_if_fail (klass->set_format != NULL, FALSE);
971
972   ctx = &enc->priv->ctx;
973
974   GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
975
976   if (!gst_caps_is_fixed (caps))
977     goto refuse_caps;
978
979   /* adjust ts tracking to new sample rate */
980   old_rate = GST_AUDIO_INFO_RATE (&ctx->info);
981   if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) {
982     enc->priv->base_ts +=
983         GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate);
984     enc->priv->samples = 0;
985   }
986
987   if (!gst_audio_info_from_caps (&state, caps))
988     goto refuse_caps;
989
990   changed = !audio_info_is_equal (&state, &ctx->info);
991
992   if (changed) {
993     GstClockTime old_min_latency;
994     GstClockTime old_max_latency;
995
996     /* drain any pending old data stuff */
997     gst_audio_encoder_drain (enc);
998
999     /* context defaults */
1000     enc->priv->ctx.frame_samples = 0;
1001     enc->priv->ctx.frame_max = 0;
1002     enc->priv->ctx.lookahead = 0;
1003
1004     /* element might report latency */
1005     GST_OBJECT_LOCK (enc);
1006     old_min_latency = ctx->min_latency;
1007     old_max_latency = ctx->max_latency;
1008     GST_OBJECT_UNLOCK (enc);
1009
1010     if (klass->set_format)
1011       res = klass->set_format (enc, &state);
1012
1013     /* notify if new latency */
1014     GST_OBJECT_LOCK (enc);
1015     if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) ||
1016         (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) {
1017       GST_OBJECT_UNLOCK (enc);
1018       /* post latency message on the bus */
1019       gst_element_post_message (GST_ELEMENT (enc),
1020           gst_message_new_latency (GST_OBJECT (enc)));
1021       GST_OBJECT_LOCK (enc);
1022     }
1023     GST_OBJECT_UNLOCK (enc);
1024   } else {
1025     GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
1026   }
1027
1028   return res;
1029
1030   /* ERRORS */
1031 refuse_caps:
1032   {
1033     GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
1034     return res;
1035   }
1036 }
1037
1038
1039 /**
1040  * gst_audio_encoder_proxy_getcaps:
1041  * @enc: a #GstAudioEncoder
1042  * @caps: initial caps
1043  *
1044  * Returns caps that express @caps (or sink template caps if @caps == NULL)
1045  * restricted to channel/rate combinations supported by downstream elements
1046  * (e.g. muxers).
1047  *
1048  * Returns: a #GstCaps owned by caller
1049  *
1050  * Since: 0.10.36
1051  */
1052 GstCaps *
1053 gst_audio_encoder_proxy_getcaps (GstAudioEncoder * enc, GstCaps * caps)
1054 {
1055   const GstCaps *templ_caps;
1056   GstCaps *allowed = NULL;
1057   GstCaps *fcaps, *filter_caps;
1058   gint i, j;
1059
1060   /* we want to be able to communicate to upstream elements like audioconvert
1061    * and audioresample any rate/channel restrictions downstream (e.g. muxer
1062    * only accepting certain sample rates) */
1063   templ_caps = caps ? caps : gst_pad_get_pad_template_caps (enc->sinkpad);
1064   allowed = gst_pad_get_allowed_caps (enc->srcpad);
1065   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
1066     fcaps = gst_caps_copy (templ_caps);
1067     goto done;
1068   }
1069
1070   GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps);
1071   GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
1072
1073   filter_caps = gst_caps_new_empty ();
1074
1075   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
1076     GQuark q_name;
1077
1078     q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
1079
1080     /* pick rate + channel fields from allowed caps */
1081     for (j = 0; j < gst_caps_get_size (allowed); j++) {
1082       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
1083       const GValue *val;
1084       GstStructure *s;
1085
1086       s = gst_structure_id_empty_new (q_name);
1087       if ((val = gst_structure_get_value (allowed_s, "rate")))
1088         gst_structure_set_value (s, "rate", val);
1089       if ((val = gst_structure_get_value (allowed_s, "channels")))
1090         gst_structure_set_value (s, "channels", val);
1091       /* following might also make sense for some encoded formats,
1092        * e.g. wavpack */
1093       if ((val = gst_structure_get_value (allowed_s, "width")))
1094         gst_structure_set_value (s, "width", val);
1095       if ((val = gst_structure_get_value (allowed_s, "depth")))
1096         gst_structure_set_value (s, "depth", val);
1097       if ((val = gst_structure_get_value (allowed_s, "endianness")))
1098         gst_structure_set_value (s, "endianness", val);
1099       if ((val = gst_structure_get_value (allowed_s, "signed")))
1100         gst_structure_set_value (s, "signed", val);
1101       if ((val = gst_structure_get_value (allowed_s, "channel-positions")))
1102         gst_structure_set_value (s, "channel-positions", val);
1103
1104       gst_caps_merge_structure (filter_caps, s);
1105     }
1106   }
1107
1108   fcaps = gst_caps_intersect (filter_caps, templ_caps);
1109   gst_caps_unref (filter_caps);
1110
1111 done:
1112   gst_caps_replace (&allowed, NULL);
1113
1114   GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
1115
1116   return fcaps;
1117 }
1118
1119 static GstCaps *
1120 gst_audio_encoder_sink_getcaps (GstPad * pad, GstCaps * filter)
1121 {
1122   GstAudioEncoder *enc;
1123   GstAudioEncoderClass *klass;
1124   GstCaps *caps;
1125
1126   enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1127   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1128   g_assert (pad == enc->sinkpad);
1129
1130   if (klass->getcaps)
1131     caps = klass->getcaps (enc, filter);
1132   else
1133     caps = gst_audio_encoder_proxy_getcaps (enc, NULL);
1134   gst_object_unref (enc);
1135
1136   GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1137
1138   return caps;
1139 }
1140
1141 static gboolean
1142 gst_audio_encoder_sink_eventfunc (GstAudioEncoder * enc, GstEvent * event)
1143 {
1144   GstAudioEncoderClass *klass;
1145   gboolean handled = FALSE;
1146
1147   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1148
1149   switch (GST_EVENT_TYPE (event)) {
1150     case GST_EVENT_SEGMENT:
1151     {
1152       GstSegment seg;
1153
1154       gst_event_copy_segment (event, &seg);
1155
1156       if (seg.format == GST_FORMAT_TIME) {
1157         GST_DEBUG_OBJECT (enc, "received TIME SEGMENT %" GST_PTR_FORMAT, &seg);
1158       } else {
1159         GST_DEBUG_OBJECT (enc, "received SEGMENT %" GST_PTR_FORMAT, &seg);
1160         GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1161         break;
1162       }
1163
1164       /* finish current segment */
1165       gst_audio_encoder_drain (enc);
1166       /* reset partially for new segment */
1167       gst_audio_encoder_reset (enc, FALSE);
1168       /* and follow along with segment */
1169       enc->segment = seg;
1170       break;
1171     }
1172
1173     case GST_EVENT_FLUSH_START:
1174       break;
1175
1176     case GST_EVENT_FLUSH_STOP:
1177       /* discard any pending stuff */
1178       /* TODO route through drain ?? */
1179       if (!enc->priv->drained && klass->flush)
1180         klass->flush (enc);
1181       /* and get (re)set for the sequel */
1182       gst_audio_encoder_reset (enc, FALSE);
1183       break;
1184
1185     case GST_EVENT_EOS:
1186       gst_audio_encoder_drain (enc);
1187       break;
1188
1189     case GST_EVENT_CAPS:
1190     {
1191       GstCaps *caps;
1192
1193       gst_event_parse_caps (event, &caps);
1194       gst_audio_encoder_sink_setcaps (enc, caps);
1195       gst_event_unref (event);
1196       handled = TRUE;
1197       break;
1198     }
1199
1200     default:
1201       break;
1202   }
1203
1204   return handled;
1205 }
1206
1207 static gboolean
1208 gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event)
1209 {
1210   GstAudioEncoder *enc;
1211   GstAudioEncoderClass *klass;
1212   gboolean handled = FALSE;
1213   gboolean ret = TRUE;
1214
1215   enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1216   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1217
1218   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1219       GST_EVENT_TYPE_NAME (event));
1220
1221   if (klass->event)
1222     handled = klass->event (enc, event);
1223
1224   if (!handled)
1225     handled = gst_audio_encoder_sink_eventfunc (enc, event);
1226
1227   if (!handled)
1228     ret = gst_pad_event_default (pad, event);
1229
1230   GST_DEBUG_OBJECT (enc, "event handled");
1231
1232   gst_object_unref (enc);
1233   return ret;
1234 }
1235
1236 static gboolean
1237 gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query)
1238 {
1239   gboolean res = TRUE;
1240   GstAudioEncoder *enc;
1241
1242   enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1243
1244   switch (GST_QUERY_TYPE (query)) {
1245     case GST_QUERY_FORMATS:
1246     {
1247       gst_query_set_formats (query, 3,
1248           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1249       res = TRUE;
1250       break;
1251     }
1252     case GST_QUERY_CONVERT:
1253     {
1254       GstFormat src_fmt, dest_fmt;
1255       gint64 src_val, dest_val;
1256
1257       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1258       if (!(res = gst_audio_info_convert (&enc->priv->ctx.info,
1259                   src_fmt, src_val, dest_fmt, &dest_val)))
1260         goto error;
1261       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1262       break;
1263     }
1264     default:
1265       res = gst_pad_query_default (pad, query);
1266       break;
1267   }
1268
1269 error:
1270   gst_object_unref (enc);
1271   return res;
1272 }
1273
1274 static const GstQueryType *
1275 gst_audio_encoder_get_query_types (GstPad * pad)
1276 {
1277   static const GstQueryType gst_audio_encoder_src_query_types[] = {
1278     GST_QUERY_POSITION,
1279     GST_QUERY_DURATION,
1280     GST_QUERY_CONVERT,
1281     GST_QUERY_LATENCY,
1282     0
1283   };
1284
1285   return gst_audio_encoder_src_query_types;
1286 }
1287
1288 /*
1289  * gst_audio_encoded_audio_convert:
1290  * @fmt: audio format of the encoded audio
1291  * @bytes: number of encoded bytes
1292  * @samples: number of encoded samples
1293  * @src_format: source format
1294  * @src_value: source value
1295  * @dest_format: destination format
1296  * @dest_value: destination format
1297  *
1298  * Helper function to convert @src_value in @src_format to @dest_value in
1299  * @dest_format for encoded audio data.  Conversion is possible between
1300  * BYTE and TIME format by using estimated bitrate based on
1301  * @samples and @bytes (and @fmt).
1302  *
1303  * Since: 0.10.36
1304  */
1305 /* FIXME: make gst_audio_encoded_audio_convert() public? */
1306 static gboolean
1307 gst_audio_encoded_audio_convert (GstAudioInfo * fmt,
1308     gint64 bytes, gint64 samples, GstFormat src_format,
1309     gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
1310 {
1311   gboolean res = FALSE;
1312
1313   g_return_val_if_fail (dest_format != NULL, FALSE);
1314   g_return_val_if_fail (dest_value != NULL, FALSE);
1315
1316   if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
1317           src_value == -1)) {
1318     if (dest_value)
1319       *dest_value = src_value;
1320     return TRUE;
1321   }
1322
1323   if (samples == 0 || bytes == 0 || fmt->rate == 0) {
1324     GST_DEBUG ("not enough metadata yet to convert");
1325     goto exit;
1326   }
1327
1328   bytes *= fmt->rate;
1329
1330   switch (src_format) {
1331     case GST_FORMAT_BYTES:
1332       switch (*dest_format) {
1333         case GST_FORMAT_TIME:
1334           *dest_value = gst_util_uint64_scale (src_value,
1335               GST_SECOND * samples, bytes);
1336           res = TRUE;
1337           break;
1338         default:
1339           res = FALSE;
1340       }
1341       break;
1342     case GST_FORMAT_TIME:
1343       switch (*dest_format) {
1344         case GST_FORMAT_BYTES:
1345           *dest_value = gst_util_uint64_scale (src_value, bytes,
1346               samples * GST_SECOND);
1347           res = TRUE;
1348           break;
1349         default:
1350           res = FALSE;
1351       }
1352       break;
1353     default:
1354       res = FALSE;
1355   }
1356
1357 exit:
1358   return res;
1359 }
1360
1361 /* FIXME ? are any of these queries (other than latency) an encoder's business
1362  * also, the conversion stuff might seem to make sense, but seems to not mind
1363  * segment stuff etc at all
1364  * Supposedly that's backward compatibility ... */
1365 static gboolean
1366 gst_audio_encoder_src_query (GstPad * pad, GstQuery * query)
1367 {
1368   GstAudioEncoder *enc;
1369   GstPad *peerpad;
1370   gboolean res = FALSE;
1371
1372   enc = GST_AUDIO_ENCODER (GST_PAD_PARENT (pad));
1373   peerpad = gst_pad_get_peer (GST_PAD (enc->sinkpad));
1374
1375   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1376
1377   switch (GST_QUERY_TYPE (query)) {
1378     case GST_QUERY_POSITION:
1379     {
1380       GstFormat fmt, req_fmt;
1381       gint64 pos, val;
1382
1383       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1384         GST_LOG_OBJECT (enc, "returning peer response");
1385         break;
1386       }
1387
1388       if (!peerpad) {
1389         GST_LOG_OBJECT (enc, "no peer");
1390         break;
1391       }
1392
1393       gst_query_parse_position (query, &req_fmt, NULL);
1394       fmt = GST_FORMAT_TIME;
1395       if (!(res = gst_pad_query_position (peerpad, fmt, &pos)))
1396         break;
1397
1398       if ((res = gst_pad_query_convert (peerpad, fmt, pos, req_fmt, &val))) {
1399         gst_query_set_position (query, req_fmt, val);
1400       }
1401       break;
1402     }
1403     case GST_QUERY_DURATION:
1404     {
1405       GstFormat fmt, req_fmt;
1406       gint64 dur, val;
1407
1408       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1409         GST_LOG_OBJECT (enc, "returning peer response");
1410         break;
1411       }
1412
1413       if (!peerpad) {
1414         GST_LOG_OBJECT (enc, "no peer");
1415         break;
1416       }
1417
1418       gst_query_parse_duration (query, &req_fmt, NULL);
1419       fmt = GST_FORMAT_TIME;
1420       if (!(res = gst_pad_query_duration (peerpad, fmt, &dur)))
1421         break;
1422
1423       if ((res = gst_pad_query_convert (peerpad, fmt, dur, req_fmt, &val))) {
1424         gst_query_set_duration (query, req_fmt, val);
1425       }
1426       break;
1427     }
1428     case GST_QUERY_FORMATS:
1429     {
1430       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1431       res = TRUE;
1432       break;
1433     }
1434     case GST_QUERY_CONVERT:
1435     {
1436       GstFormat src_fmt, dest_fmt;
1437       gint64 src_val, dest_val;
1438
1439       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1440       if (!(res = gst_audio_encoded_audio_convert (&enc->priv->ctx.info,
1441                   enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
1442                   &dest_fmt, &dest_val)))
1443         break;
1444       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1445       break;
1446     }
1447     case GST_QUERY_LATENCY:
1448     {
1449       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1450         gboolean live;
1451         GstClockTime min_latency, max_latency;
1452
1453         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1454         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1455             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1456             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1457
1458         GST_OBJECT_LOCK (enc);
1459         /* add our latency */
1460         if (min_latency != -1)
1461           min_latency += enc->priv->ctx.min_latency;
1462         if (max_latency != -1)
1463           max_latency += enc->priv->ctx.max_latency;
1464         GST_OBJECT_UNLOCK (enc);
1465
1466         gst_query_set_latency (query, live, min_latency, max_latency);
1467       }
1468       break;
1469     }
1470     default:
1471       res = gst_pad_query_default (pad, query);
1472       break;
1473   }
1474
1475   gst_object_unref (peerpad);
1476   return res;
1477 }
1478
1479 static void
1480 gst_audio_encoder_set_property (GObject * object, guint prop_id,
1481     const GValue * value, GParamSpec * pspec)
1482 {
1483   GstAudioEncoder *enc;
1484
1485   enc = GST_AUDIO_ENCODER (object);
1486
1487   switch (prop_id) {
1488     case PROP_PERFECT_TS:
1489       if (enc->priv->granule && !g_value_get_boolean (value))
1490         GST_WARNING_OBJECT (enc, "perfect-timestamp can not be set FALSE "
1491             "while granule handling is enabled");
1492       else
1493         enc->priv->perfect_ts = g_value_get_boolean (value);
1494       break;
1495     case PROP_HARD_RESYNC:
1496       enc->priv->hard_resync = g_value_get_boolean (value);
1497       break;
1498     case PROP_TOLERANCE:
1499       enc->priv->tolerance = g_value_get_int64 (value);
1500       break;
1501     default:
1502       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1503       break;
1504   }
1505 }
1506
1507 static void
1508 gst_audio_encoder_get_property (GObject * object, guint prop_id,
1509     GValue * value, GParamSpec * pspec)
1510 {
1511   GstAudioEncoder *enc;
1512
1513   enc = GST_AUDIO_ENCODER (object);
1514
1515   switch (prop_id) {
1516     case PROP_PERFECT_TS:
1517       g_value_set_boolean (value, enc->priv->perfect_ts);
1518       break;
1519     case PROP_GRANULE:
1520       g_value_set_boolean (value, enc->priv->granule);
1521       break;
1522     case PROP_HARD_RESYNC:
1523       g_value_set_boolean (value, enc->priv->hard_resync);
1524       break;
1525     case PROP_TOLERANCE:
1526       g_value_set_int64 (value, enc->priv->tolerance);
1527       break;
1528     default:
1529       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1530       break;
1531   }
1532 }
1533
1534 static gboolean
1535 gst_audio_encoder_activate (GstAudioEncoder * enc, gboolean active)
1536 {
1537   GstAudioEncoderClass *klass;
1538   gboolean result = FALSE;
1539
1540   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1541
1542   g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE);
1543
1544   GST_DEBUG_OBJECT (enc, "activate %d", active);
1545
1546   if (active) {
1547     if (!enc->priv->active && klass->start)
1548       result = klass->start (enc);
1549   } else {
1550     /* We must make sure streaming has finished before resetting things
1551      * and calling the ::stop vfunc */
1552     GST_PAD_STREAM_LOCK (enc->sinkpad);
1553     GST_PAD_STREAM_UNLOCK (enc->sinkpad);
1554
1555     if (enc->priv->active && klass->stop)
1556       result = klass->stop (enc);
1557
1558     /* clean up */
1559     gst_audio_encoder_reset (enc, TRUE);
1560   }
1561   GST_DEBUG_OBJECT (enc, "activate return: %d", result);
1562   return result;
1563 }
1564
1565
1566 static gboolean
1567 gst_audio_encoder_sink_activate_push (GstPad * pad, gboolean active)
1568 {
1569   gboolean result = TRUE;
1570   GstAudioEncoder *enc;
1571
1572   enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1573
1574   GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
1575
1576   result = gst_audio_encoder_activate (enc, active);
1577
1578   if (result)
1579     enc->priv->active = active;
1580
1581   GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
1582
1583   gst_object_unref (enc);
1584   return result;
1585 }
1586
1587 /**
1588  * gst_audio_encoder_get_audio_info:
1589  * @enc: a #GstAudioEncoder
1590  *
1591  * Returns: a #GstAudioInfo describing the input audio format
1592  *
1593  * Since: 0.10.36
1594  */
1595 GstAudioInfo *
1596 gst_audio_encoder_get_audio_info (GstAudioEncoder * enc)
1597 {
1598   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), NULL);
1599
1600   return &enc->priv->ctx.info;
1601 }
1602
1603 /**
1604  * gst_audio_encoder_set_frame_samples:
1605  * @enc: a #GstAudioEncoder
1606  * @num: number of samples per frame
1607  *
1608  * Sets number of samples (per channel) subclass needs to be handed,
1609  * or will be handed all available if 0.
1610  *
1611  * Since: 0.10.36
1612  */
1613 void
1614 gst_audio_encoder_set_frame_samples (GstAudioEncoder * enc, gint num)
1615 {
1616   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1617
1618   enc->priv->ctx.frame_samples = num;
1619 }
1620
1621 /**
1622  * gst_audio_encoder_get_frame_samples:
1623  * @enc: a #GstAudioEncoder
1624  *
1625  * Returns: currently requested samples per frame
1626  *
1627  * Since: 0.10.36
1628  */
1629 gint
1630 gst_audio_encoder_get_frame_samples (GstAudioEncoder * enc)
1631 {
1632   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1633
1634   return enc->priv->ctx.frame_samples;
1635 }
1636
1637 /**
1638  * gst_audio_encoder_set_frame_max:
1639  * @enc: a #GstAudioEncoder
1640  * @num: number of frames
1641  *
1642  * Sets max number of frames accepted at once (assumed minimally 1)
1643  *
1644  * Since: 0.10.36
1645  */
1646 void
1647 gst_audio_encoder_set_frame_max (GstAudioEncoder * enc, gint num)
1648 {
1649   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1650
1651   enc->priv->ctx.frame_max = num;
1652 }
1653
1654 /**
1655  * gst_audio_encoder_get_frame_max:
1656  * @enc: a #GstAudioEncoder
1657  *
1658  * Returns: currently configured maximum handled frames
1659  *
1660  * Since: 0.10.36
1661  */
1662 gint
1663 gst_audio_encoder_get_frame_max (GstAudioEncoder * enc)
1664 {
1665   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1666
1667   return enc->priv->ctx.frame_max;
1668 }
1669
1670 /**
1671  * gst_audio_encoder_set_lookahead:
1672  * @enc: a #GstAudioEncoder
1673  * @num: lookahead
1674  *
1675  * Sets encoder lookahead (in units of input rate samples)
1676  *
1677  * Since: 0.10.36
1678  */
1679 void
1680 gst_audio_encoder_set_lookahead (GstAudioEncoder * enc, gint num)
1681 {
1682   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1683
1684   enc->priv->ctx.lookahead = num;
1685 }
1686
1687 /**
1688  * gst_audio_encoder_get_lookahead:
1689  * @enc: a #GstAudioEncoder
1690  *
1691  * Returns: currently configured encoder lookahead
1692  */
1693 gint
1694 gst_audio_encoder_get_lookahead (GstAudioEncoder * enc)
1695 {
1696   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1697
1698   return enc->priv->ctx.lookahead;
1699 }
1700
1701 /**
1702  * gst_audio_encoder_set_latency:
1703  * @enc: a #GstAudioEncoder
1704  * @min: minimum latency
1705  * @max: maximum latency
1706  *
1707  * Sets encoder latency.
1708  *
1709  * Since: 0.10.36
1710  */
1711 void
1712 gst_audio_encoder_set_latency (GstAudioEncoder * enc,
1713     GstClockTime min, GstClockTime max)
1714 {
1715   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1716
1717   GST_OBJECT_LOCK (enc);
1718   enc->priv->ctx.min_latency = min;
1719   enc->priv->ctx.max_latency = max;
1720   GST_OBJECT_UNLOCK (enc);
1721 }
1722
1723 /**
1724  * gst_audio_encoder_get_latency:
1725  * @enc: a #GstAudioEncoder
1726  * @min: (out) (allow-none): a pointer to storage to hold minimum latency
1727  * @max: (out) (allow-none): a pointer to storage to hold maximum latency
1728  *
1729  * Sets the variables pointed to by @min and @max to the currently configured
1730  * latency.
1731  *
1732  * Since: 0.10.36
1733  */
1734 void
1735 gst_audio_encoder_get_latency (GstAudioEncoder * enc,
1736     GstClockTime * min, GstClockTime * max)
1737 {
1738   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1739
1740   GST_OBJECT_LOCK (enc);
1741   if (min)
1742     *min = enc->priv->ctx.min_latency;
1743   if (max)
1744     *max = enc->priv->ctx.max_latency;
1745   GST_OBJECT_UNLOCK (enc);
1746 }
1747
1748 /**
1749  * gst_audio_encoder_set_mark_granule:
1750  * @enc: a #GstAudioEncoder
1751  * @enabled: new state
1752  *
1753  * Enable or disable encoder granule handling.
1754  *
1755  * MT safe.
1756  *
1757  * Since: 0.10.36
1758  */
1759 void
1760 gst_audio_encoder_set_mark_granule (GstAudioEncoder * enc, gboolean enabled)
1761 {
1762   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1763
1764   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1765
1766   GST_OBJECT_LOCK (enc);
1767   enc->priv->granule = enabled;
1768   GST_OBJECT_UNLOCK (enc);
1769 }
1770
1771 /**
1772  * gst_audio_encoder_get_mark_granule:
1773  * @enc: a #GstAudioEncoder
1774  *
1775  * Queries if the encoder will handle granule marking.
1776  *
1777  * Returns: TRUE if granule marking is enabled.
1778  *
1779  * MT safe.
1780  *
1781  * Since: 0.10.36
1782  */
1783 gboolean
1784 gst_audio_encoder_get_mark_granule (GstAudioEncoder * enc)
1785 {
1786   gboolean result;
1787
1788   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1789
1790   GST_OBJECT_LOCK (enc);
1791   result = enc->priv->granule;
1792   GST_OBJECT_UNLOCK (enc);
1793
1794   return result;
1795 }
1796
1797 /**
1798  * gst_audio_encoder_set_perfect_timestamp:
1799  * @enc: a #GstAudioEncoder
1800  * @enabled: new state
1801  *
1802  * Enable or disable encoder perfect output timestamp preference.
1803  *
1804  * MT safe.
1805  *
1806  * Since: 0.10.36
1807  */
1808 void
1809 gst_audio_encoder_set_perfect_timestamp (GstAudioEncoder * enc,
1810     gboolean enabled)
1811 {
1812   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1813
1814   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1815
1816   GST_OBJECT_LOCK (enc);
1817   enc->priv->perfect_ts = enabled;
1818   GST_OBJECT_UNLOCK (enc);
1819 }
1820
1821 /**
1822  * gst_audio_encoder_get_perfect_timestamp:
1823  * @enc: a #GstAudioEncoder
1824  *
1825  * Queries encoder perfect timestamp behaviour.
1826  *
1827  * Returns: TRUE if pefect timestamp setting enabled.
1828  *
1829  * MT safe.
1830  *
1831  * Since: 0.10.36
1832  */
1833 gboolean
1834 gst_audio_encoder_get_perfect_timestamp (GstAudioEncoder * enc)
1835 {
1836   gboolean result;
1837
1838   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1839
1840   GST_OBJECT_LOCK (enc);
1841   result = enc->priv->perfect_ts;
1842   GST_OBJECT_UNLOCK (enc);
1843
1844   return result;
1845 }
1846
1847 /**
1848  * gst_audio_encoder_set_hard_sync:
1849  * @enc: a #GstAudioEncoder
1850  * @enabled: new state
1851  *
1852  * Sets encoder hard resync handling.
1853  *
1854  * MT safe.
1855  *
1856  * Since: 0.10.36
1857  */
1858 void
1859 gst_audio_encoder_set_hard_resync (GstAudioEncoder * enc, gboolean enabled)
1860 {
1861   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1862
1863   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1864
1865   GST_OBJECT_LOCK (enc);
1866   enc->priv->hard_resync = enabled;
1867   GST_OBJECT_UNLOCK (enc);
1868 }
1869
1870 /**
1871  * gst_audio_encoder_get_hard_sync:
1872  * @enc: a #GstAudioEncoder
1873  *
1874  * Queries encoder's hard resync setting.
1875  *
1876  * Returns: TRUE if hard resync is enabled.
1877  *
1878  * MT safe.
1879  *
1880  * Since: 0.10.36
1881  */
1882 gboolean
1883 gst_audio_encoder_get_hard_resync (GstAudioEncoder * enc)
1884 {
1885   gboolean result;
1886
1887   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1888
1889   GST_OBJECT_LOCK (enc);
1890   result = enc->priv->hard_resync;
1891   GST_OBJECT_UNLOCK (enc);
1892
1893   return result;
1894 }
1895
1896 /**
1897  * gst_audio_encoder_set_tolerance:
1898  * @enc: a #GstAudioEncoder
1899  * @tolerance: new tolerance
1900  *
1901  * Configures encoder audio jitter tolerance threshold.
1902  *
1903  * MT safe.
1904  *
1905  * Since: 0.10.36
1906  */
1907 void
1908 gst_audio_encoder_set_tolerance (GstAudioEncoder * enc, gint64 tolerance)
1909 {
1910   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1911
1912   GST_OBJECT_LOCK (enc);
1913   enc->priv->tolerance = tolerance;
1914   GST_OBJECT_UNLOCK (enc);
1915 }
1916
1917 /**
1918  * gst_audio_encoder_get_tolerance:
1919  * @enc: a #GstAudioEncoder
1920  *
1921  * Queries current audio jitter tolerance threshold.
1922  *
1923  * Returns: encoder audio jitter tolerance threshold.
1924  *
1925  * MT safe.
1926  *
1927  * Since: 0.10.36
1928  */
1929 gint64
1930 gst_audio_encoder_get_tolerance (GstAudioEncoder * enc)
1931 {
1932   gint64 result;
1933
1934   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1935
1936   GST_OBJECT_LOCK (enc);
1937   result = enc->priv->tolerance;
1938   GST_OBJECT_UNLOCK (enc);
1939
1940   return result;
1941 }