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