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>
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.
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.
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.
23 * SECTION:gstaudioencoder
24 * @short_description: Base class for audio encoders
25 * @see_also: #GstBaseTransform
28 * This base class is for audio encoders turning raw audio samples into
31 * GstAudioEncoder and subclass should cooperate as follows.
34 * <itemizedlist><title>Configuration</title>
36 * Initially, GstAudioEncoder calls @start when the encoder element
37 * is activated, which allows subclass to perform any global setup.
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.
48 * GstAudioEncoder calls @stop at end of all processing.
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.
59 * <title>Data processing</title>
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.
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.
71 * Just prior to actually pushing a buffer downstream,
72 * it is passed to @pre_push.
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.
82 * <itemizedlist><title>Shutdown phase</title>
84 * GstAudioEncoder class calls @stop to inform the subclass that data
85 * parsing will be stopped.
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.
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.
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.
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).
127 * Things that subclass need to take care of:
129 * <listitem><para>Provide pad templates</para></listitem>
131 * Set source pad caps when appropriate
134 * Inform base class of buffer processing needs using context's
135 * frame_samples and frame_bytes.
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.
143 * Accept data in @handle_frame and provide encoded results to
144 * @gst_audio_encoder_finish_frame.
154 #define GST_USE_UNSTABLE_API
155 #include "gstaudioencoder.h"
156 #include <gst/base/gstadapter.h>
157 #include <gst/audio/audio.h>
158 #include <gst/pbutils/descriptions.h>
164 GST_DEBUG_CATEGORY_STATIC (gst_audio_encoder_debug);
165 #define GST_CAT_DEFAULT gst_audio_encoder_debug
167 #define GST_AUDIO_ENCODER_GET_PRIVATE(obj) \
168 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_AUDIO_ENCODER, \
169 GstAudioEncoderPrivate))
180 #define DEFAULT_PERFECT_TS FALSE
181 #define DEFAULT_GRANULE FALSE
182 #define DEFAULT_HARD_RESYNC FALSE
183 #define DEFAULT_TOLERANCE 40000000
185 typedef struct _GstAudioEncoderContext
194 /* MT-protected (with LOCK) */
195 GstClockTime min_latency;
196 GstClockTime max_latency;
197 } GstAudioEncoderContext;
199 struct _GstAudioEncoderPrivate
201 /* activation status */
204 /* input base/first ts as basis for output ts;
205 * kept nearly constant for perfect_ts,
206 * otherwise resyncs to upstream ts */
207 GstClockTime base_ts;
208 /* corresponding base granulepos */
210 /* input samples processed and sent downstream so far (w.r.t. base_ts) */
213 /* currently collected sample data */
215 /* offset in adapter up to which already supplied to encoder */
217 /* mark outgoing discont */
219 /* to guess duration of drained data */
220 GstClockTime last_duration;
222 /* subclass provided data in processing round */
224 /* subclass gave all it could already */
226 /* subclass currently being forcibly drained */
229 /* output bps estimatation */
230 /* global in samples seen */
232 /* global bytes sent out */
235 /* context storage */
236 GstAudioEncoderContext ctx;
241 gboolean hard_resync;
249 static GstElementClass *parent_class = NULL;
251 static void gst_audio_encoder_class_init (GstAudioEncoderClass * klass);
252 static void gst_audio_encoder_init (GstAudioEncoder * parse,
253 GstAudioEncoderClass * klass);
256 gst_audio_encoder_get_type (void)
258 static GType audio_encoder_type = 0;
260 if (!audio_encoder_type) {
261 static const GTypeInfo audio_encoder_info = {
262 sizeof (GstAudioEncoderClass),
263 (GBaseInitFunc) NULL,
264 (GBaseFinalizeFunc) NULL,
265 (GClassInitFunc) gst_audio_encoder_class_init,
268 sizeof (GstAudioEncoder),
270 (GInstanceInitFunc) gst_audio_encoder_init,
272 const GInterfaceInfo preset_interface_info = {
273 NULL, /* interface_init */
274 NULL, /* interface_finalize */
275 NULL /* interface_data */
278 audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT,
279 "GstAudioEncoder", &audio_encoder_info, G_TYPE_FLAG_ABSTRACT);
281 g_type_add_interface_static (audio_encoder_type, GST_TYPE_PRESET,
282 &preset_interface_info);
284 return audio_encoder_type;
287 static void gst_audio_encoder_finalize (GObject * object);
288 static void gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full);
290 static void gst_audio_encoder_set_property (GObject * object,
291 guint prop_id, const GValue * value, GParamSpec * pspec);
292 static void gst_audio_encoder_get_property (GObject * object,
293 guint prop_id, GValue * value, GParamSpec * pspec);
295 static gboolean gst_audio_encoder_sink_activate_push (GstPad * pad,
298 static gboolean gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event);
299 static gboolean gst_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps);
300 static GstFlowReturn gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer);
301 static gboolean gst_audio_encoder_src_query (GstPad * pad, GstQuery * query);
302 static gboolean gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query);
303 static const GstQueryType *gst_audio_encoder_get_query_types (GstPad * pad);
304 static GstCaps *gst_audio_encoder_sink_getcaps (GstPad * pad);
308 gst_audio_encoder_class_init (GstAudioEncoderClass * klass)
310 GObjectClass *gobject_class;
312 gobject_class = G_OBJECT_CLASS (klass);
313 parent_class = g_type_class_peek_parent (klass);
315 GST_DEBUG_CATEGORY_INIT (gst_audio_encoder_debug, "audioencoder", 0,
316 "audio encoder base class");
318 g_type_class_add_private (klass, sizeof (GstAudioEncoderPrivate));
320 gobject_class->set_property = gst_audio_encoder_set_property;
321 gobject_class->get_property = gst_audio_encoder_get_property;
323 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_audio_encoder_finalize);
326 g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
327 g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps",
328 "Favour perfect timestamps over tracking upstream timestamps",
329 DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
330 g_object_class_install_property (gobject_class, PROP_GRANULE,
331 g_param_spec_boolean ("mark-granule", "Granule Marking",
332 "Apply granule semantics to buffer metadata (implies perfect-timestamp)",
333 DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
334 g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
335 g_param_spec_boolean ("hard-resync", "Hard Resync",
336 "Perform clipping and sample flushing upon discontinuity",
337 DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
338 g_object_class_install_property (gobject_class, PROP_TOLERANCE,
339 g_param_spec_int64 ("tolerance", "Tolerance",
340 "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
341 0, G_MAXINT64, DEFAULT_TOLERANCE,
342 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
346 gst_audio_encoder_init (GstAudioEncoder * enc, GstAudioEncoderClass * bclass)
348 GstPadTemplate *pad_template;
350 GST_DEBUG_OBJECT (enc, "gst_audio_encoder_init");
352 enc->priv = GST_AUDIO_ENCODER_GET_PRIVATE (enc);
354 /* only push mode supported */
356 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
357 g_return_if_fail (pad_template != NULL);
358 enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
359 gst_pad_set_event_function (enc->sinkpad,
360 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_event));
361 gst_pad_set_setcaps_function (enc->sinkpad,
362 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_setcaps));
363 gst_pad_set_getcaps_function (enc->sinkpad,
364 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_getcaps));
365 gst_pad_set_query_function (enc->sinkpad,
366 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_query));
367 gst_pad_set_chain_function (enc->sinkpad,
368 GST_DEBUG_FUNCPTR (gst_audio_encoder_chain));
369 gst_pad_set_activatepush_function (enc->sinkpad,
370 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_activate_push));
371 gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
373 GST_DEBUG_OBJECT (enc, "sinkpad created");
375 /* and we don't mind upstream traveling stuff that much ... */
377 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
378 g_return_if_fail (pad_template != NULL);
379 enc->srcpad = gst_pad_new_from_template (pad_template, "src");
380 gst_pad_set_query_function (enc->srcpad,
381 GST_DEBUG_FUNCPTR (gst_audio_encoder_src_query));
382 gst_pad_set_query_type_function (enc->srcpad,
383 GST_DEBUG_FUNCPTR (gst_audio_encoder_get_query_types));
384 gst_pad_use_fixed_caps (enc->srcpad);
385 gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
386 GST_DEBUG_OBJECT (enc, "src created");
388 enc->priv->adapter = gst_adapter_new ();
390 /* property default */
391 enc->priv->granule = DEFAULT_GRANULE;
392 enc->priv->perfect_ts = DEFAULT_PERFECT_TS;
393 enc->priv->hard_resync = DEFAULT_HARD_RESYNC;
394 enc->priv->tolerance = DEFAULT_TOLERANCE;
397 gst_audio_encoder_reset (enc, TRUE);
398 GST_DEBUG_OBJECT (enc, "init ok");
402 gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full)
404 GST_OBJECT_LOCK (enc);
406 GST_LOG_OBJECT (enc, "reset full %d", full);
409 enc->priv->active = FALSE;
410 enc->priv->samples_in = 0;
411 enc->priv->bytes_out = 0;
412 gst_audio_info_clear (&enc->priv->ctx.info);
413 memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx));
416 gst_tag_list_free (enc->priv->tags);
417 enc->priv->tags = NULL;
420 gst_segment_init (&enc->segment, GST_FORMAT_TIME);
422 gst_adapter_clear (enc->priv->adapter);
423 enc->priv->got_data = FALSE;
424 enc->priv->drained = TRUE;
425 enc->priv->offset = 0;
426 enc->priv->base_ts = GST_CLOCK_TIME_NONE;
427 enc->priv->base_gp = -1;
428 enc->priv->samples = 0;
429 enc->priv->discont = FALSE;
431 GST_OBJECT_UNLOCK (enc);
435 gst_audio_encoder_finalize (GObject * object)
437 GstAudioEncoder *enc = GST_AUDIO_ENCODER (object);
439 g_object_unref (enc->priv->adapter);
441 G_OBJECT_CLASS (parent_class)->finalize (object);
445 * gst_audio_encoder_finish_frame:
446 * @enc: a #GstAudioEncoder
447 * @buffer: encoded data
448 * @samples: number of samples (per channel) represented by encoded data
450 * Collects encoded data and/or pushes encoded data downstream.
451 * Source pad caps must be set when this is called. Depending on the nature
452 * of the (framing of) the format, subclass can decide whether to push
453 * encoded data directly or to collect various "frames" in a single buffer.
454 * Note that the latter behaviour is recommended whenever the format is allowed,
455 * as it incurs no additional latency and avoids otherwise generating a
456 * a multitude of (small) output buffers. If not explicitly pushed,
457 * any available encoded data is pushed at the end of each processing cycle,
458 * i.e. which encodes as much data as available input data allows.
460 * If @samples < 0, then best estimate is all samples provided to encoder
461 * (subclass) so far. @buf may be NULL, in which case next number of @samples
462 * are considered discarded, e.g. as a result of discontinuous transmission,
463 * and a discontinuity is marked (note that @buf == NULL => push == TRUE).
465 * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
470 gst_audio_encoder_finish_frame (GstAudioEncoder * enc, GstBuffer * buf,
473 GstAudioEncoderClass *klass;
474 GstAudioEncoderPrivate *priv;
475 GstAudioEncoderContext *ctx;
476 GstFlowReturn ret = GST_FLOW_OK;
478 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
480 ctx = &enc->priv->ctx;
482 /* subclass should know what it is producing by now */
483 g_return_val_if_fail (GST_PAD_CAPS (enc->srcpad) != NULL, GST_FLOW_ERROR);
484 /* subclass should not hand us no data */
485 g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0,
488 if (G_UNLIKELY (enc->priv->tags)) {
491 /* add codec info to pending tags */
492 tags = enc->priv->tags;
493 /* no more pending */
494 enc->priv->tags = NULL;
495 gst_pb_utils_add_codec_description_to_tag_list (tags, GST_TAG_CODEC,
496 GST_PAD_CAPS (enc->srcpad));
497 gst_pb_utils_add_codec_description_to_tag_list (tags, GST_TAG_AUDIO_CODEC,
498 GST_PAD_CAPS (enc->srcpad));
499 GST_DEBUG_OBJECT (enc, "sending tags %" GST_PTR_FORMAT, tags);
500 gst_element_found_tags_for_pad (GST_ELEMENT (enc), enc->srcpad, tags);
503 GST_LOG_OBJECT (enc, "accepting %d bytes encoded data as %d samples",
504 buf ? GST_BUFFER_SIZE (buf) : -1, samples);
506 /* mark subclass still alive and providing */
507 priv->got_data = TRUE;
509 /* remove corresponding samples from input */
511 samples = (enc->priv->offset / ctx->info.bpf);
513 if (G_LIKELY (samples)) {
514 /* track upstream ts if so configured */
515 if (!enc->priv->perfect_ts) {
516 guint64 ts, distance;
518 ts = gst_adapter_prev_timestamp (priv->adapter, &distance);
519 g_assert (distance % ctx->info.bpf == 0);
520 distance /= ctx->info.bpf;
521 GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
522 GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
523 GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
524 GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
525 /* when draining adapter might be empty and no ts to offer */
526 if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
527 GstClockTimeDiff diff;
528 GstClockTime old_ts, next_ts;
530 /* passed into another buffer;
531 * mild check for discontinuity and only mark if so */
533 gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate);
534 old_ts = priv->base_ts +
535 gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
536 diff = GST_CLOCK_DIFF (next_ts, old_ts);
537 GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
538 /* only mark discontinuity if beyond tolerance */
539 if (G_UNLIKELY (diff < -enc->priv->tolerance ||
540 diff > enc->priv->tolerance)) {
541 GST_DEBUG_OBJECT (enc, "marked discont");
542 priv->discont = TRUE;
544 if (diff > GST_SECOND / ctx->info.rate / 2 ||
545 diff < -GST_SECOND / ctx->info.rate / 2) {
546 GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
547 " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
548 /* re-sync to upstream ts */
550 priv->samples = distance;
552 GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter");
556 /* advance sample view */
557 if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) {
558 if (G_LIKELY (!priv->force)) {
559 /* no way we can let this pass */
560 g_assert_not_reached ();
565 if (samples * ctx->info.bpf >= gst_adapter_available (priv->adapter))
566 gst_adapter_clear (priv->adapter);
568 gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
571 gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
572 priv->offset -= samples * ctx->info.bpf;
573 /* avoid subsequent stray prev_ts */
574 if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
575 gst_adapter_clear (priv->adapter);
577 /* sample count advanced below after buffer handling */
581 if (G_LIKELY (buf)) {
582 GST_LOG_OBJECT (enc, "taking %d bytes for output", GST_BUFFER_SIZE (buf));
583 buf = gst_buffer_make_metadata_writable (buf);
586 gst_buffer_set_caps (buf, GST_PAD_CAPS (enc->srcpad));
587 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
588 /* FIXME ? lookahead could lead to weird ts and duration ?
589 * (particularly if not in perfect mode) */
590 /* mind sample rounding and produce perfect output */
591 GST_BUFFER_TIMESTAMP (buf) = priv->base_ts +
592 gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
594 GST_DEBUG_OBJECT (enc, "out samples %d", samples);
595 if (G_LIKELY (samples > 0)) {
596 priv->samples += samples;
597 GST_BUFFER_DURATION (buf) = priv->base_ts +
598 gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
599 ctx->info.rate) - GST_BUFFER_TIMESTAMP (buf);
600 priv->last_duration = GST_BUFFER_DURATION (buf);
602 /* duration forecast in case of handling remainder;
603 * the last one is probably like the previous one ... */
604 GST_BUFFER_DURATION (buf) = priv->last_duration;
606 if (priv->base_gp >= 0) {
608 /* FIXME: in longer run, muxer should take care of this ... */
609 /* offset_end = granulepos for ogg muxer */
610 GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
611 enc->priv->ctx.lookahead;
612 /* offset = timestamp corresponding to granulepos for ogg muxer */
613 GST_BUFFER_OFFSET (buf) =
614 GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
617 GST_BUFFER_OFFSET (buf) = priv->bytes_out;
618 GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + GST_BUFFER_SIZE (buf);
622 priv->bytes_out += GST_BUFFER_SIZE (buf);
624 if (G_UNLIKELY (priv->discont)) {
625 GST_LOG_OBJECT (enc, "marking discont");
626 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
627 priv->discont = FALSE;
630 if (klass->pre_push) {
631 /* last chance for subclass to do some dirty stuff */
632 ret = klass->pre_push (enc, &buf);
633 if (ret != GST_FLOW_OK || !buf) {
634 GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
635 gst_flow_get_name (ret), buf);
637 gst_buffer_unref (buf);
642 GST_LOG_OBJECT (enc, "pushing buffer of size %d with ts %" GST_TIME_FORMAT
643 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
644 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
645 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
647 ret = gst_pad_push (enc->srcpad, buf);
648 GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
650 /* merely advance samples, most work for that already done above */
651 priv->samples += samples;
660 GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
661 ("received more encoded samples %d than provided %d",
662 samples, priv->offset / ctx->info.bpf), (NULL));
664 gst_buffer_unref (buf);
665 return GST_FLOW_ERROR;
669 /* adapter tracking idea:
670 * - start of adapter corresponds with what has already been encoded
671 * (i.e. really returned by encoder subclass)
672 * - start + offset is what needs to be fed to subclass next */
674 gst_audio_encoder_push_buffers (GstAudioEncoder * enc, gboolean force)
676 GstAudioEncoderClass *klass;
677 GstAudioEncoderPrivate *priv;
678 GstAudioEncoderContext *ctx;
681 GstFlowReturn ret = GST_FLOW_OK;
683 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
685 g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
688 ctx = &enc->priv->ctx;
690 while (ret == GST_FLOW_OK) {
693 av = gst_adapter_available (priv->adapter);
695 g_assert (priv->offset <= av);
698 need = ctx->frame_samples > 0 ? ctx->frame_samples * ctx->info.bpf : av;
699 GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d",
702 if ((need > av) || !av) {
703 if (G_UNLIKELY (force)) {
713 /* if we have some extra metadata,
714 * provide for integer multiple of frames to allow for better granularity
716 if (ctx->frame_samples > 0 && need) {
717 if (ctx->frame_max > 1)
718 need = need * MIN ((av / need), ctx->frame_max);
719 else if (ctx->frame_max == 0)
720 need = need * (av / need);
724 buf = gst_buffer_new ();
725 GST_BUFFER_DATA (buf) = (guint8 *)
726 gst_adapter_peek (priv->adapter, priv->offset + need) + priv->offset;
727 GST_BUFFER_SIZE (buf) = need;
730 GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
733 /* mark this already as consumed,
734 * which it should be when subclass gives us data in exchange for samples */
735 priv->offset += need;
736 priv->samples_in += need / ctx->info.bpf;
738 priv->got_data = FALSE;
739 ret = klass->handle_frame (enc, buf);
742 gst_buffer_unref (buf);
744 /* no data to feed, no leftover provided, then bail out */
745 if (G_UNLIKELY (!buf && !priv->got_data)) {
746 priv->drained = TRUE;
747 GST_LOG_OBJECT (enc, "no more data drained from subclass");
756 gst_audio_encoder_drain (GstAudioEncoder * enc)
758 if (enc->priv->drained)
761 return gst_audio_encoder_push_buffers (enc, TRUE);
765 gst_audio_encoder_set_base_gp (GstAudioEncoder * enc)
769 if (!enc->priv->granule)
772 /* use running time for granule */
773 /* incoming data is clipped, so a valid input should yield a valid output */
774 ts = gst_segment_to_running_time (&enc->segment, GST_FORMAT_TIME,
776 if (GST_CLOCK_TIME_IS_VALID (ts)) {
778 GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate);
779 GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
781 /* should reasonably have a valid base,
782 * otherwise start at 0 if we did not already start there earlier */
783 if (enc->priv->base_gp < 0) {
784 enc->priv->base_gp = 0;
785 GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
792 gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer)
794 GstAudioEncoder *enc;
795 GstAudioEncoderPrivate *priv;
796 GstAudioEncoderContext *ctx;
797 GstFlowReturn ret = GST_FLOW_OK;
800 enc = GST_AUDIO_ENCODER (GST_OBJECT_PARENT (pad));
803 ctx = &enc->priv->ctx;
805 /* should know what is coming by now */
810 "received buffer of size %d with ts %" GST_TIME_FORMAT
811 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
812 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
813 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
815 /* input shoud be whole number of sample frames */
816 if (GST_BUFFER_SIZE (buffer) % ctx->info.bpf)
819 #ifndef GST_DISABLE_GST_DEBUG
821 GstClockTime duration;
822 GstClockTimeDiff diff;
824 /* verify buffer duration */
825 duration = gst_util_uint64_scale (GST_BUFFER_SIZE (buffer), GST_SECOND,
826 ctx->info.rate * ctx->info.bpf);
827 diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
828 if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
829 (diff > GST_SECOND / ctx->info.rate / 2 ||
830 diff < -GST_SECOND / ctx->info.rate / 2)) {
831 GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
832 GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
833 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
834 GST_TIME_ARGS (duration));
839 discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
840 if (G_UNLIKELY (discont)) {
841 GST_LOG_OBJECT (buffer, "marked discont");
842 enc->priv->discont = discont;
845 /* clip to segment */
846 /* NOTE: slightly painful linking -laudio only for this one ... */
847 buffer = gst_audio_buffer_clip (buffer, &enc->segment, ctx->info.rate,
849 if (G_UNLIKELY (!buffer)) {
850 GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
855 "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT
856 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
857 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
858 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
860 if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
861 priv->base_ts = GST_BUFFER_TIMESTAMP (buffer);
862 GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
863 GST_TIME_ARGS (priv->base_ts));
864 gst_audio_encoder_set_base_gp (enc);
867 /* check for continuity;
868 * checked elsewhere in non-perfect case */
869 if (enc->priv->perfect_ts) {
870 GstClockTimeDiff diff = 0;
871 GstClockTime next_ts = 0;
873 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
874 GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
877 samples = priv->samples +
878 gst_adapter_available (priv->adapter) / ctx->info.bpf;
879 next_ts = priv->base_ts +
880 gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
881 GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
882 " samples past base_ts %" GST_TIME_FORMAT
883 ", expected ts %" GST_TIME_FORMAT, samples,
884 GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
885 diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer));
886 GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
887 /* if within tolerance,
888 * discard buffer ts and carry on producing perfect stream,
889 * otherwise clip or resync to ts */
890 if (G_UNLIKELY (diff < -enc->priv->tolerance ||
891 diff > enc->priv->tolerance)) {
892 GST_DEBUG_OBJECT (enc, "marked discont");
897 /* do some fancy tweaking in hard resync case */
898 if (discont && enc->priv->hard_resync) {
902 GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
903 GST_TIME_FORMAT ". Clipping buffer", GST_TIME_ARGS (next_ts));
906 GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf;
907 if (diff_bytes >= GST_BUFFER_SIZE (buffer)) {
908 gst_buffer_unref (buffer);
911 buffer = gst_buffer_make_metadata_writable (buffer);
912 GST_BUFFER_DATA (buffer) += diff_bytes;
913 GST_BUFFER_SIZE (buffer) -= diff_bytes;
915 GST_BUFFER_TIMESTAMP (buffer) += diff;
916 /* care even less about duration after this */
918 /* drain stuff prior to resync */
919 gst_audio_encoder_drain (enc);
923 priv->base_ts += diff;
924 gst_audio_encoder_set_base_gp (enc);
925 priv->discont |= discont;
928 gst_adapter_push (enc->priv->adapter, buffer);
929 /* new stuff, so we can push subclass again */
930 enc->priv->drained = FALSE;
932 ret = gst_audio_encoder_push_buffers (enc, FALSE);
935 GST_LOG_OBJECT (enc, "chain leaving");
941 GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
942 ("encoder not initialized"));
943 gst_buffer_unref (buffer);
944 return GST_FLOW_NOT_NEGOTIATED;
948 GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
949 ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buffer),
951 gst_buffer_unref (buffer);
952 return GST_FLOW_ERROR;
957 audio_info_is_equal (GstAudioInfo * from, GstAudioInfo * to)
961 if (from->finfo == NULL || to->finfo == NULL)
963 if (GST_AUDIO_INFO_FORMAT (from) != GST_AUDIO_INFO_FORMAT (to))
965 if (GST_AUDIO_INFO_RATE (from) != GST_AUDIO_INFO_RATE (to))
967 if (GST_AUDIO_INFO_CHANNELS (from) != GST_AUDIO_INFO_CHANNELS (to))
969 if (GST_AUDIO_INFO_CHANNELS (from) > 64)
971 return memcmp (from->position, to->position,
972 GST_AUDIO_INFO_CHANNELS (from) * sizeof (to->position[0]));
976 gst_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps)
978 GstAudioEncoder *enc;
979 GstAudioEncoderClass *klass;
980 GstAudioEncoderContext *ctx;
981 GstAudioInfo *state, *old_state;
982 gboolean res = TRUE, changed = FALSE;
985 enc = GST_AUDIO_ENCODER (GST_PAD_PARENT (pad));
986 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
988 /* subclass must do something here ... */
989 g_return_val_if_fail (klass->set_format != NULL, FALSE);
991 ctx = &enc->priv->ctx;
994 GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
996 if (!gst_caps_is_fixed (caps))
999 /* adjust ts tracking to new sample rate */
1000 old_rate = GST_AUDIO_INFO_RATE (state);
1001 if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) {
1002 enc->priv->base_ts +=
1003 GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate);
1004 enc->priv->samples = 0;
1007 old_state = gst_audio_info_copy (state);
1008 if (!gst_audio_info_from_caps (state, caps))
1011 changed = !audio_info_is_equal (state, old_state);
1012 gst_audio_info_free (old_state);
1015 GstClockTime old_min_latency;
1016 GstClockTime old_max_latency;
1018 /* drain any pending old data stuff */
1019 gst_audio_encoder_drain (enc);
1021 /* context defaults */
1022 enc->priv->ctx.frame_samples = 0;
1023 enc->priv->ctx.frame_max = 0;
1024 enc->priv->ctx.lookahead = 0;
1026 /* element might report latency */
1027 GST_OBJECT_LOCK (enc);
1028 old_min_latency = ctx->min_latency;
1029 old_max_latency = ctx->max_latency;
1030 GST_OBJECT_UNLOCK (enc);
1032 if (klass->set_format)
1033 res = klass->set_format (enc, state);
1035 /* notify if new latency */
1036 GST_OBJECT_LOCK (enc);
1037 if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) ||
1038 (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) {
1039 GST_OBJECT_UNLOCK (enc);
1040 /* post latency message on the bus */
1041 gst_element_post_message (GST_ELEMENT (enc),
1042 gst_message_new_latency (GST_OBJECT (enc)));
1043 GST_OBJECT_LOCK (enc);
1045 GST_OBJECT_UNLOCK (enc);
1047 GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
1055 GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
1062 * gst_audio_encoder_proxy_getcaps:
1063 * @enc: a #GstAudioEncoder
1064 * @caps: initial caps
1066 * Returns caps that express @caps (or sink template caps if @caps == NULL)
1067 * restricted to channel/rate combinations supported by downstream elements
1070 * Returns: a #GstCaps owned by caller
1075 gst_audio_encoder_proxy_getcaps (GstAudioEncoder * enc, GstCaps * caps)
1077 const GstCaps *templ_caps;
1078 GstCaps *allowed = NULL;
1079 GstCaps *fcaps, *filter_caps;
1082 /* we want to be able to communicate to upstream elements like audioconvert
1083 * and audioresample any rate/channel restrictions downstream (e.g. muxer
1084 * only accepting certain sample rates) */
1085 templ_caps = caps ? caps : gst_pad_get_pad_template_caps (enc->sinkpad);
1086 allowed = gst_pad_get_allowed_caps (enc->srcpad);
1087 if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
1088 fcaps = gst_caps_copy (templ_caps);
1092 GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps);
1093 GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
1095 filter_caps = gst_caps_new_empty ();
1097 for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
1100 q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
1102 /* pick rate + channel fields from allowed caps */
1103 for (j = 0; j < gst_caps_get_size (allowed); j++) {
1104 const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
1108 s = gst_structure_id_empty_new (q_name);
1109 if ((val = gst_structure_get_value (allowed_s, "rate")))
1110 gst_structure_set_value (s, "rate", val);
1111 if ((val = gst_structure_get_value (allowed_s, "channels")))
1112 gst_structure_set_value (s, "channels", val);
1113 /* following might also make sense for some encoded formats,
1115 if ((val = gst_structure_get_value (allowed_s, "width")))
1116 gst_structure_set_value (s, "width", val);
1117 if ((val = gst_structure_get_value (allowed_s, "depth")))
1118 gst_structure_set_value (s, "depth", val);
1119 if ((val = gst_structure_get_value (allowed_s, "endianness")))
1120 gst_structure_set_value (s, "endianness", val);
1121 if ((val = gst_structure_get_value (allowed_s, "signed")))
1122 gst_structure_set_value (s, "signed", val);
1123 if ((val = gst_structure_get_value (allowed_s, "channel-positions")))
1124 gst_structure_set_value (s, "channel-positions", val);
1126 gst_caps_merge_structure (filter_caps, s);
1130 fcaps = gst_caps_intersect (filter_caps, templ_caps);
1131 gst_caps_unref (filter_caps);
1134 gst_caps_replace (&allowed, NULL);
1136 GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
1142 gst_audio_encoder_sink_getcaps (GstPad * pad)
1144 GstAudioEncoder *enc;
1145 GstAudioEncoderClass *klass;
1148 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1149 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1150 g_assert (pad == enc->sinkpad);
1153 caps = klass->getcaps (enc);
1155 caps = gst_audio_encoder_proxy_getcaps (enc, NULL);
1156 gst_object_unref (enc);
1158 GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1164 gst_audio_encoder_sink_eventfunc (GstAudioEncoder * enc, GstEvent * event)
1166 GstAudioEncoderClass *klass;
1167 gboolean handled = FALSE;
1169 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1171 switch (GST_EVENT_TYPE (event)) {
1172 case GST_EVENT_NEWSEGMENT:
1175 gdouble rate, arate;
1176 gint64 start, stop, time;
1179 gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
1180 &start, &stop, &time);
1182 if (format == GST_FORMAT_TIME) {
1183 GST_DEBUG_OBJECT (enc, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT
1184 " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT
1185 ", rate %g, applied_rate %g",
1186 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time),
1189 GST_DEBUG_OBJECT (enc, "received NEW_SEGMENT %" G_GINT64_FORMAT
1190 " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT
1191 ", rate %g, applied_rate %g", start, stop, time, rate, arate);
1192 GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1196 /* finish current segment */
1197 gst_audio_encoder_drain (enc);
1198 /* reset partially for new segment */
1199 gst_audio_encoder_reset (enc, FALSE);
1200 /* and follow along with segment */
1201 gst_segment_set_newsegment_full (&enc->segment, update, rate, arate,
1202 format, start, stop, time);
1206 case GST_EVENT_FLUSH_START:
1209 case GST_EVENT_FLUSH_STOP:
1210 /* discard any pending stuff */
1211 /* TODO route through drain ?? */
1212 if (!enc->priv->drained && klass->flush)
1214 /* and get (re)set for the sequel */
1215 gst_audio_encoder_reset (enc, FALSE);
1219 gst_audio_encoder_drain (enc);
1226 gst_event_parse_tag (event, &tags);
1227 tags = gst_tag_list_copy (tags);
1228 gst_event_unref (event);
1229 gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1230 gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1231 event = gst_event_new_tag (tags);
1233 gst_pad_push_event (enc->srcpad, event);
1246 gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event)
1248 GstAudioEncoder *enc;
1249 GstAudioEncoderClass *klass;
1250 gboolean handled = FALSE;
1251 gboolean ret = TRUE;
1253 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1254 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1256 GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1257 GST_EVENT_TYPE_NAME (event));
1260 handled = klass->event (enc, event);
1263 handled = gst_audio_encoder_sink_eventfunc (enc, event);
1266 ret = gst_pad_event_default (pad, event);
1268 GST_DEBUG_OBJECT (enc, "event handled");
1270 gst_object_unref (enc);
1275 gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query)
1277 gboolean res = TRUE;
1278 GstAudioEncoder *enc;
1280 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1282 switch (GST_QUERY_TYPE (query)) {
1283 case GST_QUERY_FORMATS:
1285 gst_query_set_formats (query, 3,
1286 GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1290 case GST_QUERY_CONVERT:
1292 GstFormat src_fmt, dest_fmt;
1293 gint64 src_val, dest_val;
1295 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1296 if (!(res = gst_audio_info_convert (&enc->priv->ctx.info,
1297 src_fmt, src_val, dest_fmt, &dest_val)))
1299 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1303 res = gst_pad_query_default (pad, query);
1308 gst_object_unref (enc);
1312 static const GstQueryType *
1313 gst_audio_encoder_get_query_types (GstPad * pad)
1315 static const GstQueryType gst_audio_encoder_src_query_types[] = {
1323 return gst_audio_encoder_src_query_types;
1327 * gst_audio_encoded_audio_convert:
1328 * @fmt: audio format of the encoded audio
1329 * @bytes: number of encoded bytes
1330 * @samples: number of encoded samples
1331 * @src_format: source format
1332 * @src_value: source value
1333 * @dest_format: destination format
1334 * @dest_value: destination format
1336 * Helper function to convert @src_value in @src_format to @dest_value in
1337 * @dest_format for encoded audio data. Conversion is possible between
1338 * BYTE and TIME format by using estimated bitrate based on
1339 * @samples and @bytes (and @fmt).
1343 /* FIXME: make gst_audio_encoded_audio_convert() public? */
1345 gst_audio_encoded_audio_convert (GstAudioInfo * fmt,
1346 gint64 bytes, gint64 samples, GstFormat src_format,
1347 gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
1349 gboolean res = FALSE;
1351 g_return_val_if_fail (dest_format != NULL, FALSE);
1352 g_return_val_if_fail (dest_value != NULL, FALSE);
1354 if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
1357 *dest_value = src_value;
1361 if (samples == 0 || bytes == 0 || fmt->rate == 0) {
1362 GST_DEBUG ("not enough metadata yet to convert");
1368 switch (src_format) {
1369 case GST_FORMAT_BYTES:
1370 switch (*dest_format) {
1371 case GST_FORMAT_TIME:
1372 *dest_value = gst_util_uint64_scale (src_value,
1373 GST_SECOND * samples, bytes);
1380 case GST_FORMAT_TIME:
1381 switch (*dest_format) {
1382 case GST_FORMAT_BYTES:
1383 *dest_value = gst_util_uint64_scale (src_value, bytes,
1384 samples * GST_SECOND);
1399 /* FIXME ? are any of these queries (other than latency) an encoder's business
1400 * also, the conversion stuff might seem to make sense, but seems to not mind
1401 * segment stuff etc at all
1402 * Supposedly that's backward compatibility ... */
1404 gst_audio_encoder_src_query (GstPad * pad, GstQuery * query)
1406 GstAudioEncoder *enc;
1408 gboolean res = FALSE;
1410 enc = GST_AUDIO_ENCODER (GST_PAD_PARENT (pad));
1411 peerpad = gst_pad_get_peer (GST_PAD (enc->sinkpad));
1413 GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1415 switch (GST_QUERY_TYPE (query)) {
1416 case GST_QUERY_POSITION:
1418 GstFormat fmt, req_fmt;
1421 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1422 GST_LOG_OBJECT (enc, "returning peer response");
1427 GST_LOG_OBJECT (enc, "no peer");
1431 gst_query_parse_position (query, &req_fmt, NULL);
1432 fmt = GST_FORMAT_TIME;
1433 if (!(res = gst_pad_query_position (peerpad, &fmt, &pos)))
1436 if ((res = gst_pad_query_convert (peerpad, fmt, pos, &req_fmt, &val))) {
1437 gst_query_set_position (query, req_fmt, val);
1441 case GST_QUERY_DURATION:
1443 GstFormat fmt, req_fmt;
1446 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1447 GST_LOG_OBJECT (enc, "returning peer response");
1452 GST_LOG_OBJECT (enc, "no peer");
1456 gst_query_parse_duration (query, &req_fmt, NULL);
1457 fmt = GST_FORMAT_TIME;
1458 if (!(res = gst_pad_query_duration (peerpad, &fmt, &dur)))
1461 if ((res = gst_pad_query_convert (peerpad, fmt, dur, &req_fmt, &val))) {
1462 gst_query_set_duration (query, req_fmt, val);
1466 case GST_QUERY_FORMATS:
1468 gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1472 case GST_QUERY_CONVERT:
1474 GstFormat src_fmt, dest_fmt;
1475 gint64 src_val, dest_val;
1477 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1478 if (!(res = gst_audio_encoded_audio_convert (&enc->priv->ctx.info,
1479 enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
1480 &dest_fmt, &dest_val)))
1482 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1485 case GST_QUERY_LATENCY:
1487 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1489 GstClockTime min_latency, max_latency;
1491 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1492 GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1493 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1494 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1496 GST_OBJECT_LOCK (enc);
1497 /* add our latency */
1498 if (min_latency != -1)
1499 min_latency += enc->priv->ctx.min_latency;
1500 if (max_latency != -1)
1501 max_latency += enc->priv->ctx.max_latency;
1502 GST_OBJECT_UNLOCK (enc);
1504 gst_query_set_latency (query, live, min_latency, max_latency);
1509 res = gst_pad_query_default (pad, query);
1513 gst_object_unref (peerpad);
1518 gst_audio_encoder_set_property (GObject * object, guint prop_id,
1519 const GValue * value, GParamSpec * pspec)
1521 GstAudioEncoder *enc;
1523 enc = GST_AUDIO_ENCODER (object);
1526 case PROP_PERFECT_TS:
1527 if (enc->priv->granule && !g_value_get_boolean (value))
1528 GST_WARNING_OBJECT (enc, "perfect-timestamp can not be set FALSE "
1529 "while granule handling is enabled");
1531 enc->priv->perfect_ts = g_value_get_boolean (value);
1533 case PROP_HARD_RESYNC:
1534 enc->priv->hard_resync = g_value_get_boolean (value);
1536 case PROP_TOLERANCE:
1537 enc->priv->tolerance = g_value_get_int64 (value);
1540 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1546 gst_audio_encoder_get_property (GObject * object, guint prop_id,
1547 GValue * value, GParamSpec * pspec)
1549 GstAudioEncoder *enc;
1551 enc = GST_AUDIO_ENCODER (object);
1554 case PROP_PERFECT_TS:
1555 g_value_set_boolean (value, enc->priv->perfect_ts);
1558 g_value_set_boolean (value, enc->priv->granule);
1560 case PROP_HARD_RESYNC:
1561 g_value_set_boolean (value, enc->priv->hard_resync);
1563 case PROP_TOLERANCE:
1564 g_value_set_int64 (value, enc->priv->tolerance);
1567 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1573 gst_audio_encoder_activate (GstAudioEncoder * enc, gboolean active)
1575 GstAudioEncoderClass *klass;
1576 gboolean result = FALSE;
1578 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1580 g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE);
1582 GST_DEBUG_OBJECT (enc, "activate %d", active);
1586 if (enc->priv->tags)
1587 gst_tag_list_free (enc->priv->tags);
1588 enc->priv->tags = gst_tag_list_new ();
1590 if (!enc->priv->active && klass->start)
1591 result = klass->start (enc);
1593 /* We must make sure streaming has finished before resetting things
1594 * and calling the ::stop vfunc */
1595 GST_PAD_STREAM_LOCK (enc->sinkpad);
1596 GST_PAD_STREAM_UNLOCK (enc->sinkpad);
1598 if (enc->priv->active && klass->stop)
1599 result = klass->stop (enc);
1602 gst_audio_encoder_reset (enc, TRUE);
1604 GST_DEBUG_OBJECT (enc, "activate return: %d", result);
1610 gst_audio_encoder_sink_activate_push (GstPad * pad, gboolean active)
1612 gboolean result = TRUE;
1613 GstAudioEncoder *enc;
1615 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1617 GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
1619 result = gst_audio_encoder_activate (enc, active);
1622 enc->priv->active = active;
1624 GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
1626 gst_object_unref (enc);
1631 * gst_audio_encoder_get_audio_info:
1632 * @enc: a #GstAudioEncoder
1634 * Returns: a #GstAudioInfo describing the input audio format
1639 gst_audio_encoder_get_audio_info (GstAudioEncoder * enc)
1641 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), NULL);
1643 return &enc->priv->ctx.info;
1647 * gst_audio_encoder_set_frame_samples:
1648 * @enc: a #GstAudioEncoder
1649 * @num: number of samples per frame
1651 * Sets number of samples (per channel) subclass needs to be handed,
1652 * or will be handed all available if 0.
1657 gst_audio_encoder_set_frame_samples (GstAudioEncoder * enc, gint num)
1659 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1661 enc->priv->ctx.frame_samples = num;
1665 * gst_audio_encoder_get_frame_samples:
1666 * @enc: a #GstAudioEncoder
1668 * Returns: currently requested samples per frame
1673 gst_audio_encoder_get_frame_samples (GstAudioEncoder * enc)
1675 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1677 return enc->priv->ctx.frame_samples;
1681 * gst_audio_encoder_set_frame_max:
1682 * @enc: a #GstAudioEncoder
1683 * @num: number of frames
1685 * Sets max number of frames accepted at once (assumed minimally 1)
1690 gst_audio_encoder_set_frame_max (GstAudioEncoder * enc, gint num)
1692 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1694 enc->priv->ctx.frame_max = num;
1698 * gst_audio_encoder_get_frame_max:
1699 * @enc: a #GstAudioEncoder
1701 * Returns: currently configured maximum handled frames
1706 gst_audio_encoder_get_frame_max (GstAudioEncoder * enc)
1708 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1710 return enc->priv->ctx.frame_max;
1714 * gst_audio_encoder_set_lookahead:
1715 * @enc: a #GstAudioEncoder
1718 * Sets encoder lookahead (in units of input rate samples)
1723 gst_audio_encoder_set_lookahead (GstAudioEncoder * enc, gint num)
1725 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1727 enc->priv->ctx.lookahead = num;
1731 * gst_audio_encoder_get_lookahead:
1732 * @enc: a #GstAudioEncoder
1734 * Returns: currently configured encoder lookahead
1737 gst_audio_encoder_get_lookahead (GstAudioEncoder * enc)
1739 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1741 return enc->priv->ctx.lookahead;
1745 * gst_audio_encoder_set_latency:
1746 * @enc: a #GstAudioEncoder
1747 * @min: minimum latency
1748 * @max: maximum latency
1750 * Sets encoder latency.
1755 gst_audio_encoder_set_latency (GstAudioEncoder * enc,
1756 GstClockTime min, GstClockTime max)
1758 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1760 GST_OBJECT_LOCK (enc);
1761 enc->priv->ctx.min_latency = min;
1762 enc->priv->ctx.max_latency = max;
1763 GST_OBJECT_UNLOCK (enc);
1767 * gst_audio_encoder_get_latency:
1768 * @enc: a #GstAudioEncoder
1769 * @min: (out) (allow-none): a pointer to storage to hold minimum latency
1770 * @max: (out) (allow-none): a pointer to storage to hold maximum latency
1772 * Sets the variables pointed to by @min and @max to the currently configured
1778 gst_audio_encoder_get_latency (GstAudioEncoder * enc,
1779 GstClockTime * min, GstClockTime * max)
1781 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1783 GST_OBJECT_LOCK (enc);
1785 *min = enc->priv->ctx.min_latency;
1787 *max = enc->priv->ctx.max_latency;
1788 GST_OBJECT_UNLOCK (enc);
1792 * gst_audio_encoder_set_mark_granule:
1793 * @enc: a #GstAudioEncoder
1794 * @enabled: new state
1796 * Enable or disable encoder granule handling.
1803 gst_audio_encoder_set_mark_granule (GstAudioEncoder * enc, gboolean enabled)
1805 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1807 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1809 GST_OBJECT_LOCK (enc);
1810 enc->priv->granule = enabled;
1811 GST_OBJECT_UNLOCK (enc);
1815 * gst_audio_encoder_get_mark_granule:
1816 * @enc: a #GstAudioEncoder
1818 * Queries if the encoder will handle granule marking.
1820 * Returns: TRUE if granule marking is enabled.
1827 gst_audio_encoder_get_mark_granule (GstAudioEncoder * enc)
1831 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1833 GST_OBJECT_LOCK (enc);
1834 result = enc->priv->granule;
1835 GST_OBJECT_UNLOCK (enc);
1841 * gst_audio_encoder_set_perfect_timestamp:
1842 * @enc: a #GstAudioEncoder
1843 * @enabled: new state
1845 * Enable or disable encoder perfect output timestamp preference.
1852 gst_audio_encoder_set_perfect_timestamp (GstAudioEncoder * enc,
1855 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1857 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1859 GST_OBJECT_LOCK (enc);
1860 enc->priv->perfect_ts = enabled;
1861 GST_OBJECT_UNLOCK (enc);
1865 * gst_audio_encoder_get_perfect_timestamp:
1866 * @enc: a #GstAudioEncoder
1868 * Queries encoder perfect timestamp behaviour.
1870 * Returns: TRUE if pefect timestamp setting enabled.
1877 gst_audio_encoder_get_perfect_timestamp (GstAudioEncoder * enc)
1881 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1883 GST_OBJECT_LOCK (enc);
1884 result = enc->priv->perfect_ts;
1885 GST_OBJECT_UNLOCK (enc);
1891 * gst_audio_encoder_set_hard_sync:
1892 * @enc: a #GstAudioEncoder
1893 * @enabled: new state
1895 * Sets encoder hard resync handling.
1902 gst_audio_encoder_set_hard_resync (GstAudioEncoder * enc, gboolean enabled)
1904 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1906 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1908 GST_OBJECT_LOCK (enc);
1909 enc->priv->hard_resync = enabled;
1910 GST_OBJECT_UNLOCK (enc);
1914 * gst_audio_encoder_get_hard_sync:
1915 * @enc: a #GstAudioEncoder
1917 * Queries encoder's hard resync setting.
1919 * Returns: TRUE if hard resync is enabled.
1926 gst_audio_encoder_get_hard_resync (GstAudioEncoder * enc)
1930 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1932 GST_OBJECT_LOCK (enc);
1933 result = enc->priv->hard_resync;
1934 GST_OBJECT_UNLOCK (enc);
1940 * gst_audio_encoder_set_tolerance:
1941 * @enc: a #GstAudioEncoder
1942 * @tolerance: new tolerance
1944 * Configures encoder audio jitter tolerance threshold.
1951 gst_audio_encoder_set_tolerance (GstAudioEncoder * enc, gint64 tolerance)
1953 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1955 GST_OBJECT_LOCK (enc);
1956 enc->priv->tolerance = tolerance;
1957 GST_OBJECT_UNLOCK (enc);
1961 * gst_audio_encoder_get_tolerance:
1962 * @enc: a #GstAudioEncoder
1964 * Queries current audio jitter tolerance threshold.
1966 * Returns: encoder audio jitter tolerance threshold.
1973 gst_audio_encoder_get_tolerance (GstAudioEncoder * enc)
1977 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1979 GST_OBJECT_LOCK (enc);
1980 result = enc->priv->tolerance;
1981 GST_OBJECT_UNLOCK (enc);