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