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