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