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