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