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;
246 /* pending serialized sink events, will be sent from finish_frame() */
247 GList *pending_events;
250 static void gst_audio_encoder_finalize (GObject * object);
251 static void gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full);
253 static void gst_audio_encoder_set_property (GObject * object,
254 guint prop_id, const GValue * value, GParamSpec * pspec);
255 static void gst_audio_encoder_get_property (GObject * object,
256 guint prop_id, GValue * value, GParamSpec * pspec);
258 static gboolean gst_audio_encoder_sink_activate_push (GstPad * pad,
261 static gboolean gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event);
262 static gboolean gst_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps);
263 static GstFlowReturn gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer);
264 static gboolean gst_audio_encoder_src_query (GstPad * pad, GstQuery * query);
265 static gboolean gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query);
266 static const GstQueryType *gst_audio_encoder_get_query_types (GstPad * pad);
267 static GstCaps *gst_audio_encoder_sink_getcaps (GstPad * pad);
270 do_init (GType gtype)
272 const GInterfaceInfo preset_interface_info = {
273 NULL, /* interface_init */
274 NULL, /* interface_finalize */
275 NULL /* interface_data */
278 g_type_add_interface_static (gtype, GST_TYPE_PRESET, &preset_interface_info);
281 GST_BOILERPLATE_FULL (GstAudioEncoder, gst_audio_encoder, GstElement,
282 GST_TYPE_ELEMENT, do_init);
285 gst_audio_encoder_class_init (GstAudioEncoderClass * klass)
287 GObjectClass *gobject_class;
289 gobject_class = G_OBJECT_CLASS (klass);
291 GST_DEBUG_CATEGORY_INIT (gst_audio_encoder_debug, "audioencoder", 0,
292 "audio encoder base class");
294 g_type_class_add_private (klass, sizeof (GstAudioEncoderPrivate));
296 gobject_class->set_property = gst_audio_encoder_set_property;
297 gobject_class->get_property = gst_audio_encoder_get_property;
299 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_audio_encoder_finalize);
302 g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
303 g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps",
304 "Favour perfect timestamps over tracking upstream timestamps",
305 DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
306 g_object_class_install_property (gobject_class, PROP_GRANULE,
307 g_param_spec_boolean ("mark-granule", "Granule Marking",
308 "Apply granule semantics to buffer metadata (implies perfect-timestamp)",
309 DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
310 g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
311 g_param_spec_boolean ("hard-resync", "Hard Resync",
312 "Perform clipping and sample flushing upon discontinuity",
313 DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
314 g_object_class_install_property (gobject_class, PROP_TOLERANCE,
315 g_param_spec_int64 ("tolerance", "Tolerance",
316 "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
317 0, G_MAXINT64, DEFAULT_TOLERANCE,
318 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
322 gst_audio_encoder_base_init (gpointer g_class)
327 gst_audio_encoder_init (GstAudioEncoder * enc, GstAudioEncoderClass * bclass)
329 GstPadTemplate *pad_template;
331 GST_DEBUG_OBJECT (enc, "gst_audio_encoder_init");
333 enc->priv = GST_AUDIO_ENCODER_GET_PRIVATE (enc);
335 /* only push mode supported */
337 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
338 g_return_if_fail (pad_template != NULL);
339 enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
340 gst_pad_set_event_function (enc->sinkpad,
341 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_event));
342 gst_pad_set_setcaps_function (enc->sinkpad,
343 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_setcaps));
344 gst_pad_set_getcaps_function (enc->sinkpad,
345 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_getcaps));
346 gst_pad_set_query_function (enc->sinkpad,
347 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_query));
348 gst_pad_set_chain_function (enc->sinkpad,
349 GST_DEBUG_FUNCPTR (gst_audio_encoder_chain));
350 gst_pad_set_activatepush_function (enc->sinkpad,
351 GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_activate_push));
352 gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
354 GST_DEBUG_OBJECT (enc, "sinkpad created");
356 /* and we don't mind upstream traveling stuff that much ... */
358 gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
359 g_return_if_fail (pad_template != NULL);
360 enc->srcpad = gst_pad_new_from_template (pad_template, "src");
361 gst_pad_set_query_function (enc->srcpad,
362 GST_DEBUG_FUNCPTR (gst_audio_encoder_src_query));
363 gst_pad_set_query_type_function (enc->srcpad,
364 GST_DEBUG_FUNCPTR (gst_audio_encoder_get_query_types));
365 gst_pad_use_fixed_caps (enc->srcpad);
366 gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
367 GST_DEBUG_OBJECT (enc, "src created");
369 enc->priv->adapter = gst_adapter_new ();
371 /* property default */
372 enc->priv->granule = DEFAULT_GRANULE;
373 enc->priv->perfect_ts = DEFAULT_PERFECT_TS;
374 enc->priv->hard_resync = DEFAULT_HARD_RESYNC;
375 enc->priv->tolerance = DEFAULT_TOLERANCE;
378 gst_audio_encoder_reset (enc, TRUE);
379 GST_DEBUG_OBJECT (enc, "init ok");
383 gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full)
385 GST_OBJECT_LOCK (enc);
387 GST_LOG_OBJECT (enc, "reset full %d", full);
390 enc->priv->active = FALSE;
391 enc->priv->samples_in = 0;
392 enc->priv->bytes_out = 0;
393 gst_audio_info_clear (&enc->priv->ctx.info);
394 memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx));
397 gst_tag_list_free (enc->priv->tags);
398 enc->priv->tags = NULL;
400 g_list_foreach (enc->priv->pending_events, (GFunc) gst_event_unref, NULL);
401 g_list_free (enc->priv->pending_events);
402 enc->priv->pending_events = NULL;
405 gst_segment_init (&enc->segment, GST_FORMAT_TIME);
407 gst_adapter_clear (enc->priv->adapter);
408 enc->priv->got_data = FALSE;
409 enc->priv->drained = TRUE;
410 enc->priv->offset = 0;
411 enc->priv->base_ts = GST_CLOCK_TIME_NONE;
412 enc->priv->base_gp = -1;
413 enc->priv->samples = 0;
414 enc->priv->discont = FALSE;
416 GST_OBJECT_UNLOCK (enc);
420 gst_audio_encoder_finalize (GObject * object)
422 GstAudioEncoder *enc = GST_AUDIO_ENCODER (object);
424 g_object_unref (enc->priv->adapter);
426 G_OBJECT_CLASS (parent_class)->finalize (object);
430 * gst_audio_encoder_finish_frame:
431 * @enc: a #GstAudioEncoder
432 * @buffer: encoded data
433 * @samples: number of samples (per channel) represented by encoded data
435 * Collects encoded data and/or pushes encoded data downstream.
436 * Source pad caps must be set when this is called. Depending on the nature
437 * of the (framing of) the format, subclass can decide whether to push
438 * encoded data directly or to collect various "frames" in a single buffer.
439 * Note that the latter behaviour is recommended whenever the format is allowed,
440 * as it incurs no additional latency and avoids otherwise generating a
441 * a multitude of (small) output buffers. If not explicitly pushed,
442 * any available encoded data is pushed at the end of each processing cycle,
443 * i.e. which encodes as much data as available input data allows.
445 * If @samples < 0, then best estimate is all samples provided to encoder
446 * (subclass) so far. @buf may be NULL, in which case next number of @samples
447 * are considered discarded, e.g. as a result of discontinuous transmission,
448 * and a discontinuity is marked (note that @buf == NULL => push == TRUE).
450 * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
455 gst_audio_encoder_finish_frame (GstAudioEncoder * enc, GstBuffer * buf,
458 GstAudioEncoderClass *klass;
459 GstAudioEncoderPrivate *priv;
460 GstAudioEncoderContext *ctx;
461 GstFlowReturn ret = GST_FLOW_OK;
463 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
465 ctx = &enc->priv->ctx;
467 /* subclass should know what it is producing by now */
468 g_return_val_if_fail (GST_PAD_CAPS (enc->srcpad) != NULL, GST_FLOW_ERROR);
469 /* subclass should not hand us no data */
470 g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0,
473 if (G_UNLIKELY (enc->priv->tags)) {
476 /* add codec info to pending tags */
477 tags = enc->priv->tags;
478 /* no more pending */
479 enc->priv->tags = NULL;
480 gst_pb_utils_add_codec_description_to_tag_list (tags, GST_TAG_CODEC,
481 GST_PAD_CAPS (enc->srcpad));
482 gst_pb_utils_add_codec_description_to_tag_list (tags, GST_TAG_AUDIO_CODEC,
483 GST_PAD_CAPS (enc->srcpad));
484 GST_DEBUG_OBJECT (enc, "sending tags %" GST_PTR_FORMAT, tags);
485 gst_element_found_tags_for_pad (GST_ELEMENT (enc), enc->srcpad, tags);
488 GST_LOG_OBJECT (enc, "accepting %d bytes encoded data as %d samples",
489 buf ? GST_BUFFER_SIZE (buf) : -1, samples);
491 /* mark subclass still alive and providing */
492 priv->got_data = TRUE;
494 if (priv->pending_events) {
495 GList *pending_events, *l;
496 GST_OBJECT_LOCK (enc);
497 pending_events = priv->pending_events;
498 priv->pending_events = NULL;
499 GST_OBJECT_UNLOCK (enc);
501 GST_DEBUG_OBJECT (enc, "Pushing pending events");
502 for (l = priv->pending_events; l; l = l->next)
503 gst_pad_push_event (enc->srcpad, l->data);
504 g_list_free (pending_events);
507 /* remove corresponding samples from input */
509 samples = (enc->priv->offset / ctx->info.bpf);
511 if (G_LIKELY (samples)) {
512 /* track upstream ts if so configured */
513 if (!enc->priv->perfect_ts) {
514 guint64 ts, distance;
516 ts = gst_adapter_prev_timestamp (priv->adapter, &distance);
517 g_assert (distance % ctx->info.bpf == 0);
518 distance /= ctx->info.bpf;
519 GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
520 GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
521 GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
522 GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
523 /* when draining adapter might be empty and no ts to offer */
524 if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
525 GstClockTimeDiff diff;
526 GstClockTime old_ts, next_ts;
528 /* passed into another buffer;
529 * mild check for discontinuity and only mark if so */
531 gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate);
532 old_ts = priv->base_ts +
533 gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
534 diff = GST_CLOCK_DIFF (next_ts, old_ts);
535 GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
536 /* only mark discontinuity if beyond tolerance */
537 if (G_UNLIKELY (diff < -enc->priv->tolerance ||
538 diff > enc->priv->tolerance)) {
539 GST_DEBUG_OBJECT (enc, "marked discont");
540 priv->discont = TRUE;
542 if (diff > GST_SECOND / ctx->info.rate / 2 ||
543 diff < -GST_SECOND / ctx->info.rate / 2) {
544 GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
545 " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
546 /* re-sync to upstream ts */
548 priv->samples = distance;
550 GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter");
554 /* advance sample view */
555 if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) {
556 if (G_LIKELY (!priv->force)) {
557 /* no way we can let this pass */
558 g_assert_not_reached ();
563 if (samples * ctx->info.bpf >= gst_adapter_available (priv->adapter))
564 gst_adapter_clear (priv->adapter);
566 gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
569 gst_adapter_flush (priv->adapter, samples * ctx->info.bpf);
570 priv->offset -= samples * ctx->info.bpf;
571 /* avoid subsequent stray prev_ts */
572 if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
573 gst_adapter_clear (priv->adapter);
575 /* sample count advanced below after buffer handling */
579 if (G_LIKELY (buf)) {
580 GST_LOG_OBJECT (enc, "taking %d bytes for output", GST_BUFFER_SIZE (buf));
581 buf = gst_buffer_make_metadata_writable (buf);
584 gst_buffer_set_caps (buf, GST_PAD_CAPS (enc->srcpad));
585 if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
586 /* FIXME ? lookahead could lead to weird ts and duration ?
587 * (particularly if not in perfect mode) */
588 /* mind sample rounding and produce perfect output */
589 GST_BUFFER_TIMESTAMP (buf) = priv->base_ts +
590 gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
592 GST_DEBUG_OBJECT (enc, "out samples %d", samples);
593 if (G_LIKELY (samples > 0)) {
594 priv->samples += samples;
595 GST_BUFFER_DURATION (buf) = priv->base_ts +
596 gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
597 ctx->info.rate) - GST_BUFFER_TIMESTAMP (buf);
598 priv->last_duration = GST_BUFFER_DURATION (buf);
600 /* duration forecast in case of handling remainder;
601 * the last one is probably like the previous one ... */
602 GST_BUFFER_DURATION (buf) = priv->last_duration;
604 if (priv->base_gp >= 0) {
606 /* FIXME: in longer run, muxer should take care of this ... */
607 /* offset_end = granulepos for ogg muxer */
608 GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
609 enc->priv->ctx.lookahead;
610 /* offset = timestamp corresponding to granulepos for ogg muxer */
611 GST_BUFFER_OFFSET (buf) =
612 GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
615 GST_BUFFER_OFFSET (buf) = priv->bytes_out;
616 GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + GST_BUFFER_SIZE (buf);
620 priv->bytes_out += GST_BUFFER_SIZE (buf);
622 if (G_UNLIKELY (priv->discont)) {
623 GST_LOG_OBJECT (enc, "marking discont");
624 GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
625 priv->discont = FALSE;
628 if (klass->pre_push) {
629 /* last chance for subclass to do some dirty stuff */
630 ret = klass->pre_push (enc, &buf);
631 if (ret != GST_FLOW_OK || !buf) {
632 GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
633 gst_flow_get_name (ret), buf);
635 gst_buffer_unref (buf);
640 GST_LOG_OBJECT (enc, "pushing buffer of size %d with ts %" GST_TIME_FORMAT
641 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
642 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
643 GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
645 ret = gst_pad_push (enc->srcpad, buf);
646 GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
648 /* merely advance samples, most work for that already done above */
649 priv->samples += samples;
658 GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
659 ("received more encoded samples %d than provided %d",
660 samples, priv->offset / ctx->info.bpf), (NULL));
662 gst_buffer_unref (buf);
663 return GST_FLOW_ERROR;
667 /* adapter tracking idea:
668 * - start of adapter corresponds with what has already been encoded
669 * (i.e. really returned by encoder subclass)
670 * - start + offset is what needs to be fed to subclass next */
672 gst_audio_encoder_push_buffers (GstAudioEncoder * enc, gboolean force)
674 GstAudioEncoderClass *klass;
675 GstAudioEncoderPrivate *priv;
676 GstAudioEncoderContext *ctx;
679 GstFlowReturn ret = GST_FLOW_OK;
681 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
683 g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
686 ctx = &enc->priv->ctx;
688 while (ret == GST_FLOW_OK) {
691 av = gst_adapter_available (priv->adapter);
693 g_assert (priv->offset <= av);
696 need = ctx->frame_samples > 0 ? ctx->frame_samples * ctx->info.bpf : av;
697 GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d",
700 if ((need > av) || !av) {
701 if (G_UNLIKELY (force)) {
711 /* if we have some extra metadata,
712 * provide for integer multiple of frames to allow for better granularity
714 if (ctx->frame_samples > 0 && need) {
715 if (ctx->frame_max > 1)
716 need = need * MIN ((av / need), ctx->frame_max);
717 else if (ctx->frame_max == 0)
718 need = need * (av / need);
722 buf = gst_buffer_new ();
723 GST_BUFFER_DATA (buf) = (guint8 *)
724 gst_adapter_peek (priv->adapter, priv->offset + need) + priv->offset;
725 GST_BUFFER_SIZE (buf) = need;
728 GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
731 /* mark this already as consumed,
732 * which it should be when subclass gives us data in exchange for samples */
733 priv->offset += need;
734 priv->samples_in += need / ctx->info.bpf;
736 priv->got_data = FALSE;
737 ret = klass->handle_frame (enc, buf);
740 gst_buffer_unref (buf);
742 /* no data to feed, no leftover provided, then bail out */
743 if (G_UNLIKELY (!buf && !priv->got_data)) {
744 priv->drained = TRUE;
745 GST_LOG_OBJECT (enc, "no more data drained from subclass");
754 gst_audio_encoder_drain (GstAudioEncoder * enc)
756 if (enc->priv->drained)
759 return gst_audio_encoder_push_buffers (enc, TRUE);
763 gst_audio_encoder_set_base_gp (GstAudioEncoder * enc)
767 if (!enc->priv->granule)
770 /* use running time for granule */
771 /* incoming data is clipped, so a valid input should yield a valid output */
772 ts = gst_segment_to_running_time (&enc->segment, GST_FORMAT_TIME,
774 if (GST_CLOCK_TIME_IS_VALID (ts)) {
776 GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate);
777 GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
779 /* should reasonably have a valid base,
780 * otherwise start at 0 if we did not already start there earlier */
781 if (enc->priv->base_gp < 0) {
782 enc->priv->base_gp = 0;
783 GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
790 gst_audio_encoder_chain (GstPad * pad, GstBuffer * buffer)
792 GstAudioEncoder *enc;
793 GstAudioEncoderPrivate *priv;
794 GstAudioEncoderContext *ctx;
795 GstFlowReturn ret = GST_FLOW_OK;
798 enc = GST_AUDIO_ENCODER (GST_OBJECT_PARENT (pad));
801 ctx = &enc->priv->ctx;
803 /* should know what is coming by now */
808 "received buffer of size %d with ts %" GST_TIME_FORMAT
809 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
810 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
811 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
813 /* input shoud be whole number of sample frames */
814 if (GST_BUFFER_SIZE (buffer) % ctx->info.bpf)
817 #ifndef GST_DISABLE_GST_DEBUG
819 GstClockTime duration;
820 GstClockTimeDiff diff;
822 /* verify buffer duration */
823 duration = gst_util_uint64_scale (GST_BUFFER_SIZE (buffer), GST_SECOND,
824 ctx->info.rate * ctx->info.bpf);
825 diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
826 if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
827 (diff > GST_SECOND / ctx->info.rate / 2 ||
828 diff < -GST_SECOND / ctx->info.rate / 2)) {
829 GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
830 GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
831 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
832 GST_TIME_ARGS (duration));
837 discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
838 if (G_UNLIKELY (discont)) {
839 GST_LOG_OBJECT (buffer, "marked discont");
840 enc->priv->discont = discont;
843 /* clip to segment */
844 /* NOTE: slightly painful linking -laudio only for this one ... */
845 buffer = gst_audio_buffer_clip (buffer, &enc->segment, ctx->info.rate,
847 if (G_UNLIKELY (!buffer)) {
848 GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
853 "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT
854 ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
855 GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
856 GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
858 if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
859 priv->base_ts = GST_BUFFER_TIMESTAMP (buffer);
860 GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
861 GST_TIME_ARGS (priv->base_ts));
862 gst_audio_encoder_set_base_gp (enc);
865 /* check for continuity;
866 * checked elsewhere in non-perfect case */
867 if (enc->priv->perfect_ts) {
868 GstClockTimeDiff diff = 0;
869 GstClockTime next_ts = 0;
871 if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
872 GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
875 samples = priv->samples +
876 gst_adapter_available (priv->adapter) / ctx->info.bpf;
877 next_ts = priv->base_ts +
878 gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
879 GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
880 " samples past base_ts %" GST_TIME_FORMAT
881 ", expected ts %" GST_TIME_FORMAT, samples,
882 GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
883 diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer));
884 GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
885 /* if within tolerance,
886 * discard buffer ts and carry on producing perfect stream,
887 * otherwise clip or resync to ts */
888 if (G_UNLIKELY (diff < -enc->priv->tolerance ||
889 diff > enc->priv->tolerance)) {
890 GST_DEBUG_OBJECT (enc, "marked discont");
895 /* do some fancy tweaking in hard resync case */
896 if (discont && enc->priv->hard_resync) {
900 GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
901 GST_TIME_FORMAT ". Clipping buffer", GST_TIME_ARGS (next_ts));
904 GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf;
905 if (diff_bytes >= GST_BUFFER_SIZE (buffer)) {
906 gst_buffer_unref (buffer);
909 buffer = gst_buffer_make_metadata_writable (buffer);
910 GST_BUFFER_DATA (buffer) += diff_bytes;
911 GST_BUFFER_SIZE (buffer) -= diff_bytes;
913 GST_BUFFER_TIMESTAMP (buffer) += diff;
914 /* care even less about duration after this */
916 /* drain stuff prior to resync */
917 gst_audio_encoder_drain (enc);
921 priv->base_ts += diff;
922 gst_audio_encoder_set_base_gp (enc);
923 priv->discont |= discont;
926 gst_adapter_push (enc->priv->adapter, buffer);
927 /* new stuff, so we can push subclass again */
928 enc->priv->drained = FALSE;
930 ret = gst_audio_encoder_push_buffers (enc, FALSE);
933 GST_LOG_OBJECT (enc, "chain leaving");
939 GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
940 ("encoder not initialized"));
941 gst_buffer_unref (buffer);
942 return GST_FLOW_NOT_NEGOTIATED;
946 GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
947 ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buffer),
949 gst_buffer_unref (buffer);
950 return GST_FLOW_ERROR;
955 audio_info_is_equal (GstAudioInfo * from, GstAudioInfo * to)
959 if (from->finfo == NULL || to->finfo == NULL)
961 if (GST_AUDIO_INFO_FORMAT (from) != GST_AUDIO_INFO_FORMAT (to))
963 if (GST_AUDIO_INFO_RATE (from) != GST_AUDIO_INFO_RATE (to))
965 if (GST_AUDIO_INFO_CHANNELS (from) != GST_AUDIO_INFO_CHANNELS (to))
967 if (GST_AUDIO_INFO_CHANNELS (from) > 64)
969 return memcmp (from->position, to->position,
970 GST_AUDIO_INFO_CHANNELS (from) * sizeof (to->position[0]));
974 gst_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps)
976 GstAudioEncoder *enc;
977 GstAudioEncoderClass *klass;
978 GstAudioEncoderContext *ctx;
979 GstAudioInfo *state, *old_state;
980 gboolean res = TRUE, changed = FALSE;
983 enc = GST_AUDIO_ENCODER (GST_PAD_PARENT (pad));
984 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
986 /* subclass must do something here ... */
987 g_return_val_if_fail (klass->set_format != NULL, FALSE);
989 ctx = &enc->priv->ctx;
992 GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
994 if (!gst_caps_is_fixed (caps))
997 /* adjust ts tracking to new sample rate */
998 old_rate = GST_AUDIO_INFO_RATE (state);
999 if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) {
1000 enc->priv->base_ts +=
1001 GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate);
1002 enc->priv->samples = 0;
1005 old_state = gst_audio_info_copy (state);
1006 if (!gst_audio_info_from_caps (state, caps))
1009 changed = !audio_info_is_equal (state, old_state);
1010 gst_audio_info_free (old_state);
1013 GstClockTime old_min_latency;
1014 GstClockTime old_max_latency;
1016 /* drain any pending old data stuff */
1017 gst_audio_encoder_drain (enc);
1019 /* context defaults */
1020 enc->priv->ctx.frame_samples = 0;
1021 enc->priv->ctx.frame_max = 0;
1022 enc->priv->ctx.lookahead = 0;
1024 /* element might report latency */
1025 GST_OBJECT_LOCK (enc);
1026 old_min_latency = ctx->min_latency;
1027 old_max_latency = ctx->max_latency;
1028 GST_OBJECT_UNLOCK (enc);
1030 if (klass->set_format)
1031 res = klass->set_format (enc, state);
1033 /* notify if new latency */
1034 GST_OBJECT_LOCK (enc);
1035 if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) ||
1036 (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) {
1037 GST_OBJECT_UNLOCK (enc);
1038 /* post latency message on the bus */
1039 gst_element_post_message (GST_ELEMENT (enc),
1040 gst_message_new_latency (GST_OBJECT (enc)));
1041 GST_OBJECT_LOCK (enc);
1043 GST_OBJECT_UNLOCK (enc);
1045 GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
1053 GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
1060 * gst_audio_encoder_proxy_getcaps:
1061 * @enc: a #GstAudioEncoder
1062 * @caps: initial caps
1064 * Returns caps that express @caps (or sink template caps if @caps == NULL)
1065 * restricted to channel/rate combinations supported by downstream elements
1068 * Returns: a #GstCaps owned by caller
1073 gst_audio_encoder_proxy_getcaps (GstAudioEncoder * enc, GstCaps * caps)
1075 const GstCaps *templ_caps;
1076 GstCaps *allowed = NULL;
1077 GstCaps *fcaps, *filter_caps;
1080 /* we want to be able to communicate to upstream elements like audioconvert
1081 * and audioresample any rate/channel restrictions downstream (e.g. muxer
1082 * only accepting certain sample rates) */
1083 templ_caps = caps ? caps : gst_pad_get_pad_template_caps (enc->sinkpad);
1084 allowed = gst_pad_get_allowed_caps (enc->srcpad);
1085 if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
1086 fcaps = gst_caps_copy (templ_caps);
1090 GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps);
1091 GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
1093 filter_caps = gst_caps_new_empty ();
1095 for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
1098 q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
1100 /* pick rate + channel fields from allowed caps */
1101 for (j = 0; j < gst_caps_get_size (allowed); j++) {
1102 const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
1106 s = gst_structure_id_empty_new (q_name);
1107 if ((val = gst_structure_get_value (allowed_s, "rate")))
1108 gst_structure_set_value (s, "rate", val);
1109 if ((val = gst_structure_get_value (allowed_s, "channels")))
1110 gst_structure_set_value (s, "channels", val);
1111 /* following might also make sense for some encoded formats,
1113 if ((val = gst_structure_get_value (allowed_s, "width")))
1114 gst_structure_set_value (s, "width", val);
1115 if ((val = gst_structure_get_value (allowed_s, "depth")))
1116 gst_structure_set_value (s, "depth", val);
1117 if ((val = gst_structure_get_value (allowed_s, "endianness")))
1118 gst_structure_set_value (s, "endianness", val);
1119 if ((val = gst_structure_get_value (allowed_s, "signed")))
1120 gst_structure_set_value (s, "signed", val);
1121 if ((val = gst_structure_get_value (allowed_s, "channel-positions")))
1122 gst_structure_set_value (s, "channel-positions", val);
1124 gst_caps_merge_structure (filter_caps, s);
1128 fcaps = gst_caps_intersect (filter_caps, templ_caps);
1129 gst_caps_unref (filter_caps);
1132 gst_caps_replace (&allowed, NULL);
1134 GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
1140 gst_audio_encoder_sink_getcaps (GstPad * pad)
1142 GstAudioEncoder *enc;
1143 GstAudioEncoderClass *klass;
1146 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1147 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1148 g_assert (pad == enc->sinkpad);
1151 caps = klass->getcaps (enc);
1153 caps = gst_audio_encoder_proxy_getcaps (enc, NULL);
1154 gst_object_unref (enc);
1156 GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1162 gst_audio_encoder_sink_eventfunc (GstAudioEncoder * enc, GstEvent * event)
1164 GstAudioEncoderClass *klass;
1165 gboolean handled = FALSE;
1167 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1169 switch (GST_EVENT_TYPE (event)) {
1170 case GST_EVENT_NEWSEGMENT:
1173 gdouble rate, arate;
1174 gint64 start, stop, time;
1177 gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
1178 &start, &stop, &time);
1180 if (format == GST_FORMAT_TIME) {
1181 GST_DEBUG_OBJECT (enc, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT
1182 " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT
1183 ", rate %g, applied_rate %g",
1184 GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time),
1187 GST_DEBUG_OBJECT (enc, "received NEW_SEGMENT %" G_GINT64_FORMAT
1188 " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT
1189 ", rate %g, applied_rate %g", start, stop, time, rate, arate);
1190 GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1194 /* finish current segment */
1195 gst_audio_encoder_drain (enc);
1196 /* reset partially for new segment */
1197 gst_audio_encoder_reset (enc, FALSE);
1198 /* and follow along with segment */
1199 gst_segment_set_newsegment_full (&enc->segment, update, rate, arate,
1200 format, start, stop, time);
1204 case GST_EVENT_FLUSH_START:
1207 case GST_EVENT_FLUSH_STOP:
1208 /* discard any pending stuff */
1209 /* TODO route through drain ?? */
1210 if (!enc->priv->drained && klass->flush)
1212 /* and get (re)set for the sequel */
1213 gst_audio_encoder_reset (enc, FALSE);
1215 GST_OBJECT_LOCK (enc);
1216 g_list_foreach (enc->priv->pending_events, (GFunc) gst_event_unref, NULL);
1217 g_list_free (enc->priv->pending_events);
1218 enc->priv->pending_events = NULL;
1219 GST_OBJECT_UNLOCK (enc);
1224 gst_audio_encoder_drain (enc);
1231 gst_event_parse_tag (event, &tags);
1232 tags = gst_tag_list_copy (tags);
1233 gst_event_unref (event);
1234 gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1235 gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1236 event = gst_event_new_tag (tags);
1238 GST_OBJECT_LOCK (enc);
1239 enc->priv->pending_events =
1240 g_list_append (enc->priv->pending_events, event);
1241 GST_OBJECT_UNLOCK (enc);
1254 gst_audio_encoder_sink_event (GstPad * pad, GstEvent * event)
1256 GstAudioEncoder *enc;
1257 GstAudioEncoderClass *klass;
1258 gboolean handled = FALSE;
1259 gboolean ret = TRUE;
1261 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1262 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1264 GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1265 GST_EVENT_TYPE_NAME (event));
1268 handled = klass->event (enc, event);
1271 handled = gst_audio_encoder_sink_eventfunc (enc, event);
1274 /* Forward non-serialized events and EOS/FLUSH_STOP immediately.
1275 * For EOS this is required because no buffer or serialized event
1276 * will come after EOS and nothing could trigger another
1277 * _finish_frame() call.
1279 * For FLUSH_STOP this is required because it is expected
1280 * to be forwarded immediately and no buffers are queued anyway.
1282 if (!GST_EVENT_IS_SERIALIZED (event)
1283 || GST_EVENT_TYPE (event) == GST_EVENT_EOS
1284 || GST_EVENT_TYPE (event) == GST_EVENT_FLUSH_STOP) {
1285 ret = gst_pad_event_default (pad, event);
1287 GST_OBJECT_LOCK (enc);
1288 enc->priv->pending_events =
1289 g_list_append (enc->priv->pending_events, event);
1290 GST_OBJECT_UNLOCK (enc);
1295 GST_DEBUG_OBJECT (enc, "event handled");
1297 gst_object_unref (enc);
1302 gst_audio_encoder_sink_query (GstPad * pad, GstQuery * query)
1304 gboolean res = TRUE;
1305 GstAudioEncoder *enc;
1307 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1309 switch (GST_QUERY_TYPE (query)) {
1310 case GST_QUERY_FORMATS:
1312 gst_query_set_formats (query, 3,
1313 GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1317 case GST_QUERY_CONVERT:
1319 GstFormat src_fmt, dest_fmt;
1320 gint64 src_val, dest_val;
1322 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1323 if (!(res = gst_audio_info_convert (&enc->priv->ctx.info,
1324 src_fmt, src_val, dest_fmt, &dest_val)))
1326 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1330 res = gst_pad_query_default (pad, query);
1335 gst_object_unref (enc);
1339 static const GstQueryType *
1340 gst_audio_encoder_get_query_types (GstPad * pad)
1342 static const GstQueryType gst_audio_encoder_src_query_types[] = {
1350 return gst_audio_encoder_src_query_types;
1354 * gst_audio_encoded_audio_convert:
1355 * @fmt: audio format of the encoded audio
1356 * @bytes: number of encoded bytes
1357 * @samples: number of encoded samples
1358 * @src_format: source format
1359 * @src_value: source value
1360 * @dest_format: destination format
1361 * @dest_value: destination format
1363 * Helper function to convert @src_value in @src_format to @dest_value in
1364 * @dest_format for encoded audio data. Conversion is possible between
1365 * BYTE and TIME format by using estimated bitrate based on
1366 * @samples and @bytes (and @fmt).
1370 /* FIXME: make gst_audio_encoded_audio_convert() public? */
1372 gst_audio_encoded_audio_convert (GstAudioInfo * fmt,
1373 gint64 bytes, gint64 samples, GstFormat src_format,
1374 gint64 src_value, GstFormat * dest_format, gint64 * dest_value)
1376 gboolean res = FALSE;
1378 g_return_val_if_fail (dest_format != NULL, FALSE);
1379 g_return_val_if_fail (dest_value != NULL, FALSE);
1381 if (G_UNLIKELY (src_format == *dest_format || src_value == 0 ||
1384 *dest_value = src_value;
1388 if (samples == 0 || bytes == 0 || fmt->rate == 0) {
1389 GST_DEBUG ("not enough metadata yet to convert");
1395 switch (src_format) {
1396 case GST_FORMAT_BYTES:
1397 switch (*dest_format) {
1398 case GST_FORMAT_TIME:
1399 *dest_value = gst_util_uint64_scale (src_value,
1400 GST_SECOND * samples, bytes);
1407 case GST_FORMAT_TIME:
1408 switch (*dest_format) {
1409 case GST_FORMAT_BYTES:
1410 *dest_value = gst_util_uint64_scale (src_value, bytes,
1411 samples * GST_SECOND);
1426 /* FIXME ? are any of these queries (other than latency) an encoder's business
1427 * also, the conversion stuff might seem to make sense, but seems to not mind
1428 * segment stuff etc at all
1429 * Supposedly that's backward compatibility ... */
1431 gst_audio_encoder_src_query (GstPad * pad, GstQuery * query)
1433 GstAudioEncoder *enc;
1435 gboolean res = FALSE;
1437 enc = GST_AUDIO_ENCODER (GST_PAD_PARENT (pad));
1438 peerpad = gst_pad_get_peer (GST_PAD (enc->sinkpad));
1440 GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1442 switch (GST_QUERY_TYPE (query)) {
1443 case GST_QUERY_POSITION:
1445 GstFormat fmt, req_fmt;
1448 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1449 GST_LOG_OBJECT (enc, "returning peer response");
1454 GST_LOG_OBJECT (enc, "no peer");
1458 gst_query_parse_position (query, &req_fmt, NULL);
1459 fmt = GST_FORMAT_TIME;
1460 if (!(res = gst_pad_query_position (peerpad, &fmt, &pos)))
1463 if ((res = gst_pad_query_convert (peerpad, fmt, pos, &req_fmt, &val))) {
1464 gst_query_set_position (query, req_fmt, val);
1468 case GST_QUERY_DURATION:
1470 GstFormat fmt, req_fmt;
1473 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1474 GST_LOG_OBJECT (enc, "returning peer response");
1479 GST_LOG_OBJECT (enc, "no peer");
1483 gst_query_parse_duration (query, &req_fmt, NULL);
1484 fmt = GST_FORMAT_TIME;
1485 if (!(res = gst_pad_query_duration (peerpad, &fmt, &dur)))
1488 if ((res = gst_pad_query_convert (peerpad, fmt, dur, &req_fmt, &val))) {
1489 gst_query_set_duration (query, req_fmt, val);
1493 case GST_QUERY_FORMATS:
1495 gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1499 case GST_QUERY_CONVERT:
1501 GstFormat src_fmt, dest_fmt;
1502 gint64 src_val, dest_val;
1504 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1505 if (!(res = gst_audio_encoded_audio_convert (&enc->priv->ctx.info,
1506 enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
1507 &dest_fmt, &dest_val)))
1509 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1512 case GST_QUERY_LATENCY:
1514 if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1516 GstClockTime min_latency, max_latency;
1518 gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1519 GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1520 GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1521 GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1523 GST_OBJECT_LOCK (enc);
1524 /* add our latency */
1525 if (min_latency != -1)
1526 min_latency += enc->priv->ctx.min_latency;
1527 if (max_latency != -1)
1528 max_latency += enc->priv->ctx.max_latency;
1529 GST_OBJECT_UNLOCK (enc);
1531 gst_query_set_latency (query, live, min_latency, max_latency);
1536 res = gst_pad_query_default (pad, query);
1540 gst_object_unref (peerpad);
1545 gst_audio_encoder_set_property (GObject * object, guint prop_id,
1546 const GValue * value, GParamSpec * pspec)
1548 GstAudioEncoder *enc;
1550 enc = GST_AUDIO_ENCODER (object);
1553 case PROP_PERFECT_TS:
1554 if (enc->priv->granule && !g_value_get_boolean (value))
1555 GST_WARNING_OBJECT (enc, "perfect-timestamp can not be set FALSE "
1556 "while granule handling is enabled");
1558 enc->priv->perfect_ts = g_value_get_boolean (value);
1560 case PROP_HARD_RESYNC:
1561 enc->priv->hard_resync = g_value_get_boolean (value);
1563 case PROP_TOLERANCE:
1564 enc->priv->tolerance = g_value_get_int64 (value);
1567 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1573 gst_audio_encoder_get_property (GObject * object, guint prop_id,
1574 GValue * value, GParamSpec * pspec)
1576 GstAudioEncoder *enc;
1578 enc = GST_AUDIO_ENCODER (object);
1581 case PROP_PERFECT_TS:
1582 g_value_set_boolean (value, enc->priv->perfect_ts);
1585 g_value_set_boolean (value, enc->priv->granule);
1587 case PROP_HARD_RESYNC:
1588 g_value_set_boolean (value, enc->priv->hard_resync);
1590 case PROP_TOLERANCE:
1591 g_value_set_int64 (value, enc->priv->tolerance);
1594 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1600 gst_audio_encoder_activate (GstAudioEncoder * enc, gboolean active)
1602 GstAudioEncoderClass *klass;
1603 gboolean result = FALSE;
1605 klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1607 g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE);
1609 GST_DEBUG_OBJECT (enc, "activate %d", active);
1613 if (enc->priv->tags)
1614 gst_tag_list_free (enc->priv->tags);
1615 enc->priv->tags = gst_tag_list_new ();
1617 if (!enc->priv->active && klass->start)
1618 result = klass->start (enc);
1620 /* We must make sure streaming has finished before resetting things
1621 * and calling the ::stop vfunc */
1622 GST_PAD_STREAM_LOCK (enc->sinkpad);
1623 GST_PAD_STREAM_UNLOCK (enc->sinkpad);
1625 if (enc->priv->active && klass->stop)
1626 result = klass->stop (enc);
1629 gst_audio_encoder_reset (enc, TRUE);
1631 GST_DEBUG_OBJECT (enc, "activate return: %d", result);
1637 gst_audio_encoder_sink_activate_push (GstPad * pad, gboolean active)
1639 gboolean result = TRUE;
1640 GstAudioEncoder *enc;
1642 enc = GST_AUDIO_ENCODER (gst_pad_get_parent (pad));
1644 GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
1646 result = gst_audio_encoder_activate (enc, active);
1649 enc->priv->active = active;
1651 GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
1653 gst_object_unref (enc);
1658 * gst_audio_encoder_get_audio_info:
1659 * @enc: a #GstAudioEncoder
1661 * Returns: a #GstAudioInfo describing the input audio format
1666 gst_audio_encoder_get_audio_info (GstAudioEncoder * enc)
1668 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), NULL);
1670 return &enc->priv->ctx.info;
1674 * gst_audio_encoder_set_frame_samples:
1675 * @enc: a #GstAudioEncoder
1676 * @num: number of samples per frame
1678 * Sets number of samples (per channel) subclass needs to be handed,
1679 * or will be handed all available if 0.
1684 gst_audio_encoder_set_frame_samples (GstAudioEncoder * enc, gint num)
1686 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1688 enc->priv->ctx.frame_samples = num;
1692 * gst_audio_encoder_get_frame_samples:
1693 * @enc: a #GstAudioEncoder
1695 * Returns: currently requested samples per frame
1700 gst_audio_encoder_get_frame_samples (GstAudioEncoder * enc)
1702 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1704 return enc->priv->ctx.frame_samples;
1708 * gst_audio_encoder_set_frame_max:
1709 * @enc: a #GstAudioEncoder
1710 * @num: number of frames
1712 * Sets max number of frames accepted at once (assumed minimally 1)
1717 gst_audio_encoder_set_frame_max (GstAudioEncoder * enc, gint num)
1719 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1721 enc->priv->ctx.frame_max = num;
1725 * gst_audio_encoder_get_frame_max:
1726 * @enc: a #GstAudioEncoder
1728 * Returns: currently configured maximum handled frames
1733 gst_audio_encoder_get_frame_max (GstAudioEncoder * enc)
1735 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1737 return enc->priv->ctx.frame_max;
1741 * gst_audio_encoder_set_lookahead:
1742 * @enc: a #GstAudioEncoder
1745 * Sets encoder lookahead (in units of input rate samples)
1750 gst_audio_encoder_set_lookahead (GstAudioEncoder * enc, gint num)
1752 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1754 enc->priv->ctx.lookahead = num;
1758 * gst_audio_encoder_get_lookahead:
1759 * @enc: a #GstAudioEncoder
1761 * Returns: currently configured encoder lookahead
1764 gst_audio_encoder_get_lookahead (GstAudioEncoder * enc)
1766 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
1768 return enc->priv->ctx.lookahead;
1772 * gst_audio_encoder_set_latency:
1773 * @enc: a #GstAudioEncoder
1774 * @min: minimum latency
1775 * @max: maximum latency
1777 * Sets encoder latency.
1782 gst_audio_encoder_set_latency (GstAudioEncoder * enc,
1783 GstClockTime min, GstClockTime max)
1785 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1787 GST_OBJECT_LOCK (enc);
1788 enc->priv->ctx.min_latency = min;
1789 enc->priv->ctx.max_latency = max;
1790 GST_OBJECT_UNLOCK (enc);
1794 * gst_audio_encoder_get_latency:
1795 * @enc: a #GstAudioEncoder
1796 * @min: (out) (allow-none): a pointer to storage to hold minimum latency
1797 * @max: (out) (allow-none): a pointer to storage to hold maximum latency
1799 * Sets the variables pointed to by @min and @max to the currently configured
1805 gst_audio_encoder_get_latency (GstAudioEncoder * enc,
1806 GstClockTime * min, GstClockTime * max)
1808 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1810 GST_OBJECT_LOCK (enc);
1812 *min = enc->priv->ctx.min_latency;
1814 *max = enc->priv->ctx.max_latency;
1815 GST_OBJECT_UNLOCK (enc);
1819 * gst_audio_encoder_set_mark_granule:
1820 * @enc: a #GstAudioEncoder
1821 * @enabled: new state
1823 * Enable or disable encoder granule handling.
1830 gst_audio_encoder_set_mark_granule (GstAudioEncoder * enc, gboolean enabled)
1832 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1834 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1836 GST_OBJECT_LOCK (enc);
1837 enc->priv->granule = enabled;
1838 GST_OBJECT_UNLOCK (enc);
1842 * gst_audio_encoder_get_mark_granule:
1843 * @enc: a #GstAudioEncoder
1845 * Queries if the encoder will handle granule marking.
1847 * Returns: TRUE if granule marking is enabled.
1854 gst_audio_encoder_get_mark_granule (GstAudioEncoder * enc)
1858 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1860 GST_OBJECT_LOCK (enc);
1861 result = enc->priv->granule;
1862 GST_OBJECT_UNLOCK (enc);
1868 * gst_audio_encoder_set_perfect_timestamp:
1869 * @enc: a #GstAudioEncoder
1870 * @enabled: new state
1872 * Enable or disable encoder perfect output timestamp preference.
1879 gst_audio_encoder_set_perfect_timestamp (GstAudioEncoder * enc,
1882 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1884 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1886 GST_OBJECT_LOCK (enc);
1887 enc->priv->perfect_ts = enabled;
1888 GST_OBJECT_UNLOCK (enc);
1892 * gst_audio_encoder_get_perfect_timestamp:
1893 * @enc: a #GstAudioEncoder
1895 * Queries encoder perfect timestamp behaviour.
1897 * Returns: TRUE if pefect timestamp setting enabled.
1904 gst_audio_encoder_get_perfect_timestamp (GstAudioEncoder * enc)
1908 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1910 GST_OBJECT_LOCK (enc);
1911 result = enc->priv->perfect_ts;
1912 GST_OBJECT_UNLOCK (enc);
1918 * gst_audio_encoder_set_hard_sync:
1919 * @enc: a #GstAudioEncoder
1920 * @enabled: new state
1922 * Sets encoder hard resync handling.
1929 gst_audio_encoder_set_hard_resync (GstAudioEncoder * enc, gboolean enabled)
1931 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1933 GST_LOG_OBJECT (enc, "enabled: %d", enabled);
1935 GST_OBJECT_LOCK (enc);
1936 enc->priv->hard_resync = enabled;
1937 GST_OBJECT_UNLOCK (enc);
1941 * gst_audio_encoder_get_hard_sync:
1942 * @enc: a #GstAudioEncoder
1944 * Queries encoder's hard resync setting.
1946 * Returns: TRUE if hard resync is enabled.
1953 gst_audio_encoder_get_hard_resync (GstAudioEncoder * enc)
1957 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
1959 GST_OBJECT_LOCK (enc);
1960 result = enc->priv->hard_resync;
1961 GST_OBJECT_UNLOCK (enc);
1967 * gst_audio_encoder_set_tolerance:
1968 * @enc: a #GstAudioEncoder
1969 * @tolerance: new tolerance
1971 * Configures encoder audio jitter tolerance threshold.
1978 gst_audio_encoder_set_tolerance (GstAudioEncoder * enc, gint64 tolerance)
1980 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
1982 GST_OBJECT_LOCK (enc);
1983 enc->priv->tolerance = tolerance;
1984 GST_OBJECT_UNLOCK (enc);
1988 * gst_audio_encoder_get_tolerance:
1989 * @enc: a #GstAudioEncoder
1991 * Queries current audio jitter tolerance threshold.
1993 * Returns: encoder audio jitter tolerance threshold.
2000 gst_audio_encoder_get_tolerance (GstAudioEncoder * enc)
2004 g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2006 GST_OBJECT_LOCK (enc);
2007 result = enc->priv->tolerance;
2008 GST_OBJECT_UNLOCK (enc);
2014 * gst_audio_encoder_merge_tags:
2015 * @enc: a #GstAudioEncoder
2016 * @tags: a #GstTagList to merge
2017 * @mode: the #GstTagMergeMode to use
2019 * Adds tags to so-called pending tags, which will be processed
2020 * before pushing out data downstream.
2022 * Note that this is provided for convenience, and the subclass is
2023 * not required to use this and can still do tag handling on its own,
2024 * although it should be aware that baseclass already takes care
2025 * of the usual CODEC/AUDIO_CODEC tags.
2032 gst_audio_encoder_merge_tags (GstAudioEncoder * enc,
2033 const GstTagList * tags, GstTagMergeMode mode)
2037 g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2038 g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2040 GST_OBJECT_LOCK (enc);
2042 GST_DEBUG_OBJECT (enc, "merging tags %" GST_PTR_FORMAT, tags);
2043 otags = enc->priv->tags;
2044 enc->priv->tags = gst_tag_list_merge (enc->priv->tags, tags, mode);
2046 gst_tag_list_free (otags);
2047 GST_OBJECT_UNLOCK (enc);