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