618b7ebd6a1e56bdd661f85860259bca2bb2a341
[platform/upstream/gstreamer.git] / subprojects / gst-plugins-base / 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., 51 Franklin St, Fifth Floor,
19  * Boston, MA 02110-1301, USA.
20  */
21
22 /**
23  * SECTION:gstaudioencoder
24  * @title: GstAudioEncoder
25  * @short_description: Base class for audio encoders
26  * @see_also: #GstBaseTransform
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  *
33  * ## Configuration
34  *
35  *   * Initially, GstAudioEncoder calls @start when the encoder element
36  *     is activated, which allows subclass to perform any global setup.
37  *
38  *   * GstAudioEncoder calls @set_format to inform subclass of the format
39  *     of input audio data that it is about to receive.  Subclass should
40  *     setup for encoding and configure various base class parameters
41  *     appropriately, notably those directing desired input data handling.
42  *     While unlikely, it might be called more than once, if changing input
43  *     parameters require reconfiguration.
44  *
45  *   * GstAudioEncoder calls @stop at end of all processing.
46  *
47  * As of configuration stage, and throughout processing, GstAudioEncoder
48  * maintains various parameters that provide required context,
49  * e.g. describing the format of input audio data.
50  * Conversely, subclass can and should configure these context parameters
51  * to inform base class of its expectation w.r.t. buffer handling.
52  *
53  * ## Data processing
54  *
55  *     * Base class gathers input sample data (as directed by the context's
56  *       frame_samples and frame_max) and provides this to subclass' @handle_frame.
57  *     * If codec processing results in encoded data, subclass should call
58  *       gst_audio_encoder_finish_frame() to have encoded data pushed
59  *       downstream. Alternatively, it might also call
60  *       gst_audio_encoder_finish_frame() (with a NULL buffer and some number of
61  *       dropped samples) to indicate dropped (non-encoded) samples.
62  *     * Just prior to actually pushing a buffer downstream,
63  *       it is passed to @pre_push.
64  *     * During the parsing process GstAudioEncoderClass will handle both
65  *       srcpad and sinkpad events. Sink events will be passed to subclass
66  *       if @event callback has been provided.
67  *
68  * ## Shutdown phase
69  *
70  *   * GstAudioEncoder class calls @stop to inform the subclass that data
71  *     parsing will be stopped.
72  *
73  * Subclass is responsible for providing pad template caps for
74  * source and sink pads. The pads need to be named "sink" and "src". It also
75  * needs to set the fixed caps on srcpad, when the format is ensured.  This
76  * is typically when base class calls subclass' @set_format function, though
77  * it might be delayed until calling @gst_audio_encoder_finish_frame.
78  *
79  * In summary, above process should have subclass concentrating on
80  * codec data processing while leaving other matters to base class,
81  * such as most notably timestamp handling.  While it may exert more control
82  * in this area (see e.g. @pre_push), it is very much not recommended.
83  *
84  * In particular, base class will either favor tracking upstream timestamps
85  * (at the possible expense of jitter) or aim to arrange for a perfect stream of
86  * output timestamps, depending on #GstAudioEncoder:perfect-timestamp.
87  * However, in the latter case, the input may not be so perfect or ideal, which
88  * is handled as follows.  An input timestamp is compared with the expected
89  * timestamp as dictated by input sample stream and if the deviation is less
90  * than #GstAudioEncoder:tolerance, the deviation is discarded.
91  * Otherwise, it is considered a discontuinity and subsequent output timestamp
92  * is resynced to the new position after performing configured discontinuity
93  * processing.  In the non-perfect-timestamp case, an upstream variation
94  * exceeding tolerance only leads to marking DISCONT on subsequent outgoing
95  * (while timestamps are adjusted to upstream regardless of variation).
96  * While DISCONT is also marked in the perfect-timestamp case, this one
97  * optionally (see #GstAudioEncoder:hard-resync)
98  * performs some additional steps, such as clipping of (early) input samples
99  * or draining all currently remaining input data, depending on the direction
100  * of the discontuinity.
101  *
102  * If perfect timestamps are arranged, it is also possible to request baseclass
103  * (usually set by subclass) to provide additional buffer metadata (in OFFSET
104  * and OFFSET_END) fields according to granule defined semantics currently
105  * needed by oggmux.  Specifically, OFFSET is set to granulepos (= sample count
106  * including buffer) and OFFSET_END to corresponding timestamp (as determined
107  * by same sample count and sample rate).
108  *
109  * Things that subclass need to take care of:
110  *
111  *   * Provide pad templates
112  *   * Set source pad caps when appropriate
113  *   * Inform base class of buffer processing needs using context's
114  *      frame_samples and frame_bytes.
115  *   * Set user-configurable properties to sane defaults for format and
116  *      implementing codec at hand, e.g. those controlling timestamp behaviour
117  *      and discontinuity processing.
118  *   * Accept data in @handle_frame and provide encoded results to
119  *      gst_audio_encoder_finish_frame().
120  *
121  */
122
123 #ifdef HAVE_CONFIG_H
124 #  include "config.h"
125 #endif
126
127 #include "gstaudioencoder.h"
128 #include "gstaudioutilsprivate.h"
129 #include <gst/base/gstadapter.h>
130 #include <gst/audio/audio.h>
131 #include <gst/pbutils/descriptions.h>
132
133 #include <stdlib.h>
134 #include <string.h>
135
136
137 GST_DEBUG_CATEGORY_STATIC (gst_audio_encoder_debug);
138 #define GST_CAT_DEFAULT gst_audio_encoder_debug
139
140 enum
141 {
142   PROP_0,
143   PROP_PERFECT_TS,
144   PROP_GRANULE,
145   PROP_HARD_RESYNC,
146   PROP_TOLERANCE
147 };
148
149 #define DEFAULT_PERFECT_TS   FALSE
150 #define DEFAULT_GRANULE      FALSE
151 #define DEFAULT_HARD_RESYNC  FALSE
152 #define DEFAULT_TOLERANCE    40000000
153 #define DEFAULT_HARD_MIN     FALSE
154 #define DEFAULT_DRAINABLE    TRUE
155
156 typedef struct _GstAudioEncoderContext
157 {
158   /* input */
159   /* last negotiated input caps */
160   GstCaps *input_caps;
161   /* last negotiated input info */
162   GstAudioInfo info;
163
164   /* output */
165   GstCaps *caps;
166   GstCaps *allocation_caps;
167   gboolean output_caps_changed;
168   gint frame_samples_min, frame_samples_max;
169   gint frame_max;
170   gint lookahead;
171   /* MT-protected (with LOCK) */
172   GstClockTime min_latency;
173   GstClockTime max_latency;
174   gboolean negotiated;
175
176   GList *headers;
177   gboolean new_headers;
178
179   GstAllocator *allocator;
180   GstAllocationParams params;
181 } GstAudioEncoderContext;
182
183 struct _GstAudioEncoderPrivate
184 {
185   /* activation status */
186   gboolean active;
187
188   /* input base/first ts as basis for output ts;
189    * kept nearly constant for perfect_ts,
190    * otherwise resyncs to upstream ts */
191   GstClockTime base_ts;
192   /* corresponding base granulepos */
193   gint64 base_gp;
194   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
195   guint64 samples;
196
197   /* currently collected sample data */
198   GstAdapter *adapter;
199   /* offset in adapter up to which already supplied to encoder */
200   gint offset;
201   /* mark outgoing discont */
202   gboolean discont;
203   /* to guess duration of drained data */
204   GstClockTime last_duration;
205
206   /* subclass provided data in processing round */
207   gboolean got_data;
208   /* subclass gave all it could already */
209   gboolean drained;
210   /* subclass currently being forcibly drained */
211   gboolean force;
212   /* need to handle changed input caps */
213   gboolean do_caps;
214
215   /* output bps estimatation */
216   /* global in samples seen */
217   guint64 samples_in;
218   /* global bytes sent out */
219   guint64 bytes_out;
220
221   /* context storage */
222   GstAudioEncoderContext ctx;
223
224   /* properties */
225   gint64 tolerance;
226   gboolean perfect_ts;
227   gboolean hard_resync;
228   gboolean granule;
229   gboolean hard_min;
230   gboolean drainable;
231
232   /* upstream stream tags (global tags are passed through as-is) */
233   GstTagList *upstream_tags;
234
235   /* subclass tags */
236   GstTagList *tags;
237   GstTagMergeMode tags_merge_mode;
238
239   gboolean tags_changed;
240
241   /* pending serialized sink events, will be sent from finish_frame() */
242   GList *pending_events;
243
244   /* these are initial events or events that came in while there was nothing
245    * in the adapter. these events shall be sent after negotiation but before
246    * we push the following buffer. */
247   GList *early_pending_events;
248 };
249
250
251 static GstElementClass *parent_class = NULL;
252 static gint private_offset = 0;
253
254 /* cached quark to avoid contention on the global quark table lock */
255 #define META_TAG_AUDIO meta_tag_audio_quark
256 static GQuark meta_tag_audio_quark;
257
258 static void gst_audio_encoder_class_init (GstAudioEncoderClass * klass);
259 static void gst_audio_encoder_init (GstAudioEncoder * parse,
260     GstAudioEncoderClass * klass);
261
262 GType
263 gst_audio_encoder_get_type (void)
264 {
265   static GType audio_encoder_type = 0;
266
267   if (!audio_encoder_type) {
268     static const GTypeInfo audio_encoder_info = {
269       sizeof (GstAudioEncoderClass),
270       (GBaseInitFunc) NULL,
271       (GBaseFinalizeFunc) NULL,
272       (GClassInitFunc) gst_audio_encoder_class_init,
273       NULL,
274       NULL,
275       sizeof (GstAudioEncoder),
276       0,
277       (GInstanceInitFunc) gst_audio_encoder_init,
278     };
279     const GInterfaceInfo preset_interface_info = {
280       NULL,                     /* interface_init */
281       NULL,                     /* interface_finalize */
282       NULL                      /* interface_data */
283     };
284
285     audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT,
286         "GstAudioEncoder", &audio_encoder_info, G_TYPE_FLAG_ABSTRACT);
287
288     private_offset =
289         g_type_add_instance_private (audio_encoder_type,
290         sizeof (GstAudioEncoderPrivate));
291
292     g_type_add_interface_static (audio_encoder_type, GST_TYPE_PRESET,
293         &preset_interface_info);
294   }
295   return audio_encoder_type;
296 }
297
298 static inline GstAudioEncoderPrivate *
299 gst_audio_encoder_get_instance_private (GstAudioEncoder * self)
300 {
301   return (G_STRUCT_MEMBER_P (self, private_offset));
302 }
303
304 static void gst_audio_encoder_finalize (GObject * object);
305 static void gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full);
306
307 static void gst_audio_encoder_set_property (GObject * object,
308     guint prop_id, const GValue * value, GParamSpec * pspec);
309 static void gst_audio_encoder_get_property (GObject * object,
310     guint prop_id, GValue * value, GParamSpec * pspec);
311
312 static gboolean gst_audio_encoder_sink_activate_mode (GstPad * pad,
313     GstObject * parent, GstPadMode mode, gboolean active);
314
315 static GstCaps *gst_audio_encoder_getcaps_default (GstAudioEncoder * enc,
316     GstCaps * filter);
317
318 static gboolean gst_audio_encoder_sink_event_default (GstAudioEncoder * enc,
319     GstEvent * event);
320 static gboolean gst_audio_encoder_src_event_default (GstAudioEncoder * enc,
321     GstEvent * event);
322 static gboolean gst_audio_encoder_sink_event (GstPad * pad, GstObject * parent,
323     GstEvent * event);
324 static gboolean gst_audio_encoder_src_event (GstPad * pad, GstObject * parent,
325     GstEvent * event);
326 static gboolean gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc,
327     GstCaps * caps);
328 static GstFlowReturn gst_audio_encoder_chain (GstPad * pad, GstObject * parent,
329     GstBuffer * buffer);
330 static gboolean gst_audio_encoder_src_query (GstPad * pad, GstObject * parent,
331     GstQuery * query);
332 static gboolean gst_audio_encoder_sink_query (GstPad * pad, GstObject * parent,
333     GstQuery * query);
334 static GstStateChangeReturn gst_audio_encoder_change_state (GstElement *
335     element, GstStateChange transition);
336
337 static gboolean gst_audio_encoder_decide_allocation_default (GstAudioEncoder *
338     enc, GstQuery * query);
339 static gboolean gst_audio_encoder_propose_allocation_default (GstAudioEncoder *
340     enc, GstQuery * query);
341 static gboolean gst_audio_encoder_negotiate_default (GstAudioEncoder * enc);
342 static gboolean gst_audio_encoder_negotiate_unlocked (GstAudioEncoder * enc);
343
344 static gboolean gst_audio_encoder_transform_meta_default (GstAudioEncoder *
345     encoder, GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf);
346
347 static gboolean gst_audio_encoder_sink_query_default (GstAudioEncoder * encoder,
348     GstQuery * query);
349 static gboolean gst_audio_encoder_src_query_default (GstAudioEncoder * encoder,
350     GstQuery * query);
351
352 static void
353 gst_audio_encoder_class_init (GstAudioEncoderClass * klass)
354 {
355   GObjectClass *gobject_class;
356   GstElementClass *gstelement_class;
357
358   gobject_class = G_OBJECT_CLASS (klass);
359   gstelement_class = GST_ELEMENT_CLASS (klass);
360   parent_class = g_type_class_peek_parent (klass);
361
362   GST_DEBUG_CATEGORY_INIT (gst_audio_encoder_debug, "audioencoder", 0,
363       "audio encoder base class");
364
365   if (private_offset != 0)
366     g_type_class_adjust_private_offset (klass, &private_offset);
367
368   gobject_class->set_property = gst_audio_encoder_set_property;
369   gobject_class->get_property = gst_audio_encoder_get_property;
370
371   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_audio_encoder_finalize);
372
373   /* properties */
374   g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
375       g_param_spec_boolean ("perfect-timestamp", "Perfect Timestamps",
376           "Favour perfect timestamps over tracking upstream timestamps",
377           DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
378   g_object_class_install_property (gobject_class, PROP_GRANULE,
379       g_param_spec_boolean ("mark-granule", "Granule Marking",
380           "Apply granule semantics to buffer metadata (implies perfect-timestamp)",
381           DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
382   g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
383       g_param_spec_boolean ("hard-resync", "Hard Resync",
384           "Perform clipping and sample flushing upon discontinuity",
385           DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
386   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
387       g_param_spec_int64 ("tolerance", "Tolerance",
388           "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
389           0, G_MAXINT64, DEFAULT_TOLERANCE,
390           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
391
392   gstelement_class->change_state =
393       GST_DEBUG_FUNCPTR (gst_audio_encoder_change_state);
394
395   klass->getcaps = gst_audio_encoder_getcaps_default;
396   klass->sink_event = gst_audio_encoder_sink_event_default;
397   klass->src_event = gst_audio_encoder_src_event_default;
398   klass->sink_query = gst_audio_encoder_sink_query_default;
399   klass->src_query = gst_audio_encoder_src_query_default;
400   klass->propose_allocation = gst_audio_encoder_propose_allocation_default;
401   klass->decide_allocation = gst_audio_encoder_decide_allocation_default;
402   klass->negotiate = gst_audio_encoder_negotiate_default;
403   klass->transform_meta = gst_audio_encoder_transform_meta_default;
404
405   meta_tag_audio_quark = g_quark_from_static_string (GST_META_TAG_AUDIO_STR);
406 }
407
408 static void
409 gst_audio_encoder_init (GstAudioEncoder * enc, GstAudioEncoderClass * bclass)
410 {
411   GstPadTemplate *pad_template;
412
413   GST_DEBUG_OBJECT (enc, "gst_audio_encoder_init");
414
415   enc->priv = gst_audio_encoder_get_instance_private (enc);
416
417   /* only push mode supported */
418   pad_template =
419       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
420   g_return_if_fail (pad_template != NULL);
421   enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
422   gst_pad_set_event_function (enc->sinkpad,
423       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_event));
424   gst_pad_set_query_function (enc->sinkpad,
425       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_query));
426   gst_pad_set_chain_function (enc->sinkpad,
427       GST_DEBUG_FUNCPTR (gst_audio_encoder_chain));
428   gst_pad_set_activatemode_function (enc->sinkpad,
429       GST_DEBUG_FUNCPTR (gst_audio_encoder_sink_activate_mode));
430   gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
431
432   GST_DEBUG_OBJECT (enc, "sinkpad created");
433
434   /* and we don't mind upstream traveling stuff that much ... */
435   pad_template =
436       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
437   g_return_if_fail (pad_template != NULL);
438   enc->srcpad = gst_pad_new_from_template (pad_template, "src");
439   gst_pad_set_event_function (enc->srcpad,
440       GST_DEBUG_FUNCPTR (gst_audio_encoder_src_event));
441   gst_pad_set_query_function (enc->srcpad,
442       GST_DEBUG_FUNCPTR (gst_audio_encoder_src_query));
443   gst_pad_use_fixed_caps (enc->srcpad);
444   gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
445   GST_DEBUG_OBJECT (enc, "src created");
446
447   enc->priv->adapter = gst_adapter_new ();
448
449   g_rec_mutex_init (&enc->stream_lock);
450
451   /* property default */
452   enc->priv->granule = DEFAULT_GRANULE;
453   enc->priv->perfect_ts = DEFAULT_PERFECT_TS;
454   enc->priv->hard_resync = DEFAULT_HARD_RESYNC;
455   enc->priv->tolerance = DEFAULT_TOLERANCE;
456   enc->priv->hard_min = DEFAULT_HARD_MIN;
457   enc->priv->drainable = DEFAULT_DRAINABLE;
458
459   /* init state */
460   enc->priv->ctx.min_latency = 0;
461   enc->priv->ctx.max_latency = 0;
462   gst_audio_encoder_reset (enc, TRUE);
463   GST_DEBUG_OBJECT (enc, "init ok");
464 }
465
466 static void
467 gst_audio_encoder_reset (GstAudioEncoder * enc, gboolean full)
468 {
469   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
470
471   GST_LOG_OBJECT (enc, "reset full %d", full);
472
473   if (full) {
474     enc->priv->active = FALSE;
475     GST_OBJECT_LOCK (enc);
476     enc->priv->samples_in = 0;
477     enc->priv->bytes_out = 0;
478     GST_OBJECT_UNLOCK (enc);
479
480     g_list_foreach (enc->priv->ctx.headers, (GFunc) gst_buffer_unref, NULL);
481     g_list_free (enc->priv->ctx.headers);
482     enc->priv->ctx.headers = NULL;
483     enc->priv->ctx.new_headers = FALSE;
484
485     if (enc->priv->ctx.allocator)
486       gst_object_unref (enc->priv->ctx.allocator);
487     enc->priv->ctx.allocator = NULL;
488
489     GST_OBJECT_LOCK (enc);
490     gst_caps_replace (&enc->priv->ctx.input_caps, NULL);
491     gst_caps_replace (&enc->priv->ctx.caps, NULL);
492     gst_caps_replace (&enc->priv->ctx.allocation_caps, NULL);
493
494     memset (&enc->priv->ctx, 0, sizeof (enc->priv->ctx));
495     gst_audio_info_init (&enc->priv->ctx.info);
496     GST_OBJECT_UNLOCK (enc);
497
498     if (enc->priv->upstream_tags) {
499       gst_tag_list_unref (enc->priv->upstream_tags);
500       enc->priv->upstream_tags = NULL;
501     }
502     if (enc->priv->tags)
503       gst_tag_list_unref (enc->priv->tags);
504     enc->priv->tags = NULL;
505     enc->priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
506     enc->priv->tags_changed = FALSE;
507
508     g_list_free_full (enc->priv->early_pending_events,
509         (GDestroyNotify) gst_event_unref);
510     enc->priv->early_pending_events = NULL;
511     g_list_free_full (enc->priv->pending_events,
512         (GDestroyNotify) gst_event_unref);
513     enc->priv->pending_events = NULL;
514   }
515
516   gst_segment_init (&enc->input_segment, GST_FORMAT_TIME);
517   gst_segment_init (&enc->output_segment, GST_FORMAT_TIME);
518
519   gst_adapter_clear (enc->priv->adapter);
520   enc->priv->got_data = FALSE;
521   enc->priv->drained = TRUE;
522   enc->priv->offset = 0;
523   enc->priv->base_ts = GST_CLOCK_TIME_NONE;
524   enc->priv->base_gp = -1;
525   enc->priv->samples = 0;
526   enc->priv->discont = FALSE;
527
528   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
529 }
530
531 static void
532 gst_audio_encoder_finalize (GObject * object)
533 {
534   GstAudioEncoder *enc = GST_AUDIO_ENCODER (object);
535
536   g_object_unref (enc->priv->adapter);
537
538   g_rec_mutex_clear (&enc->stream_lock);
539
540   G_OBJECT_CLASS (parent_class)->finalize (object);
541 }
542
543 static GstStateChangeReturn
544 gst_audio_encoder_change_state (GstElement * element, GstStateChange transition)
545 {
546   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
547   GstAudioEncoder *enc = GST_AUDIO_ENCODER (element);
548   GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
549
550   switch (transition) {
551     case GST_STATE_CHANGE_NULL_TO_READY:
552       if (klass->open) {
553         if (!klass->open (enc))
554           goto open_failed;
555       }
556     default:
557       break;
558   }
559
560   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
561
562   switch (transition) {
563     case GST_STATE_CHANGE_READY_TO_NULL:
564       if (klass->close) {
565         if (!klass->close (enc))
566           goto close_failed;
567       }
568     default:
569       break;
570   }
571
572   return ret;
573
574 open_failed:
575   {
576     GST_ELEMENT_ERROR (enc, LIBRARY, INIT, (NULL), ("Failed to open codec"));
577     return GST_STATE_CHANGE_FAILURE;
578   }
579 close_failed:
580   {
581     GST_ELEMENT_ERROR (enc, LIBRARY, INIT, (NULL), ("Failed to close codec"));
582     return GST_STATE_CHANGE_FAILURE;
583   }
584 }
585
586 static gboolean
587 gst_audio_encoder_push_event (GstAudioEncoder * enc, GstEvent * event)
588 {
589   switch (GST_EVENT_TYPE (event)) {
590     case GST_EVENT_SEGMENT:{
591       GstSegment seg;
592
593       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
594       gst_event_copy_segment (event, &seg);
595
596       GST_DEBUG_OBJECT (enc, "starting segment %" GST_SEGMENT_FORMAT, &seg);
597
598       enc->output_segment = seg;
599       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
600       break;
601     }
602     default:
603       break;
604   }
605
606   return gst_pad_push_event (enc->srcpad, event);
607 }
608
609 static inline void
610 gst_audio_encoder_push_early_pending_events (GstAudioEncoder * enc)
611 {
612   GstAudioEncoderPrivate *priv = enc->priv;
613
614   if (priv->early_pending_events) {
615     GList *pending_events, *l;
616
617     pending_events = priv->early_pending_events;
618     priv->early_pending_events = NULL;
619
620     GST_DEBUG_OBJECT (enc, "Pushing early pending events");
621     for (l = pending_events; l; l = l->next)
622       gst_audio_encoder_push_event (enc, l->data);
623     g_list_free (pending_events);
624   }
625 }
626
627 static inline void
628 gst_audio_encoder_push_pending_events (GstAudioEncoder * enc)
629 {
630   GstAudioEncoderPrivate *priv = enc->priv;
631
632   gst_audio_encoder_push_early_pending_events (enc);
633
634   if (priv->pending_events) {
635     GList *pending_events, *l;
636
637     pending_events = priv->pending_events;
638     priv->pending_events = NULL;
639
640     GST_DEBUG_OBJECT (enc, "Pushing pending events");
641     for (l = pending_events; l; l = l->next)
642       gst_audio_encoder_push_event (enc, l->data);
643     g_list_free (pending_events);
644   }
645 }
646
647 static GstEvent *
648 gst_audio_encoder_create_merged_tags_event (GstAudioEncoder * enc)
649 {
650   GstTagList *merged_tags;
651
652   GST_LOG_OBJECT (enc, "upstream : %" GST_PTR_FORMAT, enc->priv->upstream_tags);
653   GST_LOG_OBJECT (enc, "encoder  : %" GST_PTR_FORMAT, enc->priv->tags);
654   GST_LOG_OBJECT (enc, "mode     : %d", enc->priv->tags_merge_mode);
655
656   merged_tags =
657       gst_tag_list_merge (enc->priv->upstream_tags, enc->priv->tags,
658       enc->priv->tags_merge_mode);
659
660   GST_DEBUG_OBJECT (enc, "merged   : %" GST_PTR_FORMAT, merged_tags);
661
662   if (merged_tags == NULL)
663     return NULL;
664
665   if (gst_tag_list_is_empty (merged_tags)) {
666     gst_tag_list_unref (merged_tags);
667     return NULL;
668   }
669
670   /* add codec info to pending tags */
671 #if 0
672   caps = gst_pad_get_current_caps (enc->srcpad);
673   gst_pb_utils_add_codec_description_to_tag_list (merged_tags,
674       GST_TAG_AUDIO_CODEC, caps);
675 #endif
676
677   return gst_event_new_tag (merged_tags);
678 }
679
680 static void
681 gst_audio_encoder_check_and_push_pending_tags (GstAudioEncoder * enc)
682 {
683   if (enc->priv->tags_changed) {
684     GstEvent *tags_event;
685
686     tags_event = gst_audio_encoder_create_merged_tags_event (enc);
687
688     if (tags_event != NULL)
689       gst_audio_encoder_push_event (enc, tags_event);
690
691     enc->priv->tags_changed = FALSE;
692   }
693 }
694
695
696 static gboolean
697 gst_audio_encoder_transform_meta_default (GstAudioEncoder *
698     encoder, GstBuffer * outbuf, GstMeta * meta, GstBuffer * inbuf)
699 {
700   const GstMetaInfo *info = meta->info;
701   const gchar *const *tags;
702   const gchar *const supported_tags[] = {
703     GST_META_TAG_AUDIO_STR,
704     GST_META_TAG_AUDIO_CHANNELS_STR,
705     NULL,
706   };
707
708   tags = gst_meta_api_type_get_tags (info->api);
709
710   if (!tags)
711     return TRUE;
712
713   while (*tags) {
714     if (!g_strv_contains (supported_tags, *tags))
715       return FALSE;
716     tags++;
717   }
718
719   return TRUE;
720 }
721
722 typedef struct
723 {
724   GstAudioEncoder *encoder;
725   GstBuffer *outbuf;
726 } CopyMetaData;
727
728 static gboolean
729 foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
730 {
731   CopyMetaData *data = user_data;
732   GstAudioEncoder *encoder = data->encoder;
733   GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (encoder);
734   GstBuffer *outbuf = data->outbuf;
735   const GstMetaInfo *info = (*meta)->info;
736   gboolean do_copy = FALSE;
737
738   if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)
739       || gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory_reference)) {
740     /* never call the transform_meta with memory specific metadata */
741     GST_DEBUG_OBJECT (encoder, "not copying memory specific metadata %s",
742         g_type_name (info->api));
743     do_copy = FALSE;
744   } else if (klass->transform_meta) {
745     do_copy = klass->transform_meta (encoder, outbuf, *meta, inbuf);
746     GST_DEBUG_OBJECT (encoder, "transformed metadata %s: copy: %d",
747         g_type_name (info->api), do_copy);
748   }
749
750   /* we only copy metadata when the subclass implemented a transform_meta
751    * function and when it returns %TRUE */
752   if (do_copy && info->transform_func) {
753     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
754     GST_DEBUG_OBJECT (encoder, "copy metadata %s", g_type_name (info->api));
755     /* simply copy then */
756     info->transform_func (outbuf, *meta, inbuf,
757         _gst_meta_transform_copy, &copy_data);
758   }
759   return TRUE;
760 }
761
762 /**
763  * gst_audio_encoder_finish_frame:
764  * @enc: a #GstAudioEncoder
765  * @buffer: (transfer full) (allow-none): encoded data
766  * @samples: number of samples (per channel) represented by encoded data
767  *
768  * Collects encoded data and pushes encoded data downstream.
769  * Source pad caps must be set when this is called.
770  *
771  * If @samples < 0, then best estimate is all samples provided to encoder
772  * (subclass) so far.  @buf may be NULL, in which case next number of @samples
773  * are considered discarded, e.g. as a result of discontinuous transmission,
774  * and a discontinuity is marked.
775  *
776  * Note that samples received in #GstAudioEncoderClass.handle_frame()
777  * may be invalidated by a call to this function.
778  *
779  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
780  */
781 GstFlowReturn
782 gst_audio_encoder_finish_frame (GstAudioEncoder * enc, GstBuffer * buf,
783     gint samples)
784 {
785   GstAudioEncoderClass *klass;
786   GstAudioEncoderPrivate *priv;
787   GstAudioEncoderContext *ctx;
788   GstFlowReturn ret = GST_FLOW_OK;
789   gboolean needs_reconfigure = FALSE;
790   GstBuffer *inbuf = NULL;
791
792   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
793   priv = enc->priv;
794   ctx = &enc->priv->ctx;
795
796   /* subclass should not hand us no data */
797   g_return_val_if_fail (buf == NULL || gst_buffer_get_size (buf) > 0,
798       GST_FLOW_ERROR);
799
800   /* subclass should know what it is producing by now */
801   if (!ctx->caps)
802     goto no_caps;
803
804   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
805
806   GST_LOG_OBJECT (enc,
807       "accepting %" G_GSIZE_FORMAT " bytes encoded data as %d samples",
808       buf ? gst_buffer_get_size (buf) : -1, samples);
809
810   needs_reconfigure = gst_pad_check_reconfigure (enc->srcpad);
811   if (G_UNLIKELY (ctx->output_caps_changed || needs_reconfigure)) {
812     if (!gst_audio_encoder_negotiate_unlocked (enc)) {
813       gst_pad_mark_reconfigure (enc->srcpad);
814       if (GST_PAD_IS_FLUSHING (enc->srcpad))
815         ret = GST_FLOW_FLUSHING;
816       else
817         ret = GST_FLOW_NOT_NEGOTIATED;
818       if (buf)
819         gst_buffer_unref (buf);
820       goto exit;
821     }
822   }
823
824   /* mark subclass still alive and providing */
825   if (G_LIKELY (buf))
826     priv->got_data = TRUE;
827
828   gst_audio_encoder_push_early_pending_events (enc);
829
830   /* send after early pending events, which likely includes segment event */
831   gst_audio_encoder_check_and_push_pending_tags (enc);
832
833   /* remove corresponding samples from input */
834   if (samples < 0)
835     samples = (enc->priv->offset / ctx->info.bpf);
836
837   if (G_LIKELY (samples)) {
838     /* track upstream ts if so configured */
839     if (!enc->priv->perfect_ts) {
840       guint64 ts, distance;
841
842       ts = gst_adapter_prev_pts (priv->adapter, &distance);
843       g_assert (distance % ctx->info.bpf == 0);
844       distance /= ctx->info.bpf;
845       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
846           GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
847       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
848           GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
849       /* when draining adapter might be empty and no ts to offer */
850       if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
851         GstClockTimeDiff diff;
852         GstClockTime old_ts, next_ts;
853
854         /* passed into another buffer;
855          * mild check for discontinuity and only mark if so */
856         next_ts = ts +
857             gst_util_uint64_scale (distance, GST_SECOND, ctx->info.rate);
858         old_ts = priv->base_ts +
859             gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->info.rate);
860         diff = GST_CLOCK_DIFF (next_ts, old_ts);
861         GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
862         /* only mark discontinuity if beyond tolerance */
863         if (G_UNLIKELY (diff < -enc->priv->tolerance ||
864                 diff > enc->priv->tolerance)) {
865           GST_DEBUG_OBJECT (enc, "marked discont");
866           priv->discont = TRUE;
867         }
868         if (diff > GST_SECOND / ctx->info.rate / 2 ||
869             diff < -GST_SECOND / ctx->info.rate / 2) {
870           GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
871               " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
872           /* re-sync to upstream ts */
873           priv->base_ts = ts;
874           priv->samples = distance;
875         } else {
876           GST_LOG_OBJECT (enc, "new upstream ts only introduces jitter");
877         }
878       }
879     }
880     /* advance sample view */
881     if (G_UNLIKELY (samples * ctx->info.bpf > priv->offset)) {
882       guint avail = gst_adapter_available (priv->adapter);
883
884       if (G_LIKELY (!priv->force)) {
885         /* we should have received EOS to enable force */
886         goto overflow;
887       } else {
888         priv->offset = 0;
889         if (avail > 0 && samples * ctx->info.bpf >= avail) {
890           inbuf = gst_adapter_take_buffer_fast (priv->adapter, avail);
891           gst_adapter_clear (priv->adapter);
892         } else if (avail > 0) {
893           inbuf =
894               gst_adapter_take_buffer_fast (priv->adapter,
895               samples * ctx->info.bpf);
896         }
897       }
898     } else {
899       guint avail = gst_adapter_available (priv->adapter);
900
901       if (avail > 0) {
902         inbuf =
903             gst_adapter_take_buffer_fast (priv->adapter,
904             samples * ctx->info.bpf);
905       }
906       priv->offset -= samples * ctx->info.bpf;
907       /* avoid subsequent stray prev_ts */
908       if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
909         gst_adapter_clear (priv->adapter);
910     }
911     /* sample count advanced below after buffer handling */
912   }
913
914   /* collect output */
915   if (G_LIKELY (buf)) {
916     gsize size;
917
918     /* Pushing headers first */
919     if (G_UNLIKELY (priv->ctx.new_headers)) {
920       GList *tmp;
921
922       GST_DEBUG_OBJECT (enc, "Sending headers");
923
924       for (tmp = priv->ctx.headers; tmp; tmp = tmp->next) {
925         GstBuffer *tmpbuf = gst_buffer_ref (tmp->data);
926
927         tmpbuf = gst_buffer_make_writable (tmpbuf);
928         size = gst_buffer_get_size (tmpbuf);
929
930         if (G_UNLIKELY (priv->discont)) {
931           GST_LOG_OBJECT (enc, "marking discont");
932           GST_BUFFER_FLAG_SET (tmpbuf, GST_BUFFER_FLAG_DISCONT);
933           priv->discont = FALSE;
934         }
935
936         /* Ogg codecs like Vorbis use offset/offset-end in a special
937          * way and both should be 0 for these codecs */
938         if (priv->base_gp >= 0) {
939           GST_BUFFER_OFFSET (tmpbuf) = 0;
940           GST_BUFFER_OFFSET_END (tmpbuf) = 0;
941         } else {
942           GST_BUFFER_OFFSET (tmpbuf) = priv->bytes_out;
943           GST_BUFFER_OFFSET_END (tmpbuf) = priv->bytes_out + size;
944         }
945
946         GST_OBJECT_LOCK (enc);
947         priv->bytes_out += size;
948         GST_OBJECT_UNLOCK (enc);
949
950         ret = gst_pad_push (enc->srcpad, tmpbuf);
951         if (ret != GST_FLOW_OK) {
952           GST_WARNING_OBJECT (enc, "pushing header returned %s",
953               gst_flow_get_name (ret));
954           goto exit;
955         }
956       }
957       priv->ctx.new_headers = FALSE;
958     }
959
960     size = gst_buffer_get_size (buf);
961
962     GST_LOG_OBJECT (enc, "taking %" G_GSIZE_FORMAT " bytes for output", size);
963     buf = gst_buffer_make_writable (buf);
964
965     /* decorate */
966     if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
967       /* FIXME ? lookahead could lead to weird ts and duration ?
968        * (particularly if not in perfect mode) */
969       /* mind sample rounding and produce perfect output */
970       GST_BUFFER_PTS (buf) = priv->base_ts +
971           gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
972           ctx->info.rate);
973       GST_BUFFER_DTS (buf) = GST_BUFFER_PTS (buf);
974       GST_DEBUG_OBJECT (enc, "out samples %d", samples);
975       if (G_LIKELY (samples > 0)) {
976         priv->samples += samples;
977         GST_BUFFER_DURATION (buf) = priv->base_ts +
978             gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
979             ctx->info.rate) - GST_BUFFER_PTS (buf);
980         priv->last_duration = GST_BUFFER_DURATION (buf);
981       } else {
982         /* duration forecast in case of handling remainder;
983          * the last one is probably like the previous one ... */
984         GST_BUFFER_DURATION (buf) = priv->last_duration;
985       }
986       if (priv->base_gp >= 0) {
987         /* pamper oggmux */
988         /* FIXME: in longer run, muxer should take care of this ... */
989         /* offset_end = granulepos for ogg muxer */
990         GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
991             enc->priv->ctx.lookahead;
992         /* offset = timestamp corresponding to granulepos for ogg muxer */
993         GST_BUFFER_OFFSET (buf) =
994             GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
995             ctx->info.rate);
996       } else {
997         GST_BUFFER_OFFSET (buf) = priv->bytes_out;
998         GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + size;
999       }
1000     }
1001
1002     if (klass->transform_meta) {
1003       if (G_LIKELY (inbuf)) {
1004         CopyMetaData data;
1005
1006         data.encoder = enc;
1007         data.outbuf = buf;
1008         gst_buffer_foreach_meta (inbuf, foreach_metadata, &data);
1009       } else {
1010         GST_WARNING_OBJECT (enc,
1011             "Can't copy metadata because input buffer disappeared");
1012       }
1013     }
1014
1015     GST_OBJECT_LOCK (enc);
1016     priv->bytes_out += size;
1017     GST_OBJECT_UNLOCK (enc);
1018
1019     if (G_UNLIKELY (priv->discont)) {
1020       GST_LOG_OBJECT (enc, "marking discont");
1021       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
1022       priv->discont = FALSE;
1023     }
1024
1025     if (klass->pre_push) {
1026       /* last chance for subclass to do some dirty stuff */
1027       ret = klass->pre_push (enc, &buf);
1028       if (ret != GST_FLOW_OK || !buf) {
1029         GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
1030             gst_flow_get_name (ret), buf);
1031
1032         if (buf)
1033           gst_buffer_unref (buf);
1034         goto exit;
1035       }
1036     }
1037
1038     GST_LOG_OBJECT (enc,
1039         "pushing buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1040         ", duration %" GST_TIME_FORMAT, size,
1041         GST_TIME_ARGS (GST_BUFFER_PTS (buf)),
1042         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
1043
1044     ret = gst_pad_push (enc->srcpad, buf);
1045     GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
1046
1047     /* Now push the events that followed after the buffer got into the
1048      * adapter. */
1049     gst_audio_encoder_push_pending_events (enc);
1050   } else {
1051     /* merely advance samples, most work for that already done above */
1052     priv->samples += samples;
1053   }
1054
1055 exit:
1056   if (inbuf)
1057     gst_buffer_unref (inbuf);
1058
1059   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1060
1061   return ret;
1062
1063   /* ERRORS */
1064 no_caps:
1065   {
1066     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, ("no caps set"), (NULL));
1067     if (buf)
1068       gst_buffer_unref (buf);
1069     return GST_FLOW_ERROR;
1070   }
1071 overflow:
1072   {
1073     GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
1074         ("received more encoded samples %d than provided %d as inputs",
1075             samples, priv->offset / ctx->info.bpf), (NULL));
1076     if (buf)
1077       gst_buffer_unref (buf);
1078     ret = GST_FLOW_ERROR;
1079     /* no way we can let this pass */
1080     g_assert_not_reached ();
1081     /* really no way */
1082     goto exit;
1083   }
1084 }
1085
1086  /* adapter tracking idea:
1087   * - start of adapter corresponds with what has already been encoded
1088   * (i.e. really returned by encoder subclass)
1089   * - start + offset is what needs to be fed to subclass next */
1090 static GstFlowReturn
1091 gst_audio_encoder_push_buffers (GstAudioEncoder * enc, gboolean force)
1092 {
1093   GstAudioEncoderClass *klass;
1094   GstAudioEncoderPrivate *priv;
1095   GstAudioEncoderContext *ctx;
1096   gint av, need;
1097   GstBuffer *buf;
1098   GstFlowReturn ret = GST_FLOW_OK;
1099
1100   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1101
1102   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
1103
1104   priv = enc->priv;
1105   ctx = &enc->priv->ctx;
1106
1107   while (ret == GST_FLOW_OK) {
1108
1109     buf = NULL;
1110     av = gst_adapter_available (priv->adapter);
1111
1112     g_assert (priv->offset <= av);
1113     av -= priv->offset;
1114
1115     need =
1116         ctx->frame_samples_min >
1117         0 ? ctx->frame_samples_min * ctx->info.bpf : av;
1118     GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d", av, need,
1119         force);
1120
1121     if ((need > av) || !av) {
1122       if (G_UNLIKELY (force)) {
1123         priv->force = TRUE;
1124         need = av;
1125       } else {
1126         break;
1127       }
1128     } else {
1129       priv->force = FALSE;
1130     }
1131
1132     if (ctx->frame_samples_max > 0)
1133       need = MIN (av, ctx->frame_samples_max * ctx->info.bpf);
1134
1135     if (ctx->frame_samples_min == ctx->frame_samples_max) {
1136       /* if we have some extra metadata,
1137        * provide for integer multiple of frames to allow for better granularity
1138        * of processing */
1139       if (ctx->frame_samples_min > 0 && need) {
1140         if (ctx->frame_max > 1)
1141           need = need * MIN ((av / need), ctx->frame_max);
1142         else if (ctx->frame_max == 0)
1143           need = need * (av / need);
1144       }
1145     }
1146
1147     priv->got_data = FALSE;
1148     if (G_LIKELY (need)) {
1149       const guint8 *data;
1150
1151       data = gst_adapter_map (priv->adapter, priv->offset + need);
1152       buf =
1153           gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY,
1154           (gpointer) data, priv->offset + need, priv->offset, need, NULL, NULL);
1155     } else if (!priv->drainable) {
1156       GST_DEBUG_OBJECT (enc, "non-drainable and no more data");
1157       goto finish;
1158     }
1159
1160     GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
1161         need, priv->offset);
1162
1163     /* mark this already as consumed,
1164      * which it should be when subclass gives us data in exchange for samples */
1165     priv->offset += need;
1166     GST_OBJECT_LOCK (enc);
1167     priv->samples_in += need / ctx->info.bpf;
1168     GST_OBJECT_UNLOCK (enc);
1169
1170     /* subclass might not want to be bothered with leftover data,
1171      * so take care of that here if so, otherwise pass along */
1172     if (G_UNLIKELY (priv->force && priv->hard_min && buf)) {
1173       GST_DEBUG_OBJECT (enc, "bypassing subclass with leftover");
1174       ret = gst_audio_encoder_finish_frame (enc, NULL, -1);
1175     } else {
1176       ret = klass->handle_frame (enc, buf);
1177     }
1178
1179     if (G_LIKELY (buf)) {
1180       gst_buffer_unref (buf);
1181       gst_adapter_unmap (priv->adapter);
1182     }
1183
1184   finish:
1185     /* no data to feed, no leftover provided, then bail out */
1186     if (G_UNLIKELY (!buf && !priv->got_data)) {
1187       priv->drained = TRUE;
1188       GST_LOG_OBJECT (enc, "no more data drained from subclass");
1189       break;
1190     }
1191   }
1192
1193   return ret;
1194 }
1195
1196 static GstFlowReturn
1197 gst_audio_encoder_drain (GstAudioEncoder * enc)
1198 {
1199   GST_DEBUG_OBJECT (enc, "draining");
1200   if (enc->priv->drained)
1201     return GST_FLOW_OK;
1202   else {
1203     GST_DEBUG_OBJECT (enc, "... really");
1204     return gst_audio_encoder_push_buffers (enc, TRUE);
1205   }
1206 }
1207
1208 static void
1209 gst_audio_encoder_set_base_gp (GstAudioEncoder * enc)
1210 {
1211   GstClockTime ts;
1212
1213   if (!enc->priv->granule)
1214     return;
1215
1216   /* use running time for granule */
1217   /* incoming data is clipped, so a valid input should yield a valid output */
1218   ts = gst_segment_to_running_time (&enc->input_segment, GST_FORMAT_TIME,
1219       enc->priv->base_ts);
1220   if (GST_CLOCK_TIME_IS_VALID (ts)) {
1221     enc->priv->base_gp =
1222         GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->priv->ctx.info.rate);
1223     GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
1224   } else {
1225     /* should reasonably have a valid base,
1226      * otherwise start at 0 if we did not already start there earlier */
1227     if (enc->priv->base_gp < 0) {
1228       enc->priv->base_gp = 0;
1229       GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
1230           enc->priv->base_gp);
1231     }
1232   }
1233 }
1234
1235 static GstFlowReturn
1236 gst_audio_encoder_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
1237 {
1238   GstAudioEncoder *enc;
1239   GstAudioEncoderPrivate *priv;
1240   GstAudioEncoderContext *ctx;
1241   GstFlowReturn ret = GST_FLOW_OK;
1242   gboolean discont;
1243   gsize size;
1244
1245   enc = GST_AUDIO_ENCODER (parent);
1246
1247   priv = enc->priv;
1248   ctx = &enc->priv->ctx;
1249
1250   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1251
1252   if (G_UNLIKELY (priv->do_caps)) {
1253     GstCaps *caps = gst_pad_get_current_caps (enc->sinkpad);
1254     if (!caps)
1255       goto not_negotiated;
1256     if (!gst_audio_encoder_sink_setcaps (enc, caps)) {
1257       gst_caps_unref (caps);
1258       goto not_negotiated;
1259     }
1260     gst_caps_unref (caps);
1261     priv->do_caps = FALSE;
1262   }
1263
1264   /* should know what is coming by now */
1265   if (!ctx->info.bpf)
1266     goto not_negotiated;
1267
1268   size = gst_buffer_get_size (buffer);
1269
1270   GST_LOG_OBJECT (enc,
1271       "received buffer of size %" G_GSIZE_FORMAT " with ts %" GST_TIME_FORMAT
1272       ", duration %" GST_TIME_FORMAT, size,
1273       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1274       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1275
1276   /* input should be whole number of sample frames */
1277   if (size % ctx->info.bpf)
1278     goto wrong_buffer;
1279
1280 #ifndef GST_DISABLE_GST_DEBUG
1281   {
1282     GstClockTime duration;
1283     GstClockTimeDiff diff;
1284
1285     /* verify buffer duration */
1286     duration = gst_util_uint64_scale (size, GST_SECOND,
1287         ctx->info.rate * ctx->info.bpf);
1288     diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
1289     if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
1290         (diff > GST_SECOND / ctx->info.rate / 2 ||
1291             diff < -GST_SECOND / ctx->info.rate / 2)) {
1292       GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
1293           GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
1294           GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
1295           GST_TIME_ARGS (duration));
1296     }
1297   }
1298 #endif
1299
1300   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
1301   if (G_UNLIKELY (discont)) {
1302     GST_LOG_OBJECT (enc, "marked discont");
1303     enc->priv->discont = discont;
1304   }
1305
1306   /* clip to segment */
1307   buffer = gst_audio_buffer_clip (buffer, &enc->input_segment, ctx->info.rate,
1308       ctx->info.bpf);
1309   if (G_UNLIKELY (!buffer)) {
1310     GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
1311     goto done;
1312   }
1313
1314   size = gst_buffer_get_size (buffer);
1315
1316   GST_LOG_OBJECT (enc,
1317       "buffer after segment clipping has size %" G_GSIZE_FORMAT " with ts %"
1318       GST_TIME_FORMAT ", duration %" GST_TIME_FORMAT, size,
1319       GST_TIME_ARGS (GST_BUFFER_PTS (buffer)),
1320       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
1321
1322   if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
1323     priv->base_ts = GST_BUFFER_PTS (buffer);
1324     GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
1325         GST_TIME_ARGS (priv->base_ts));
1326     gst_audio_encoder_set_base_gp (enc);
1327   }
1328
1329   /* check for continuity;
1330    * checked elsewhere in non-perfect case */
1331   if (enc->priv->perfect_ts) {
1332     GstClockTimeDiff diff = 0;
1333     GstClockTime next_ts = 0;
1334
1335     if (GST_BUFFER_PTS_IS_VALID (buffer) &&
1336         GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
1337       guint64 samples;
1338
1339       samples = priv->samples +
1340           gst_adapter_available (priv->adapter) / ctx->info.bpf;
1341       next_ts = priv->base_ts +
1342           gst_util_uint64_scale (samples, GST_SECOND, ctx->info.rate);
1343       GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
1344           " samples past base_ts %" GST_TIME_FORMAT
1345           ", expected ts %" GST_TIME_FORMAT, samples,
1346           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
1347       diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_PTS (buffer));
1348       GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
1349       /* if within tolerance,
1350        * discard buffer ts and carry on producing perfect stream,
1351        * otherwise clip or resync to ts */
1352       if (G_UNLIKELY (diff < -enc->priv->tolerance ||
1353               diff > enc->priv->tolerance)) {
1354         GST_DEBUG_OBJECT (enc, "marked discont");
1355         discont = TRUE;
1356       }
1357     }
1358
1359     /* do some fancy tweaking in hard resync case */
1360     if (discont && enc->priv->hard_resync) {
1361       if (diff < 0) {
1362         guint64 diff_bytes;
1363
1364         GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
1365             GST_TIME_FORMAT ".  Clipping buffer", GST_TIME_ARGS (next_ts));
1366
1367         diff_bytes =
1368             GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->info.rate) * ctx->info.bpf;
1369         if (diff_bytes >= size) {
1370           gst_buffer_unref (buffer);
1371           goto done;
1372         }
1373         buffer = gst_buffer_make_writable (buffer);
1374         gst_buffer_resize (buffer, diff_bytes, size - diff_bytes);
1375
1376         GST_BUFFER_PTS (buffer) += diff;
1377         /* care even less about duration after this */
1378       } else {
1379         /* drain stuff prior to resync */
1380         gst_audio_encoder_drain (enc);
1381       }
1382     }
1383     if (discont) {
1384       /* now re-sync ts */
1385       GstClockTime shift =
1386           gst_util_uint64_scale (gst_adapter_available (priv->adapter),
1387           GST_SECOND, ctx->info.rate * ctx->info.bpf);
1388
1389       if (G_UNLIKELY (shift > GST_BUFFER_PTS (buffer))) {
1390         /* ERROR */
1391         goto wrong_time;
1392       }
1393       /* arrange for newly added samples to come out with the ts
1394        * of the incoming buffer that adds these */
1395       priv->base_ts = GST_BUFFER_PTS (buffer) - shift;
1396       priv->samples = 0;
1397       gst_audio_encoder_set_base_gp (enc);
1398       priv->discont |= discont;
1399     }
1400   }
1401
1402   gst_adapter_push (enc->priv->adapter, buffer);
1403   /* new stuff, so we can push subclass again */
1404   enc->priv->drained = FALSE;
1405
1406   ret = gst_audio_encoder_push_buffers (enc, FALSE);
1407
1408 done:
1409   GST_LOG_OBJECT (enc, "chain leaving");
1410
1411   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1412
1413   return ret;
1414
1415   /* ERRORS */
1416 not_negotiated:
1417   {
1418     GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
1419         ("encoder not initialized"));
1420     gst_buffer_unref (buffer);
1421     ret = GST_FLOW_NOT_NEGOTIATED;
1422     goto done;
1423   }
1424 wrong_buffer:
1425   {
1426     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
1427         ("buffer size %" G_GSIZE_FORMAT " not a multiple of %d",
1428             gst_buffer_get_size (buffer), ctx->info.bpf));
1429     gst_buffer_unref (buffer);
1430     ret = GST_FLOW_ERROR;
1431     goto done;
1432   }
1433 wrong_time:
1434   {
1435     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
1436         ("buffer going too far back in time"));
1437     gst_buffer_unref (buffer);
1438     ret = GST_FLOW_ERROR;
1439     goto done;
1440   }
1441 }
1442
1443 static gboolean
1444 gst_audio_encoder_sink_setcaps (GstAudioEncoder * enc, GstCaps * caps)
1445 {
1446   GstAudioEncoderClass *klass;
1447   GstAudioEncoderContext *ctx;
1448   GstAudioInfo state;
1449   gboolean res = TRUE;
1450   guint old_rate;
1451
1452   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1453
1454   /* subclass must do something here ... */
1455   g_return_val_if_fail (klass->set_format != NULL, FALSE);
1456
1457   ctx = &enc->priv->ctx;
1458
1459   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1460
1461   GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
1462
1463   if (!gst_caps_is_fixed (caps))
1464     goto refuse_caps;
1465
1466   if (enc->priv->ctx.input_caps
1467       && gst_caps_is_equal (enc->priv->ctx.input_caps, caps))
1468     goto same_caps;
1469
1470   if (!gst_audio_info_from_caps (&state, caps))
1471     goto refuse_caps;
1472
1473   if (enc->priv->ctx.input_caps && gst_audio_info_is_equal (&state, &ctx->info))
1474     goto same_caps;
1475
1476   /* adjust ts tracking to new sample rate */
1477   old_rate = GST_AUDIO_INFO_RATE (&ctx->info);
1478   if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && old_rate) {
1479     enc->priv->base_ts +=
1480         GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, old_rate);
1481     enc->priv->samples = 0;
1482   }
1483
1484   /* drain any pending old data stuff */
1485   gst_audio_encoder_drain (enc);
1486
1487   /* context defaults */
1488   /* FIXME 2.0: This is quite unexpected behaviour. We should never
1489    * just reset *settings* of a subclass inside the base class */
1490   enc->priv->ctx.frame_samples_min = 0;
1491   enc->priv->ctx.frame_samples_max = 0;
1492   enc->priv->ctx.frame_max = 0;
1493   enc->priv->ctx.lookahead = 0;
1494
1495   if (klass->set_format)
1496     res = klass->set_format (enc, &state);
1497
1498   if (res) {
1499     GST_OBJECT_LOCK (enc);
1500     ctx->info = state;
1501     gst_caps_replace (&enc->priv->ctx.input_caps, caps);
1502     GST_OBJECT_UNLOCK (enc);
1503   } else {
1504     /* invalidate state to ensure no casual carrying on */
1505     GST_DEBUG_OBJECT (enc, "subclass did not accept format");
1506     gst_audio_info_init (&state);
1507     goto exit;
1508   }
1509
1510 exit:
1511
1512   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1513
1514   return res;
1515
1516 same_caps:
1517   {
1518     GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
1519     goto exit;
1520   }
1521
1522   /* ERRORS */
1523 refuse_caps:
1524   {
1525     GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
1526     goto exit;
1527   }
1528 }
1529
1530
1531 /**
1532  * gst_audio_encoder_proxy_getcaps:
1533  * @enc: a #GstAudioEncoder
1534  * @caps: (allow-none): initial caps
1535  * @filter: (allow-none): filter caps
1536  *
1537  * Returns caps that express @caps (or sink template caps if @caps == NULL)
1538  * restricted to channel/rate combinations supported by downstream elements
1539  * (e.g. muxers).
1540  *
1541  * Returns: (transfer full): a #GstCaps owned by caller
1542  */
1543 GstCaps *
1544 gst_audio_encoder_proxy_getcaps (GstAudioEncoder * enc, GstCaps * caps,
1545     GstCaps * filter)
1546 {
1547   return __gst_audio_element_proxy_getcaps (GST_ELEMENT_CAST (enc),
1548       GST_AUDIO_ENCODER_SINK_PAD (enc), GST_AUDIO_ENCODER_SRC_PAD (enc),
1549       caps, filter);
1550 }
1551
1552 static GstCaps *
1553 gst_audio_encoder_getcaps_default (GstAudioEncoder * enc, GstCaps * filter)
1554 {
1555   GstCaps *caps;
1556
1557   caps = gst_audio_encoder_proxy_getcaps (enc, NULL, filter);
1558   GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1559
1560   return caps;
1561 }
1562
1563 static GList *
1564 _flush_events (GstPad * pad, GList * events)
1565 {
1566   GList *tmp;
1567
1568   for (tmp = events; tmp; tmp = tmp->next) {
1569     if (GST_EVENT_TYPE (tmp->data) != GST_EVENT_EOS &&
1570         GST_EVENT_TYPE (tmp->data) != GST_EVENT_SEGMENT &&
1571         GST_EVENT_IS_STICKY (tmp->data)) {
1572       gst_pad_store_sticky_event (pad, GST_EVENT_CAST (tmp->data));
1573     }
1574     gst_event_unref (tmp->data);
1575   }
1576   g_list_free (events);
1577
1578   return NULL;
1579 }
1580
1581 static gboolean
1582 gst_audio_encoder_sink_event_default (GstAudioEncoder * enc, GstEvent * event)
1583 {
1584   GstAudioEncoderClass *klass;
1585   gboolean res;
1586
1587   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1588
1589   switch (GST_EVENT_TYPE (event)) {
1590     case GST_EVENT_SEGMENT:
1591     {
1592       GstSegment seg;
1593
1594       gst_event_copy_segment (event, &seg);
1595
1596       if (seg.format == GST_FORMAT_TIME) {
1597         GST_DEBUG_OBJECT (enc, "received TIME SEGMENT %" GST_SEGMENT_FORMAT,
1598             &seg);
1599       } else {
1600         GST_DEBUG_OBJECT (enc, "received SEGMENT %" GST_SEGMENT_FORMAT, &seg);
1601         GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1602         res = TRUE;
1603         gst_event_unref (event);
1604         break;
1605       }
1606
1607       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1608       /* finish current segment */
1609       gst_audio_encoder_drain (enc);
1610       /* reset partially for new segment */
1611       gst_audio_encoder_reset (enc, FALSE);
1612       /* and follow along with segment */
1613       enc->input_segment = seg;
1614
1615       enc->priv->early_pending_events =
1616           g_list_append (enc->priv->early_pending_events, event);
1617       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1618
1619       res = TRUE;
1620       break;
1621     }
1622
1623     case GST_EVENT_FLUSH_START:
1624       res = gst_audio_encoder_push_event (enc, event);
1625       break;
1626
1627     case GST_EVENT_FLUSH_STOP:
1628       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1629       /* discard any pending stuff */
1630       /* TODO route through drain ?? */
1631       if (!enc->priv->drained && klass->flush)
1632         klass->flush (enc);
1633       /* and get (re)set for the sequel */
1634       gst_audio_encoder_reset (enc, FALSE);
1635
1636       enc->priv->pending_events = _flush_events (enc->srcpad,
1637           enc->priv->pending_events);
1638       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1639
1640       res = gst_audio_encoder_push_event (enc, event);
1641       break;
1642
1643     case GST_EVENT_EOS:
1644       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1645       gst_audio_encoder_drain (enc);
1646
1647       /* check for pending events and tags */
1648       gst_audio_encoder_push_pending_events (enc);
1649       gst_audio_encoder_check_and_push_pending_tags (enc);
1650
1651       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1652
1653       /* forward immediately because no buffer or serialized event
1654        * will come after EOS and nothing could trigger another
1655        * _finish_frame() call. */
1656       res = gst_audio_encoder_push_event (enc, event);
1657       break;
1658
1659     case GST_EVENT_CAPS:
1660     {
1661       GstCaps *caps;
1662
1663       gst_event_parse_caps (event, &caps);
1664       enc->priv->do_caps = TRUE;
1665       res = TRUE;
1666       gst_event_unref (event);
1667       break;
1668     }
1669
1670     case GST_EVENT_STREAM_START:
1671     {
1672       GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1673       /* Flush upstream tags after a STREAM_START */
1674       GST_DEBUG_OBJECT (enc, "received STREAM_START. Clearing taglist");
1675       if (enc->priv->upstream_tags) {
1676         gst_tag_list_unref (enc->priv->upstream_tags);
1677         enc->priv->upstream_tags = NULL;
1678         enc->priv->tags_changed = TRUE;
1679       }
1680       GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1681       res = gst_audio_encoder_push_event (enc, event);
1682       break;
1683     }
1684
1685     case GST_EVENT_TAG:
1686     {
1687       GstTagList *tags;
1688
1689       gst_event_parse_tag (event, &tags);
1690
1691       if (gst_tag_list_get_scope (tags) == GST_TAG_SCOPE_STREAM) {
1692         GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1693         if (enc->priv->upstream_tags != tags) {
1694           tags = gst_tag_list_copy (tags);
1695
1696           /* FIXME: make generic based on GST_TAG_FLAG_ENCODED */
1697           gst_tag_list_remove_tag (tags, GST_TAG_CODEC);
1698           gst_tag_list_remove_tag (tags, GST_TAG_AUDIO_CODEC);
1699           gst_tag_list_remove_tag (tags, GST_TAG_VIDEO_CODEC);
1700           gst_tag_list_remove_tag (tags, GST_TAG_SUBTITLE_CODEC);
1701           gst_tag_list_remove_tag (tags, GST_TAG_CONTAINER_FORMAT);
1702           gst_tag_list_remove_tag (tags, GST_TAG_BITRATE);
1703           gst_tag_list_remove_tag (tags, GST_TAG_NOMINAL_BITRATE);
1704           gst_tag_list_remove_tag (tags, GST_TAG_MAXIMUM_BITRATE);
1705           gst_tag_list_remove_tag (tags, GST_TAG_MINIMUM_BITRATE);
1706           gst_tag_list_remove_tag (tags, GST_TAG_ENCODER);
1707           gst_tag_list_remove_tag (tags, GST_TAG_ENCODER_VERSION);
1708
1709           if (enc->priv->upstream_tags)
1710             gst_tag_list_unref (enc->priv->upstream_tags);
1711           enc->priv->upstream_tags = tags;
1712           GST_INFO_OBJECT (enc, "upstream stream tags: %" GST_PTR_FORMAT, tags);
1713         }
1714         gst_event_unref (event);
1715         event = gst_audio_encoder_create_merged_tags_event (enc);
1716         GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1717
1718         /* No tags, go out of here instead of fall through */
1719         if (!event) {
1720           res = TRUE;
1721           break;
1722         }
1723       }
1724       /* fall through */
1725     }
1726     default:
1727       /* Forward non-serialized events immediately. */
1728       if (!GST_EVENT_IS_SERIALIZED (event)) {
1729         res =
1730             gst_pad_event_default (enc->sinkpad, GST_OBJECT_CAST (enc), event);
1731       } else {
1732         GST_AUDIO_ENCODER_STREAM_LOCK (enc);
1733         if (gst_adapter_available (enc->priv->adapter) == 0) {
1734           enc->priv->early_pending_events =
1735               g_list_append (enc->priv->early_pending_events, event);
1736         } else {
1737           enc->priv->pending_events =
1738               g_list_append (enc->priv->pending_events, event);
1739         }
1740         GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
1741         res = TRUE;
1742       }
1743       break;
1744   }
1745   return res;
1746 }
1747
1748 static gboolean
1749 gst_audio_encoder_sink_event (GstPad * pad, GstObject * parent,
1750     GstEvent * event)
1751 {
1752   GstAudioEncoder *enc;
1753   GstAudioEncoderClass *klass;
1754   gboolean ret;
1755
1756   enc = GST_AUDIO_ENCODER (parent);
1757   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1758
1759   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1760       GST_EVENT_TYPE_NAME (event));
1761
1762   if (klass->sink_event)
1763     ret = klass->sink_event (enc, event);
1764   else {
1765     gst_event_unref (event);
1766     ret = FALSE;
1767   }
1768
1769   GST_DEBUG_OBJECT (enc, "event result %d", ret);
1770
1771   return ret;
1772 }
1773
1774 static gboolean
1775 gst_audio_encoder_sink_query_default (GstAudioEncoder * enc, GstQuery * query)
1776 {
1777   GstPad *pad = GST_AUDIO_ENCODER_SINK_PAD (enc);
1778   gboolean res = FALSE;
1779
1780   switch (GST_QUERY_TYPE (query)) {
1781     case GST_QUERY_FORMATS:
1782     {
1783       gst_query_set_formats (query, 3,
1784           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1785       res = TRUE;
1786       break;
1787     }
1788     case GST_QUERY_CONVERT:
1789     {
1790       GstFormat src_fmt, dest_fmt;
1791       gint64 src_val, dest_val;
1792
1793       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1794       GST_OBJECT_LOCK (enc);
1795       res = gst_audio_info_convert (&enc->priv->ctx.info,
1796           src_fmt, src_val, dest_fmt, &dest_val);
1797       GST_OBJECT_UNLOCK (enc);
1798       if (!res)
1799         goto error;
1800       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1801       res = TRUE;
1802       break;
1803     }
1804     case GST_QUERY_CAPS:
1805     {
1806       GstCaps *filter, *caps;
1807       GstAudioEncoderClass *klass;
1808
1809       gst_query_parse_caps (query, &filter);
1810
1811       klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1812       if (klass->getcaps) {
1813         caps = klass->getcaps (enc, filter);
1814         gst_query_set_caps_result (query, caps);
1815         gst_caps_unref (caps);
1816         res = TRUE;
1817       }
1818       break;
1819     }
1820     case GST_QUERY_ALLOCATION:
1821     {
1822       GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1823
1824       if (klass->propose_allocation)
1825         res = klass->propose_allocation (enc, query);
1826       break;
1827     }
1828     default:
1829       res = gst_pad_query_default (pad, GST_OBJECT (enc), query);
1830       break;
1831   }
1832
1833 error:
1834   return res;
1835 }
1836
1837 static gboolean
1838 gst_audio_encoder_sink_query (GstPad * pad, GstObject * parent,
1839     GstQuery * query)
1840 {
1841   GstAudioEncoder *encoder;
1842   GstAudioEncoderClass *encoder_class;
1843   gboolean ret = FALSE;
1844
1845   encoder = GST_AUDIO_ENCODER (parent);
1846   encoder_class = GST_AUDIO_ENCODER_GET_CLASS (encoder);
1847
1848   GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
1849       GST_QUERY_TYPE_NAME (query));
1850
1851   if (encoder_class->sink_query)
1852     ret = encoder_class->sink_query (encoder, query);
1853
1854   return ret;
1855 }
1856
1857 static gboolean
1858 gst_audio_encoder_src_event_default (GstAudioEncoder * enc, GstEvent * event)
1859 {
1860   gboolean res;
1861
1862   switch (GST_EVENT_TYPE (event)) {
1863     default:
1864       res = gst_pad_event_default (enc->srcpad, GST_OBJECT_CAST (enc), event);
1865       break;
1866   }
1867   return res;
1868 }
1869
1870 static gboolean
1871 gst_audio_encoder_src_event (GstPad * pad, GstObject * parent, GstEvent * event)
1872 {
1873   GstAudioEncoder *enc;
1874   GstAudioEncoderClass *klass;
1875   gboolean ret;
1876
1877   enc = GST_AUDIO_ENCODER (parent);
1878   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
1879
1880   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1881       GST_EVENT_TYPE_NAME (event));
1882
1883   if (klass->src_event)
1884     ret = klass->src_event (enc, event);
1885   else {
1886     gst_event_unref (event);
1887     ret = FALSE;
1888   }
1889
1890   return ret;
1891 }
1892
1893 static gboolean
1894 gst_audio_encoder_decide_allocation_default (GstAudioEncoder * enc,
1895     GstQuery * query)
1896 {
1897   GstAllocator *allocator = NULL;
1898   GstAllocationParams params;
1899   gboolean update_allocator;
1900
1901   /* we got configuration from our peer or the decide_allocation method,
1902    * parse them */
1903   if (gst_query_get_n_allocation_params (query) > 0) {
1904     /* try the allocator */
1905     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
1906     update_allocator = TRUE;
1907   } else {
1908     allocator = NULL;
1909     gst_allocation_params_init (&params);
1910     update_allocator = FALSE;
1911   }
1912
1913   if (update_allocator)
1914     gst_query_set_nth_allocation_param (query, 0, allocator, &params);
1915   else
1916     gst_query_add_allocation_param (query, allocator, &params);
1917   if (allocator)
1918     gst_object_unref (allocator);
1919
1920   return TRUE;
1921 }
1922
1923 static gboolean
1924 gst_audio_encoder_propose_allocation_default (GstAudioEncoder * enc,
1925     GstQuery * query)
1926 {
1927   return TRUE;
1928 }
1929
1930 /* FIXME ? are any of these queries (other than latency) an encoder's business
1931  * also, the conversion stuff might seem to make sense, but seems to not mind
1932  * segment stuff etc at all
1933  * Supposedly that's backward compatibility ... */
1934 static gboolean
1935 gst_audio_encoder_src_query_default (GstAudioEncoder * enc, GstQuery * query)
1936 {
1937   GstPad *pad = GST_AUDIO_ENCODER_SRC_PAD (enc);
1938   gboolean res = FALSE;
1939
1940   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1941
1942   switch (GST_QUERY_TYPE (query)) {
1943     case GST_QUERY_POSITION:
1944     {
1945       GstFormat fmt, req_fmt;
1946       gint64 pos, val;
1947
1948       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1949         GST_LOG_OBJECT (enc, "returning peer response");
1950         break;
1951       }
1952
1953       gst_query_parse_position (query, &req_fmt, NULL);
1954
1955       /* Refuse BYTES format queries. If it made sense to
1956        *        * answer them, upstream would have already */
1957       if (req_fmt == GST_FORMAT_BYTES) {
1958         GST_LOG_OBJECT (enc, "Ignoring BYTES position query");
1959         break;
1960       }
1961
1962       fmt = GST_FORMAT_TIME;
1963       if (!(res = gst_pad_peer_query_position (enc->sinkpad, fmt, &pos)))
1964         break;
1965
1966       if ((res =
1967               gst_pad_peer_query_convert (enc->sinkpad, fmt, pos, req_fmt,
1968                   &val))) {
1969         gst_query_set_position (query, req_fmt, val);
1970       }
1971       break;
1972     }
1973     case GST_QUERY_DURATION:
1974     {
1975       GstFormat fmt, req_fmt;
1976       gint64 dur, val;
1977
1978       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1979         GST_LOG_OBJECT (enc, "returning peer response");
1980         break;
1981       }
1982
1983       gst_query_parse_duration (query, &req_fmt, NULL);
1984
1985       /* Refuse BYTES format queries. If it made sense to
1986        *        * answer them, upstream would have already */
1987       if (req_fmt == GST_FORMAT_BYTES) {
1988         GST_LOG_OBJECT (enc, "Ignoring BYTES position query");
1989         break;
1990       }
1991
1992       fmt = GST_FORMAT_TIME;
1993       if (!(res = gst_pad_peer_query_duration (enc->sinkpad, fmt, &dur)))
1994         break;
1995
1996       if ((res =
1997               gst_pad_peer_query_convert (enc->sinkpad, fmt, dur, req_fmt,
1998                   &val))) {
1999         gst_query_set_duration (query, req_fmt, val);
2000       }
2001       break;
2002     }
2003     case GST_QUERY_FORMATS:
2004     {
2005       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
2006       res = TRUE;
2007       break;
2008     }
2009     case GST_QUERY_CONVERT:
2010     {
2011       GstFormat src_fmt, dest_fmt;
2012       gint64 src_val, dest_val;
2013
2014       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
2015       GST_OBJECT_LOCK (enc);
2016       res = __gst_audio_encoded_audio_convert (&enc->priv->ctx.info,
2017           enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
2018           &dest_fmt, &dest_val);
2019       GST_OBJECT_UNLOCK (enc);
2020       if (!res)
2021         break;
2022       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
2023       break;
2024     }
2025     case GST_QUERY_LATENCY:
2026     {
2027       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
2028         gboolean live;
2029         GstClockTime min_latency, max_latency;
2030
2031         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
2032         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
2033             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
2034             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
2035
2036         GST_OBJECT_LOCK (enc);
2037         /* add our latency */
2038         min_latency += enc->priv->ctx.min_latency;
2039         if (max_latency == -1 || enc->priv->ctx.max_latency == -1)
2040           max_latency = -1;
2041         else
2042           max_latency += enc->priv->ctx.max_latency;
2043         GST_OBJECT_UNLOCK (enc);
2044
2045         gst_query_set_latency (query, live, min_latency, max_latency);
2046       }
2047       break;
2048     }
2049     default:
2050       res = gst_pad_query_default (pad, GST_OBJECT (enc), query);
2051       break;
2052   }
2053
2054   return res;
2055 }
2056
2057 static gboolean
2058 gst_audio_encoder_src_query (GstPad * pad, GstObject * parent, GstQuery * query)
2059 {
2060   GstAudioEncoder *encoder;
2061   GstAudioEncoderClass *encoder_class;
2062   gboolean ret = FALSE;
2063
2064   encoder = GST_AUDIO_ENCODER (parent);
2065   encoder_class = GST_AUDIO_ENCODER_GET_CLASS (encoder);
2066
2067   GST_DEBUG_OBJECT (encoder, "received query %d, %s", GST_QUERY_TYPE (query),
2068       GST_QUERY_TYPE_NAME (query));
2069
2070   if (encoder_class->src_query)
2071     ret = encoder_class->src_query (encoder, query);
2072
2073   return ret;
2074 }
2075
2076
2077 static void
2078 gst_audio_encoder_set_property (GObject * object, guint prop_id,
2079     const GValue * value, GParamSpec * pspec)
2080 {
2081   GstAudioEncoder *enc;
2082
2083   enc = GST_AUDIO_ENCODER (object);
2084
2085   switch (prop_id) {
2086     case PROP_PERFECT_TS:
2087       if (enc->priv->granule && !g_value_get_boolean (value))
2088         GST_WARNING_OBJECT (enc, "perfect-timestamp can not be set FALSE "
2089             "while granule handling is enabled");
2090       else
2091         enc->priv->perfect_ts = g_value_get_boolean (value);
2092       break;
2093     case PROP_HARD_RESYNC:
2094       enc->priv->hard_resync = g_value_get_boolean (value);
2095       break;
2096     case PROP_TOLERANCE:
2097       enc->priv->tolerance = g_value_get_int64 (value);
2098       break;
2099     default:
2100       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2101       break;
2102   }
2103 }
2104
2105 static void
2106 gst_audio_encoder_get_property (GObject * object, guint prop_id,
2107     GValue * value, GParamSpec * pspec)
2108 {
2109   GstAudioEncoder *enc;
2110
2111   enc = GST_AUDIO_ENCODER (object);
2112
2113   switch (prop_id) {
2114     case PROP_PERFECT_TS:
2115       g_value_set_boolean (value, enc->priv->perfect_ts);
2116       break;
2117     case PROP_GRANULE:
2118       g_value_set_boolean (value, enc->priv->granule);
2119       break;
2120     case PROP_HARD_RESYNC:
2121       g_value_set_boolean (value, enc->priv->hard_resync);
2122       break;
2123     case PROP_TOLERANCE:
2124       g_value_set_int64 (value, enc->priv->tolerance);
2125       break;
2126     default:
2127       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
2128       break;
2129   }
2130 }
2131
2132 static gboolean
2133 gst_audio_encoder_activate (GstAudioEncoder * enc, gboolean active)
2134 {
2135   GstAudioEncoderClass *klass;
2136   gboolean result = TRUE;
2137
2138   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2139
2140   g_return_val_if_fail (!enc->priv->granule || enc->priv->perfect_ts, FALSE);
2141
2142   GST_DEBUG_OBJECT (enc, "activate %d", active);
2143
2144   if (active) {
2145     /* arrange clean state */
2146     gst_audio_encoder_reset (enc, TRUE);
2147
2148     if (!enc->priv->active && klass->start)
2149       result = klass->start (enc);
2150   } else {
2151     /* We must make sure streaming has finished before resetting things
2152      * and calling the ::stop vfunc */
2153     GST_PAD_STREAM_LOCK (enc->sinkpad);
2154     GST_PAD_STREAM_UNLOCK (enc->sinkpad);
2155
2156     if (enc->priv->active && klass->stop)
2157       result = klass->stop (enc);
2158
2159     /* clean up */
2160     gst_audio_encoder_reset (enc, TRUE);
2161   }
2162   GST_DEBUG_OBJECT (enc, "activate return: %d", result);
2163   return result;
2164 }
2165
2166
2167 static gboolean
2168 gst_audio_encoder_sink_activate_mode (GstPad * pad, GstObject * parent,
2169     GstPadMode mode, gboolean active)
2170 {
2171   gboolean result = TRUE;
2172   GstAudioEncoder *enc;
2173
2174   enc = GST_AUDIO_ENCODER (parent);
2175
2176   GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
2177
2178   result = gst_audio_encoder_activate (enc, active);
2179
2180   if (result)
2181     enc->priv->active = active;
2182
2183   GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
2184
2185   return result;
2186 }
2187
2188 /**
2189  * gst_audio_encoder_get_audio_info:
2190  * @enc: a #GstAudioEncoder
2191  *
2192  * Returns: (transfer none): a #GstAudioInfo describing the input audio format
2193  */
2194 GstAudioInfo *
2195 gst_audio_encoder_get_audio_info (GstAudioEncoder * enc)
2196 {
2197   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), NULL);
2198
2199   return &enc->priv->ctx.info;
2200 }
2201
2202 /**
2203  * gst_audio_encoder_set_frame_samples_min:
2204  * @enc: a #GstAudioEncoder
2205  * @num: number of samples per frame
2206  *
2207  * Sets number of samples (per channel) subclass needs to be handed,
2208  * at least or will be handed all available if 0.
2209  *
2210  * If an exact number of samples is required, gst_audio_encoder_set_frame_samples_max()
2211  * must be called with the same number.
2212  *
2213  * Note: This value will be reset to 0 every time before
2214  * #GstAudioEncoderClass.set_format() is called.
2215  */
2216 void
2217 gst_audio_encoder_set_frame_samples_min (GstAudioEncoder * enc, gint num)
2218 {
2219   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2220
2221   enc->priv->ctx.frame_samples_min = num;
2222   GST_LOG_OBJECT (enc, "set to %d", num);
2223 }
2224
2225 /**
2226  * gst_audio_encoder_get_frame_samples_min:
2227  * @enc: a #GstAudioEncoder
2228  *
2229  * Returns: currently minimum requested samples per frame
2230  */
2231 gint
2232 gst_audio_encoder_get_frame_samples_min (GstAudioEncoder * enc)
2233 {
2234   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2235
2236   return enc->priv->ctx.frame_samples_min;
2237 }
2238
2239 /**
2240  * gst_audio_encoder_set_frame_samples_max:
2241  * @enc: a #GstAudioEncoder
2242  * @num: number of samples per frame
2243  *
2244  * Sets number of samples (per channel) subclass needs to be handed,
2245  * at most or will be handed all available if 0.
2246  *
2247  * If an exact number of samples is required, gst_audio_encoder_set_frame_samples_min()
2248  * must be called with the same number.
2249  *
2250  * Note: This value will be reset to 0 every time before
2251  * #GstAudioEncoderClass.set_format() is called.
2252  */
2253 void
2254 gst_audio_encoder_set_frame_samples_max (GstAudioEncoder * enc, gint num)
2255 {
2256   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2257
2258   enc->priv->ctx.frame_samples_max = num;
2259   GST_LOG_OBJECT (enc, "set to %d", num);
2260 }
2261
2262 /**
2263  * gst_audio_encoder_get_frame_samples_max:
2264  * @enc: a #GstAudioEncoder
2265  *
2266  * Returns: currently maximum requested samples per frame
2267  */
2268 gint
2269 gst_audio_encoder_get_frame_samples_max (GstAudioEncoder * enc)
2270 {
2271   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2272
2273   return enc->priv->ctx.frame_samples_max;
2274 }
2275
2276 /**
2277  * gst_audio_encoder_set_frame_max:
2278  * @enc: a #GstAudioEncoder
2279  * @num: number of frames
2280  *
2281  * Sets max number of frames accepted at once (assumed minimally 1).
2282  * Requires @frame_samples_min and @frame_samples_max to be the equal.
2283  *
2284  * Note: This value will be reset to 0 every time before
2285  * #GstAudioEncoderClass.set_format() is called.
2286  */
2287 void
2288 gst_audio_encoder_set_frame_max (GstAudioEncoder * enc, gint num)
2289 {
2290   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2291
2292   enc->priv->ctx.frame_max = num;
2293   GST_LOG_OBJECT (enc, "set to %d", num);
2294 }
2295
2296 /**
2297  * gst_audio_encoder_get_frame_max:
2298  * @enc: a #GstAudioEncoder
2299  *
2300  * Returns: currently configured maximum handled frames
2301  */
2302 gint
2303 gst_audio_encoder_get_frame_max (GstAudioEncoder * enc)
2304 {
2305   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2306
2307   return enc->priv->ctx.frame_max;
2308 }
2309
2310 /**
2311  * gst_audio_encoder_set_lookahead:
2312  * @enc: a #GstAudioEncoder
2313  * @num: lookahead
2314  *
2315  * Sets encoder lookahead (in units of input rate samples)
2316  *
2317  * Note: This value will be reset to 0 every time before
2318  * #GstAudioEncoderClass.set_format() is called.
2319  */
2320 void
2321 gst_audio_encoder_set_lookahead (GstAudioEncoder * enc, gint num)
2322 {
2323   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2324
2325   enc->priv->ctx.lookahead = num;
2326   GST_LOG_OBJECT (enc, "set to %d", num);
2327 }
2328
2329 /**
2330  * gst_audio_encoder_get_lookahead:
2331  * @enc: a #GstAudioEncoder
2332  *
2333  * Returns: currently configured encoder lookahead
2334  */
2335 gint
2336 gst_audio_encoder_get_lookahead (GstAudioEncoder * enc)
2337 {
2338   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2339
2340   return enc->priv->ctx.lookahead;
2341 }
2342
2343 /**
2344  * gst_audio_encoder_set_latency:
2345  * @enc: a #GstAudioEncoder
2346  * @min: minimum latency
2347  * @max: maximum latency
2348  *
2349  * Sets encoder latency.
2350  */
2351 void
2352 gst_audio_encoder_set_latency (GstAudioEncoder * enc,
2353     GstClockTime min, GstClockTime max)
2354 {
2355   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2356   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (min));
2357   g_return_if_fail (min <= max);
2358
2359   GST_OBJECT_LOCK (enc);
2360   enc->priv->ctx.min_latency = min;
2361   enc->priv->ctx.max_latency = max;
2362   GST_OBJECT_UNLOCK (enc);
2363
2364   GST_LOG_OBJECT (enc, "set to %" GST_TIME_FORMAT "-%" GST_TIME_FORMAT,
2365       GST_TIME_ARGS (min), GST_TIME_ARGS (max));
2366
2367   /* post latency message on the bus */
2368   gst_element_post_message (GST_ELEMENT (enc),
2369       gst_message_new_latency (GST_OBJECT (enc)));
2370 }
2371
2372 /**
2373  * gst_audio_encoder_get_latency:
2374  * @enc: a #GstAudioEncoder
2375  * @min: (out) (allow-none): a pointer to storage to hold minimum latency
2376  * @max: (out) (allow-none): a pointer to storage to hold maximum latency
2377  *
2378  * Sets the variables pointed to by @min and @max to the currently configured
2379  * latency.
2380  */
2381 void
2382 gst_audio_encoder_get_latency (GstAudioEncoder * enc,
2383     GstClockTime * min, GstClockTime * max)
2384 {
2385   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2386
2387   GST_OBJECT_LOCK (enc);
2388   if (min)
2389     *min = enc->priv->ctx.min_latency;
2390   if (max)
2391     *max = enc->priv->ctx.max_latency;
2392   GST_OBJECT_UNLOCK (enc);
2393 }
2394
2395 /**
2396  * gst_audio_encoder_set_headers:
2397  * @enc: a #GstAudioEncoder
2398  * @headers: (transfer full) (element-type Gst.Buffer): a list of
2399  *   #GstBuffer containing the codec header
2400  *
2401  * Set the codec headers to be sent downstream whenever requested.
2402  */
2403 void
2404 gst_audio_encoder_set_headers (GstAudioEncoder * enc, GList * headers)
2405 {
2406   GST_DEBUG_OBJECT (enc, "new headers %p", headers);
2407
2408   if (enc->priv->ctx.headers) {
2409     g_list_foreach (enc->priv->ctx.headers, (GFunc) gst_buffer_unref, NULL);
2410     g_list_free (enc->priv->ctx.headers);
2411   }
2412   enc->priv->ctx.headers = headers;
2413   enc->priv->ctx.new_headers = TRUE;
2414 }
2415
2416 /**
2417  * gst_audio_encoder_set_allocation_caps:
2418  * @enc: a #GstAudioEncoder
2419  * @allocation_caps: (allow-none): a #GstCaps or %NULL
2420  *
2421  * Sets a caps in allocation query which are different from the set
2422  * pad's caps. Use this function before calling
2423  * gst_audio_encoder_negotiate(). Setting to %NULL the allocation
2424  * query will use the caps from the pad.
2425  *
2426  * Since: 1.10
2427  */
2428 void
2429 gst_audio_encoder_set_allocation_caps (GstAudioEncoder * enc,
2430     GstCaps * allocation_caps)
2431 {
2432   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2433
2434   gst_caps_replace (&enc->priv->ctx.allocation_caps, allocation_caps);
2435 }
2436
2437 /**
2438  * gst_audio_encoder_set_mark_granule:
2439  * @enc: a #GstAudioEncoder
2440  * @enabled: new state
2441  *
2442  * Enable or disable encoder granule handling.
2443  *
2444  * MT safe.
2445  */
2446 void
2447 gst_audio_encoder_set_mark_granule (GstAudioEncoder * enc, gboolean enabled)
2448 {
2449   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2450
2451   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2452
2453   GST_OBJECT_LOCK (enc);
2454   enc->priv->granule = enabled;
2455   GST_OBJECT_UNLOCK (enc);
2456 }
2457
2458 /**
2459  * gst_audio_encoder_get_mark_granule:
2460  * @enc: a #GstAudioEncoder
2461  *
2462  * Queries if the encoder will handle granule marking.
2463  *
2464  * Returns: TRUE if granule marking is enabled.
2465  *
2466  * MT safe.
2467  */
2468 gboolean
2469 gst_audio_encoder_get_mark_granule (GstAudioEncoder * enc)
2470 {
2471   gboolean result;
2472
2473   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2474
2475   GST_OBJECT_LOCK (enc);
2476   result = enc->priv->granule;
2477   GST_OBJECT_UNLOCK (enc);
2478
2479   return result;
2480 }
2481
2482 /**
2483  * gst_audio_encoder_set_perfect_timestamp:
2484  * @enc: a #GstAudioEncoder
2485  * @enabled: new state
2486  *
2487  * Enable or disable encoder perfect output timestamp preference.
2488  *
2489  * MT safe.
2490  */
2491 void
2492 gst_audio_encoder_set_perfect_timestamp (GstAudioEncoder * enc,
2493     gboolean enabled)
2494 {
2495   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2496
2497   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2498
2499   GST_OBJECT_LOCK (enc);
2500   enc->priv->perfect_ts = enabled;
2501   GST_OBJECT_UNLOCK (enc);
2502 }
2503
2504 /**
2505  * gst_audio_encoder_get_perfect_timestamp:
2506  * @enc: a #GstAudioEncoder
2507  *
2508  * Queries encoder perfect timestamp behaviour.
2509  *
2510  * Returns: TRUE if perfect timestamp setting enabled.
2511  *
2512  * MT safe.
2513  */
2514 gboolean
2515 gst_audio_encoder_get_perfect_timestamp (GstAudioEncoder * enc)
2516 {
2517   gboolean result;
2518
2519   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2520
2521   GST_OBJECT_LOCK (enc);
2522   result = enc->priv->perfect_ts;
2523   GST_OBJECT_UNLOCK (enc);
2524
2525   return result;
2526 }
2527
2528 /**
2529  * gst_audio_encoder_set_hard_sync:
2530  * @enc: a #GstAudioEncoder
2531  * @enabled: new state
2532  *
2533  * Sets encoder hard resync handling.
2534  *
2535  * MT safe.
2536  */
2537 void
2538 gst_audio_encoder_set_hard_resync (GstAudioEncoder * enc, gboolean enabled)
2539 {
2540   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2541
2542   GST_LOG_OBJECT (enc, "enabled: %d", enabled);
2543
2544   GST_OBJECT_LOCK (enc);
2545   enc->priv->hard_resync = enabled;
2546   GST_OBJECT_UNLOCK (enc);
2547 }
2548
2549 /**
2550  * gst_audio_encoder_get_hard_sync:
2551  * @enc: a #GstAudioEncoder
2552  *
2553  * Queries encoder's hard resync setting.
2554  *
2555  * Returns: TRUE if hard resync is enabled.
2556  *
2557  * MT safe.
2558  */
2559 gboolean
2560 gst_audio_encoder_get_hard_resync (GstAudioEncoder * enc)
2561 {
2562   gboolean result;
2563
2564   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2565
2566   GST_OBJECT_LOCK (enc);
2567   result = enc->priv->hard_resync;
2568   GST_OBJECT_UNLOCK (enc);
2569
2570   return result;
2571 }
2572
2573 /**
2574  * gst_audio_encoder_set_tolerance:
2575  * @enc: a #GstAudioEncoder
2576  * @tolerance: new tolerance
2577  *
2578  * Configures encoder audio jitter tolerance threshold.
2579  *
2580  * MT safe.
2581  */
2582 void
2583 gst_audio_encoder_set_tolerance (GstAudioEncoder * enc, GstClockTime tolerance)
2584 {
2585   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2586   g_return_if_fail (GST_CLOCK_TIME_IS_VALID (tolerance));
2587
2588   GST_OBJECT_LOCK (enc);
2589   enc->priv->tolerance = tolerance;
2590   GST_OBJECT_UNLOCK (enc);
2591
2592   GST_LOG_OBJECT (enc, "set to %" GST_TIME_FORMAT, GST_TIME_ARGS (tolerance));
2593 }
2594
2595 /**
2596  * gst_audio_encoder_get_tolerance:
2597  * @enc: a #GstAudioEncoder
2598  *
2599  * Queries current audio jitter tolerance threshold.
2600  *
2601  * Returns: encoder audio jitter tolerance threshold.
2602  *
2603  * MT safe.
2604  */
2605 GstClockTime
2606 gst_audio_encoder_get_tolerance (GstAudioEncoder * enc)
2607 {
2608   GstClockTime result;
2609
2610   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2611
2612   GST_OBJECT_LOCK (enc);
2613   result = enc->priv->tolerance;
2614   GST_OBJECT_UNLOCK (enc);
2615
2616   return result;
2617 }
2618
2619 /**
2620  * gst_audio_encoder_set_hard_min:
2621  * @enc: a #GstAudioEncoder
2622  * @enabled: new state
2623  *
2624  * Configures encoder hard minimum handling.  If enabled, subclass
2625  * will never be handed less samples than it configured, which otherwise
2626  * might occur near end-of-data handling.  Instead, the leftover samples
2627  * will simply be discarded.
2628  *
2629  * MT safe.
2630  */
2631 void
2632 gst_audio_encoder_set_hard_min (GstAudioEncoder * enc, gboolean enabled)
2633 {
2634   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2635
2636   GST_OBJECT_LOCK (enc);
2637   enc->priv->hard_min = enabled;
2638   GST_OBJECT_UNLOCK (enc);
2639 }
2640
2641 /**
2642  * gst_audio_encoder_get_hard_min:
2643  * @enc: a #GstAudioEncoder
2644  *
2645  * Queries encoder hard minimum handling.
2646  *
2647  * Returns: TRUE if hard minimum handling is enabled.
2648  *
2649  * MT safe.
2650  */
2651 gboolean
2652 gst_audio_encoder_get_hard_min (GstAudioEncoder * enc)
2653 {
2654   gboolean result;
2655
2656   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2657
2658   GST_OBJECT_LOCK (enc);
2659   result = enc->priv->hard_min;
2660   GST_OBJECT_UNLOCK (enc);
2661
2662   return result;
2663 }
2664
2665 /**
2666  * gst_audio_encoder_set_drainable:
2667  * @enc: a #GstAudioEncoder
2668  * @enabled: new state
2669  *
2670  * Configures encoder drain handling.  If drainable, subclass might
2671  * be handed a NULL buffer to have it return any leftover encoded data.
2672  * Otherwise, it is not considered so capable and will only ever be passed
2673  * real data.
2674  *
2675  * MT safe.
2676  */
2677 void
2678 gst_audio_encoder_set_drainable (GstAudioEncoder * enc, gboolean enabled)
2679 {
2680   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2681
2682   GST_OBJECT_LOCK (enc);
2683   enc->priv->drainable = enabled;
2684   GST_OBJECT_UNLOCK (enc);
2685 }
2686
2687 /**
2688  * gst_audio_encoder_get_drainable:
2689  * @enc: a #GstAudioEncoder
2690  *
2691  * Queries encoder drain handling.
2692  *
2693  * Returns: TRUE if drainable handling is enabled.
2694  *
2695  * MT safe.
2696  */
2697 gboolean
2698 gst_audio_encoder_get_drainable (GstAudioEncoder * enc)
2699 {
2700   gboolean result;
2701
2702   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), 0);
2703
2704   GST_OBJECT_LOCK (enc);
2705   result = enc->priv->drainable;
2706   GST_OBJECT_UNLOCK (enc);
2707
2708   return result;
2709 }
2710
2711 /**
2712  * gst_audio_encoder_merge_tags:
2713  * @enc: a #GstAudioEncoder
2714  * @tags: (allow-none): a #GstTagList to merge, or NULL to unset
2715  *     previously-set tags
2716  * @mode: the #GstTagMergeMode to use, usually #GST_TAG_MERGE_REPLACE
2717  *
2718  * Sets the audio encoder tags and how they should be merged with any
2719  * upstream stream tags. This will override any tags previously-set
2720  * with gst_audio_encoder_merge_tags().
2721  *
2722  * Note that this is provided for convenience, and the subclass is
2723  * not required to use this and can still do tag handling on its own.
2724  *
2725  * MT safe.
2726  */
2727 void
2728 gst_audio_encoder_merge_tags (GstAudioEncoder * enc,
2729     const GstTagList * tags, GstTagMergeMode mode)
2730 {
2731   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
2732   g_return_if_fail (tags == NULL || GST_IS_TAG_LIST (tags));
2733   g_return_if_fail (tags == NULL || mode != GST_TAG_MERGE_UNDEFINED);
2734
2735   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2736   if (enc->priv->tags != tags) {
2737     if (enc->priv->tags) {
2738       gst_tag_list_unref (enc->priv->tags);
2739       enc->priv->tags = NULL;
2740       enc->priv->tags_merge_mode = GST_TAG_MERGE_APPEND;
2741     }
2742     if (tags) {
2743       enc->priv->tags = gst_tag_list_ref ((GstTagList *) tags);
2744       enc->priv->tags_merge_mode = mode;
2745     }
2746
2747     GST_DEBUG_OBJECT (enc, "setting encoder tags to %" GST_PTR_FORMAT, tags);
2748     enc->priv->tags_changed = TRUE;
2749   }
2750   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2751 }
2752
2753 static gboolean
2754 gst_audio_encoder_negotiate_default (GstAudioEncoder * enc)
2755 {
2756   GstAudioEncoderClass *klass;
2757   gboolean res = TRUE;
2758   GstQuery *query = NULL;
2759   GstAllocator *allocator;
2760   GstAllocationParams params;
2761   GstCaps *caps, *prevcaps;
2762
2763   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2764   g_return_val_if_fail (GST_IS_CAPS (enc->priv->ctx.caps), FALSE);
2765
2766   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2767
2768   caps = enc->priv->ctx.caps;
2769   if (enc->priv->ctx.allocation_caps == NULL)
2770     enc->priv->ctx.allocation_caps = gst_caps_ref (caps);
2771
2772   GST_DEBUG_OBJECT (enc, "Setting srcpad caps %" GST_PTR_FORMAT, caps);
2773
2774   if (enc->priv->early_pending_events) {
2775     GList **pending_events, *l;
2776
2777     pending_events = &enc->priv->early_pending_events;
2778
2779     GST_DEBUG_OBJECT (enc, "Pushing pending events");
2780     for (l = *pending_events; l;) {
2781       GstEvent *event = GST_EVENT (l->data);
2782       GList *tmp;
2783
2784       if (GST_EVENT_TYPE (event) < GST_EVENT_CAPS) {
2785         gst_audio_encoder_push_event (enc, l->data);
2786         tmp = l;
2787         l = l->next;
2788         *pending_events = g_list_delete_link (*pending_events, tmp);
2789       } else {
2790         l = l->next;
2791       }
2792     }
2793   }
2794
2795   prevcaps = gst_pad_get_current_caps (enc->srcpad);
2796   if (!prevcaps || !gst_caps_is_equal (prevcaps, caps))
2797     res = gst_pad_set_caps (enc->srcpad, caps);
2798   if (prevcaps)
2799     gst_caps_unref (prevcaps);
2800
2801   if (!res)
2802     goto done;
2803   enc->priv->ctx.output_caps_changed = FALSE;
2804
2805   query = gst_query_new_allocation (enc->priv->ctx.allocation_caps, TRUE);
2806   if (!gst_pad_peer_query (enc->srcpad, query)) {
2807     GST_DEBUG_OBJECT (enc, "didn't get downstream ALLOCATION hints");
2808   }
2809
2810   g_assert (klass->decide_allocation != NULL);
2811   res = klass->decide_allocation (enc, query);
2812
2813   GST_DEBUG_OBJECT (enc, "ALLOCATION (%d) params: %" GST_PTR_FORMAT, res,
2814       query);
2815
2816   if (!res)
2817     goto no_decide_allocation;
2818
2819   /* we got configuration from our peer or the decide_allocation method,
2820    * parse them */
2821   if (gst_query_get_n_allocation_params (query) > 0) {
2822     gst_query_parse_nth_allocation_param (query, 0, &allocator, &params);
2823   } else {
2824     allocator = NULL;
2825     gst_allocation_params_init (&params);
2826   }
2827
2828   if (enc->priv->ctx.allocator)
2829     gst_object_unref (enc->priv->ctx.allocator);
2830   enc->priv->ctx.allocator = allocator;
2831   enc->priv->ctx.params = params;
2832
2833 done:
2834   if (query)
2835     gst_query_unref (query);
2836
2837   return res;
2838
2839   /* ERRORS */
2840 no_decide_allocation:
2841   {
2842     GST_WARNING_OBJECT (enc, "Subclass failed to decide allocation");
2843     goto done;
2844   }
2845 }
2846
2847 static gboolean
2848 gst_audio_encoder_negotiate_unlocked (GstAudioEncoder * enc)
2849 {
2850   GstAudioEncoderClass *klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2851   gboolean ret = TRUE;
2852
2853   if (G_LIKELY (klass->negotiate))
2854     ret = klass->negotiate (enc);
2855
2856   enc->priv->ctx.negotiated = TRUE;
2857
2858   return ret;
2859 }
2860
2861 /**
2862  * gst_audio_encoder_negotiate:
2863  * @enc: a #GstAudioEncoder
2864  *
2865  * Negotiate with downstream elements to currently configured #GstCaps.
2866  * Unmark GST_PAD_FLAG_NEED_RECONFIGURE in any case. But mark it again if
2867  * negotiate fails.
2868  *
2869  * Returns: %TRUE if the negotiation succeeded, else %FALSE.
2870  */
2871 gboolean
2872 gst_audio_encoder_negotiate (GstAudioEncoder * enc)
2873 {
2874   GstAudioEncoderClass *klass;
2875   gboolean ret = TRUE;
2876
2877   g_return_val_if_fail (GST_IS_AUDIO_ENCODER (enc), FALSE);
2878
2879   klass = GST_AUDIO_ENCODER_GET_CLASS (enc);
2880
2881   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2882   gst_pad_check_reconfigure (enc->srcpad);
2883   if (klass->negotiate) {
2884     ret = klass->negotiate (enc);
2885     if (!ret)
2886       gst_pad_mark_reconfigure (enc->srcpad);
2887   }
2888   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2889
2890   return ret;
2891 }
2892
2893 /**
2894  * gst_audio_encoder_set_output_format:
2895  * @enc: a #GstAudioEncoder
2896  * @caps: (transfer none): #GstCaps
2897  *
2898  * Configure output caps on the srcpad of @enc.
2899  *
2900  * Returns: %TRUE on success.
2901  */
2902 gboolean
2903 gst_audio_encoder_set_output_format (GstAudioEncoder * enc, GstCaps * caps)
2904 {
2905   gboolean res = TRUE;
2906   GstCaps *templ_caps;
2907
2908   GST_DEBUG_OBJECT (enc, "Setting srcpad caps %" GST_PTR_FORMAT, caps);
2909
2910   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2911   if (!gst_caps_is_fixed (caps))
2912     goto refuse_caps;
2913
2914   /* Only allow caps that are a subset of the template caps */
2915   templ_caps = gst_pad_get_pad_template_caps (enc->srcpad);
2916   if (!gst_caps_is_subset (caps, templ_caps)) {
2917     gst_caps_unref (templ_caps);
2918     goto refuse_caps;
2919   }
2920   gst_caps_unref (templ_caps);
2921
2922   gst_caps_replace (&enc->priv->ctx.caps, caps);
2923   enc->priv->ctx.output_caps_changed = TRUE;
2924
2925 done:
2926   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2927
2928   return res;
2929
2930   /* ERRORS */
2931 refuse_caps:
2932   {
2933     GST_WARNING_OBJECT (enc, "refused caps %" GST_PTR_FORMAT, caps);
2934     res = FALSE;
2935     goto done;
2936   }
2937 }
2938
2939 /**
2940  * gst_audio_encoder_allocate_output_buffer:
2941  * @enc: a #GstAudioEncoder
2942  * @size: size of the buffer
2943  *
2944  * Helper function that allocates a buffer to hold an encoded audio frame
2945  * for @enc's current output format.
2946  *
2947  * Returns: (transfer full): allocated buffer
2948  */
2949 GstBuffer *
2950 gst_audio_encoder_allocate_output_buffer (GstAudioEncoder * enc, gsize size)
2951 {
2952   GstBuffer *buffer = NULL;
2953   gboolean needs_reconfigure = FALSE;
2954
2955   g_return_val_if_fail (size > 0, NULL);
2956
2957   GST_DEBUG ("alloc src buffer");
2958
2959   GST_AUDIO_ENCODER_STREAM_LOCK (enc);
2960
2961   needs_reconfigure = gst_pad_check_reconfigure (enc->srcpad);
2962   if (G_UNLIKELY (enc->priv->ctx.output_caps_changed || (enc->priv->ctx.caps
2963               && needs_reconfigure))) {
2964     if (!gst_audio_encoder_negotiate_unlocked (enc)) {
2965       GST_INFO_OBJECT (enc, "Failed to negotiate, fallback allocation");
2966       gst_pad_mark_reconfigure (enc->srcpad);
2967       goto fallback;
2968     }
2969   }
2970
2971   buffer =
2972       gst_buffer_new_allocate (enc->priv->ctx.allocator, size,
2973       &enc->priv->ctx.params);
2974   if (!buffer) {
2975     GST_INFO_OBJECT (enc, "couldn't allocate output buffer");
2976     goto fallback;
2977   }
2978
2979   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2980
2981   return buffer;
2982
2983 fallback:
2984   buffer = gst_buffer_new_allocate (NULL, size, NULL);
2985   GST_AUDIO_ENCODER_STREAM_UNLOCK (enc);
2986
2987   return buffer;
2988 }
2989
2990 /**
2991  * gst_audio_encoder_get_allocator:
2992  * @enc: a #GstAudioEncoder
2993  * @allocator: (out) (allow-none) (transfer full): the #GstAllocator
2994  * used
2995  * @params: (out) (allow-none) (transfer full): the
2996  * #GstAllocationParams of @allocator
2997  *
2998  * Lets #GstAudioEncoder sub-classes to know the memory @allocator
2999  * used by the base class and its @params.
3000  *
3001  * Unref the @allocator after use it.
3002  */
3003 void
3004 gst_audio_encoder_get_allocator (GstAudioEncoder * enc,
3005     GstAllocator ** allocator, GstAllocationParams * params)
3006 {
3007   g_return_if_fail (GST_IS_AUDIO_ENCODER (enc));
3008
3009   if (allocator)
3010     *allocator = enc->priv->ctx.allocator ?
3011         gst_object_ref (enc->priv->ctx.allocator) : NULL;
3012
3013   if (params)
3014     *params = enc->priv->ctx.params;
3015 }