baseaudioencoder: debug format fixes
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstbaseaudioencoder.c
1 /* GStreamer
2  * Copyright (C) 2011 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>.
3  * Copyright (C) 2011 Nokia Corporation. All rights reserved.
4  *   Contact: Stefan Kost <stefan.kost@nokia.com>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /**
23  * SECTION:gstbaseaudioencoder
24  * @short_description: Base class for audio encoders
25  * @see_also: #GstBaseTransform
26  *
27  * This base class is for audio encoders turning raw audio samples into
28  * encoded audio data.
29  *
30  * GstBaseAudioEncoder and subclass should cooperate as follows.
31  * <orderedlist>
32  * <listitem>
33  *   <itemizedlist><title>Configuration</title>
34  *   <listitem><para>
35  *     Initially, GstBaseAudioEncoder calls @start when the encoder element
36  *     is activated, which allows subclass to perform any global setup.
37  *   </para></listitem>
38  *   <listitem><para>
39  *     GstBaseAudioEncoder calls @set_format to inform subclass of the format
40  *     of input audio data that it is about to receive.  Subclass should
41  *     setup for encoding and configure various base class context parameters
42  *     appropriately, notably those directing desired input data handling.
43  *     While unlikely, it might be called more than once, if changing input
44  *     parameters require reconfiguration.
45  *   </para></listitem>
46  *   <listitem><para>
47  *     GstBaseAudioEncoder calls @stop at end of all processing.
48  *   </para></listitem>
49  *   </itemizedlist>
50  * </listitem>
51  * As of configuration stage, and throughout processing, GstBaseAudioEncoder
52  * provides a GstBaseAudioEncoderContext that provides required context,
53  * e.g. describing the format of input audio data.
54  * Conversely, subclass can and should configure context to inform
55  * base class of its expectation w.r.t. buffer handling.
56  * <listitem>
57  *   <itemizedlist>
58  *   <title>Data processing</title>
59  *     <listitem><para>
60  *       Base class gathers input sample data (as directed by the context's
61  *       frame_samples and frame_max) and provides this to subclass' @handle_frame.
62  *     </para></listitem>
63  *     <listitem><para>
64  *       If codec processing results in encoded data, subclass should call
65  *       @gst_base_audio_encoder_finish_frame to have encoded data pushed
66  *       downstream.  Alternatively, it might also call to indicate dropped
67  *       (non-encoded) samples.
68  *     </para></listitem>
69  *     <listitem><para>
70  *       Just prior to actually pushing a buffer downstream,
71  *       it is passed to @pre_push.
72  *     </para></listitem>
73  *     <listitem><para>
74  *       During the parsing process GstBaseAudioEncoderClass will handle both
75  *       srcpad and sinkpad events. Sink events will be passed to subclass
76  *       if @event callback has been provided.
77  *     </para></listitem>
78  *   </itemizedlist>
79  * </listitem>
80  * <listitem>
81  *   <itemizedlist><title>Shutdown phase</title>
82  *   <listitem><para>
83  *     GstBaseAudioEncoder class calls @stop to inform the subclass that data
84  *     parsing will be stopped.
85  *   </para></listitem>
86  *   </itemizedlist>
87  * </listitem>
88  * </orderedlist>
89  *
90  * Subclass is responsible for providing pad template caps for
91  * source and sink pads. The pads need to be named "sink" and "src". It also 
92  * needs to set the fixed caps on srcpad, when the format is ensured.  This
93  * is typically when base class calls subclass' @set_format function, though
94  * it might be delayed until calling @gst_base_audio_encoder_finish_frame.
95  *
96  * In summary, above process should have subclass concentrating on
97  * codec data processing while leaving other matters to base class,
98  * such as most notably timestamp handling.  While it may exert more control
99  * in this area (see e.g. @pre_push), it is very much not recommended.
100  *
101  * In particular, base class will either favor tracking upstream timestamps
102  * (at the possible expense of jitter) or aim to arrange for a perfect stream of
103  * output timestamps, depending on #GstBaseAudioEncoder:perfect-ts.
104  * However, in the latter case, the input may not be so perfect or ideal, which
105  * is handled as follows.  An input timestamp is compared with the expected
106  * timestamp as dictated by input sample stream and if the deviation is less
107  * than #GstBaseAudioEncoder:tolerance, the deviation is discarded.
108  * Otherwise, it is considered a discontuinity and subsequent output timestamp
109  * is resynced to the new position after performing configured discontinuity
110  * processing.  In the non-perfect-ts case, an upstream variation exceeding
111  * tolerance only leads to marking DISCONT on subsequent outgoing
112  * (while timestamps are adjusted to upstream regardless of variation).
113  * While DISCONT is also marked in the perfect-ts case, this one optionally
114  * (see #GstBaseAudioEncoder:hard-resync)
115  * performs some additional steps, such as clipping of (early) input samples
116  * or draining all currently remaining input data, depending on the direction
117  * of the discontuinity.
118  *
119  * If perfect timestamps are arranged, it is also possible to request baseclass
120  * (usually set by subclass) to provide additional buffer metadata (in OFFSET
121  * and OFFSET_END) fields according to granule defined semantics currently
122  * needed by oggmux.  Specifically, OFFSET is set to granulepos (= sample count
123  * including buffer) and OFFSET_END to corresponding timestamp (as determined
124  * by same sample count and sample rate).
125  *
126  * Things that subclass need to take care of:
127  * <itemizedlist>
128  *   <listitem><para>Provide pad templates</para></listitem>
129  *   <listitem><para>
130  *      Set source pad caps when appropriate
131  *   </para></listitem>
132  *   <listitem><para>
133  *      Inform base class of buffer processing needs using context's
134  *      frame_samples and frame_bytes.
135  *   </para></listitem>
136  *   <listitem><para>
137  *      Set user-configurable properties to sane defaults for format and
138  *      implementing codec at hand, e.g. those controlling timestamp behaviour
139  *      and discontinuity processing.
140  *   </para></listitem>
141  *   <listitem><para>
142  *      Accept data in @handle_frame and provide encoded results to
143  *      @gst_base_audio_encoder_finish_frame.
144  *   </para></listitem>
145  * </itemizedlist>
146  *
147  */
148
149 #ifdef HAVE_CONFIG_H
150 #  include "config.h"
151 #endif
152
153 #include "gstbaseaudioencoder.h"
154 #include <gst/base/gstadapter.h>
155 #include <gst/audio/audio.h>
156
157 #include <stdlib.h>
158 #include <string.h>
159
160
161 GST_DEBUG_CATEGORY_STATIC (gst_base_audio_encoder_debug);
162 #define GST_CAT_DEFAULT gst_base_audio_encoder_debug
163
164 #define GST_BASE_AUDIO_ENCODER_GET_PRIVATE(obj)  \
165     (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_ENCODER, \
166         GstBaseAudioEncoderPrivate))
167
168 enum
169 {
170   PROP_0,
171   PROP_PERFECT_TS,
172   PROP_GRANULE,
173   PROP_HARD_RESYNC,
174   PROP_TOLERANCE
175 };
176
177 #define DEFAULT_PERFECT_TS   FALSE
178 #define DEFAULT_GRANULE      FALSE
179 #define DEFAULT_HARD_RESYNC  FALSE
180 #define DEFAULT_TOLERANCE    40000000
181
182 struct _GstBaseAudioEncoderPrivate
183 {
184   /* activation status */
185   gboolean active;
186
187   /* input base/first ts as basis for output ts;
188    * kept nearly constant for perfect_ts,
189    * otherwise resyncs to upstream ts */
190   GstClockTime base_ts;
191   /* corresponding base granulepos */
192   gint64 base_gp;
193   /* input samples processed and sent downstream so far (w.r.t. base_ts) */
194   guint64 samples;
195
196   /* currently collected sample data */
197   GstAdapter *adapter;
198   /* offset in adapter up to which already supplied to encoder */
199   gint offset;
200   /* mark outgoing discont */
201   gboolean discont;
202   /* to guess duration of drained data */
203   GstClockTime last_duration;
204
205   /* subclass provided data in processing round */
206   gboolean got_data;
207   /* subclass gave all it could already */
208   gboolean drained;
209   /* subclass currently being forcibly drained */
210   gboolean force;
211
212   /* output bps estimatation */
213   /* global in samples seen */
214   guint64 samples_in;
215   /* global bytes sent out */
216   guint64 bytes_out;
217
218   /* context storage */
219   GstBaseAudioEncoderContext ctx;
220 };
221
222
223 static GstElementClass *parent_class = NULL;
224
225 static void gst_base_audio_encoder_class_init (GstBaseAudioEncoderClass *
226     klass);
227 static void gst_base_audio_encoder_init (GstBaseAudioEncoder * parse,
228     GstBaseAudioEncoderClass * klass);
229
230 GType
231 gst_base_audio_encoder_get_type (void)
232 {
233   static GType base_audio_encoder_type = 0;
234
235   if (!base_audio_encoder_type) {
236     static const GTypeInfo base_audio_encoder_info = {
237       sizeof (GstBaseAudioEncoderClass),
238       (GBaseInitFunc) NULL,
239       (GBaseFinalizeFunc) NULL,
240       (GClassInitFunc) gst_base_audio_encoder_class_init,
241       NULL,
242       NULL,
243       sizeof (GstBaseAudioEncoder),
244       0,
245       (GInstanceInitFunc) gst_base_audio_encoder_init,
246     };
247     const GInterfaceInfo preset_interface_info = {
248       NULL,                     /* interface_init */
249       NULL,                     /* interface_finalize */
250       NULL                      /* interface_data */
251     };
252
253     base_audio_encoder_type = g_type_register_static (GST_TYPE_ELEMENT,
254         "GstBaseAudioEncoder", &base_audio_encoder_info, G_TYPE_FLAG_ABSTRACT);
255
256     g_type_add_interface_static (base_audio_encoder_type, GST_TYPE_PRESET,
257         &preset_interface_info);
258   }
259   return base_audio_encoder_type;
260 }
261
262 static void gst_base_audio_encoder_finalize (GObject * object);
263 static void gst_base_audio_encoder_reset (GstBaseAudioEncoder * enc,
264     gboolean full);
265
266 static void gst_base_audio_encoder_set_property (GObject * object,
267     guint prop_id, const GValue * value, GParamSpec * pspec);
268 static void gst_base_audio_encoder_get_property (GObject * object,
269     guint prop_id, GValue * value, GParamSpec * pspec);
270
271 static gboolean gst_base_audio_encoder_sink_activate_push (GstPad * pad,
272     gboolean active);
273
274 static gboolean gst_base_audio_encoder_sink_event (GstPad * pad,
275     GstEvent * event);
276 static gboolean gst_base_audio_encoder_sink_setcaps (GstPad * pad,
277     GstCaps * caps);
278 static GstFlowReturn gst_base_audio_encoder_chain (GstPad * pad,
279     GstBuffer * buffer);
280 static gboolean gst_base_audio_encoder_src_query (GstPad * pad,
281     GstQuery * query);
282 static gboolean gst_base_audio_encoder_sink_query (GstPad * pad,
283     GstQuery * query);
284 static const GstQueryType *gst_base_audio_encoder_get_query_types (GstPad *
285     pad);
286 static GstCaps *gst_base_audio_encoder_sink_getcaps (GstPad * pad);
287
288
289 static void
290 gst_base_audio_encoder_class_init (GstBaseAudioEncoderClass * klass)
291 {
292   GObjectClass *gobject_class;
293
294   gobject_class = G_OBJECT_CLASS (klass);
295   parent_class = g_type_class_peek_parent (klass);
296
297   GST_DEBUG_CATEGORY_INIT (gst_base_audio_encoder_debug, "baseaudioencoder", 0,
298       "baseaudioencoder element");
299
300   g_type_class_add_private (klass, sizeof (GstBaseAudioEncoderPrivate));
301
302   gobject_class->set_property = gst_base_audio_encoder_set_property;
303   gobject_class->get_property = gst_base_audio_encoder_get_property;
304
305   gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_base_audio_encoder_finalize);
306
307   /* properties */
308   g_object_class_install_property (gobject_class, PROP_PERFECT_TS,
309       g_param_spec_boolean ("perfect-ts", "Perfect Timestamps",
310           "Favour perfect timestamps over tracking upstream timestamps",
311           DEFAULT_PERFECT_TS, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
312   g_object_class_install_property (gobject_class, PROP_GRANULE,
313       g_param_spec_boolean ("granule", "Granule Marking",
314           "Apply granule semantics to buffer metadata (implies perfect-ts)",
315           DEFAULT_GRANULE, G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
316   g_object_class_install_property (gobject_class, PROP_HARD_RESYNC,
317       g_param_spec_boolean ("hard-resync", "Hard Resync",
318           "Perform clipping and sample flushing upon discontinuity",
319           DEFAULT_HARD_RESYNC, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
320   g_object_class_install_property (gobject_class, PROP_TOLERANCE,
321       g_param_spec_int64 ("tolerance", "Tolerance",
322           "Consider discontinuity if timestamp jitter/imperfection exceeds tolerance (ns)",
323           0, G_MAXINT64, DEFAULT_TOLERANCE,
324           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
325 }
326
327 static void
328 gst_base_audio_encoder_init (GstBaseAudioEncoder * enc,
329     GstBaseAudioEncoderClass * bclass)
330 {
331   GstPadTemplate *pad_template;
332
333   GST_DEBUG_OBJECT (enc, "gst_base_audio_encoder_init");
334
335   enc->priv = GST_BASE_AUDIO_ENCODER_GET_PRIVATE (enc);
336
337   /* only push mode supported */
338   pad_template =
339       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "sink");
340   g_return_if_fail (pad_template != NULL);
341   enc->sinkpad = gst_pad_new_from_template (pad_template, "sink");
342   gst_pad_set_event_function (enc->sinkpad,
343       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_event));
344   gst_pad_set_setcaps_function (enc->sinkpad,
345       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_setcaps));
346   gst_pad_set_getcaps_function (enc->sinkpad,
347       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_getcaps));
348   gst_pad_set_query_function (enc->sinkpad,
349       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_query));
350   gst_pad_set_chain_function (enc->sinkpad,
351       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_chain));
352   gst_pad_set_activatepush_function (enc->sinkpad,
353       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_sink_activate_push));
354   gst_element_add_pad (GST_ELEMENT (enc), enc->sinkpad);
355
356   GST_DEBUG_OBJECT (enc, "sinkpad created");
357
358   /* and we don't mind upstream traveling stuff that much ... */
359   pad_template =
360       gst_element_class_get_pad_template (GST_ELEMENT_CLASS (bclass), "src");
361   g_return_if_fail (pad_template != NULL);
362   enc->srcpad = gst_pad_new_from_template (pad_template, "src");
363   gst_pad_set_query_function (enc->srcpad,
364       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_src_query));
365   gst_pad_set_query_type_function (enc->srcpad,
366       GST_DEBUG_FUNCPTR (gst_base_audio_encoder_get_query_types));
367   gst_pad_use_fixed_caps (enc->srcpad);
368   gst_element_add_pad (GST_ELEMENT (enc), enc->srcpad);
369   GST_DEBUG_OBJECT (enc, "src created");
370
371   enc->priv->adapter = gst_adapter_new ();
372   enc->ctx = &enc->priv->ctx;
373
374   /* property default */
375   enc->perfect_ts = DEFAULT_PERFECT_TS;
376   enc->hard_resync = DEFAULT_HARD_RESYNC;
377   enc->tolerance = DEFAULT_TOLERANCE;
378
379   /* init state */
380   gst_base_audio_encoder_reset (enc, TRUE);
381   GST_DEBUG_OBJECT (enc, "init ok");
382 }
383
384 static void
385 gst_base_audio_encoder_reset (GstBaseAudioEncoder * enc, gboolean full)
386 {
387   GST_OBJECT_LOCK (enc);
388
389   if (full) {
390     enc->priv->active = FALSE;
391     enc->priv->samples_in = 0;
392     enc->priv->bytes_out = 0;
393     g_free (enc->ctx->state.channel_pos);
394     memset (enc->ctx, 0, sizeof (enc->ctx));
395   }
396
397   gst_segment_init (&enc->segment, GST_FORMAT_TIME);
398
399   gst_adapter_clear (enc->priv->adapter);
400   enc->priv->got_data = FALSE;
401   enc->priv->drained = TRUE;
402   enc->priv->offset = 0;
403   enc->priv->base_ts = GST_CLOCK_TIME_NONE;
404   enc->priv->base_gp = -1;
405   enc->priv->samples = 0;
406   enc->priv->discont = FALSE;
407
408   GST_OBJECT_UNLOCK (enc);
409 }
410
411 static void
412 gst_base_audio_encoder_finalize (GObject * object)
413 {
414   GstBaseAudioEncoder *enc = GST_BASE_AUDIO_ENCODER (object);
415
416   g_object_unref (enc->priv->adapter);
417
418   G_OBJECT_CLASS (parent_class)->finalize (object);
419 }
420
421 /**
422  * gst_base_audio_encoder_finish_frame:
423  * @enc: a #GstBaseAudioEncoder
424  * @buffer: encoded data
425  * @samples: number of samples (per channel) represented by encoded data
426  *
427  * Collects encoded data and/or pushes encoded data downstream.
428  * Source pad caps must be set when this is called.  Depending on the nature
429  * of the (framing of) the format, subclass can decide whether to push
430  * encoded data directly or to collect various "frames" in a single buffer.
431  * Note that the latter behaviour is recommended whenever the format is allowed,
432  * as it incurs no additional latency and avoids otherwise generating a
433  * a multitude of (small) output buffers.  If not explicitly pushed,
434  * any available encoded data is pushed at the end of each processing cycle,
435  * i.e. which encodes as much data as available input data allows.
436  *
437  * If @samples < 0, then best estimate is all samples provided to encoder
438  * (subclass) so far.  @buf may be NULL, in which case next number of @samples
439  * are considered discarded, e.g. as a result of discontinuous transmission,
440  * and a discontinuity is marked (note that @buf == NULL => push == TRUE).
441  *
442  * Returns: a #GstFlowReturn that should be escalated to caller (of caller)
443  */
444 GstFlowReturn
445 gst_base_audio_encoder_finish_frame (GstBaseAudioEncoder * enc, GstBuffer * buf,
446     gint samples)
447 {
448   GstBaseAudioEncoderClass *klass;
449   GstBaseAudioEncoderPrivate *priv;
450   GstBaseAudioEncoderContext *ctx;
451   GstFlowReturn ret = GST_FLOW_OK;
452
453   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
454   priv = enc->priv;
455   ctx = enc->ctx;
456
457   /* subclass should know what it is producing by now */
458   g_return_val_if_fail (GST_PAD_CAPS (enc->srcpad) != NULL, GST_FLOW_ERROR);
459   /* subclass should not hand us no data */
460   g_return_val_if_fail (buf == NULL || GST_BUFFER_SIZE (buf) > 0,
461       GST_FLOW_ERROR);
462
463   GST_LOG_OBJECT (enc, "accepting %d bytes encoded data as %d samples",
464       buf ? GST_BUFFER_SIZE (buf) : -1, samples);
465
466   /* mark subclass still alive and providing */
467   priv->got_data = TRUE;
468
469   /* remove corresponding samples from input */
470   if (samples < 0)
471     samples = (enc->priv->offset / ctx->state.bpf);
472
473   if (G_LIKELY (samples)) {
474     /* track upstream ts if so configured */
475     if (!enc->perfect_ts) {
476       guint64 ts, distance;
477
478       ts = gst_adapter_prev_timestamp (priv->adapter, &distance);
479       g_assert (distance % ctx->state.bpf == 0);
480       distance /= ctx->state.bpf;
481       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past prev_ts %"
482           GST_TIME_FORMAT, distance, GST_TIME_ARGS (ts));
483       GST_LOG_OBJECT (enc, "%" G_GUINT64_FORMAT " samples past base_ts %"
484           GST_TIME_FORMAT, priv->samples, GST_TIME_ARGS (priv->base_ts));
485       /* when draining adapter might be empty and no ts to offer */
486       if (GST_CLOCK_TIME_IS_VALID (ts) && ts != priv->base_ts) {
487         GstClockTimeDiff diff;
488         GstClockTime old_ts, next_ts;
489
490         /* passed into another buffer;
491          * mild check for discontinuity and only mark if so */
492         next_ts = ts +
493             gst_util_uint64_scale (distance, GST_SECOND, ctx->state.rate);
494         old_ts = priv->base_ts +
495             gst_util_uint64_scale (priv->samples, GST_SECOND, ctx->state.rate);
496         diff = GST_CLOCK_DIFF (next_ts, old_ts);
497         GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
498         /* only mark discontinuity if beyond tolerance */
499         if (G_UNLIKELY (diff < -enc->tolerance || diff > enc->tolerance)) {
500           GST_DEBUG_OBJECT (enc, "marked discont");
501           priv->discont = TRUE;
502         }
503         GST_LOG_OBJECT (enc, "new upstream ts %" GST_TIME_FORMAT
504             " at distance %" G_GUINT64_FORMAT, GST_TIME_ARGS (ts), distance);
505         /* re-sync to upstream ts */
506         priv->base_ts = ts;
507         priv->samples = distance;
508       }
509     }
510     /* advance sample view */
511     if (G_UNLIKELY (samples * ctx->state.bpf > priv->offset)) {
512       if (G_LIKELY (!priv->force)) {
513         /* no way we can let this pass */
514         g_assert_not_reached ();
515         /* really no way */
516         goto overflow;
517       } else {
518         priv->offset = 0;
519         if (samples * ctx->state.bpf >= gst_adapter_available (priv->adapter))
520           gst_adapter_clear (priv->adapter);
521         else
522           gst_adapter_flush (priv->adapter, samples * ctx->state.bpf);
523       }
524     } else {
525       gst_adapter_flush (priv->adapter, samples * ctx->state.bpf);
526       priv->offset -= samples * ctx->state.bpf;
527       /* avoid subsequent stray prev_ts */
528       if (G_UNLIKELY (gst_adapter_available (priv->adapter) == 0))
529         gst_adapter_clear (priv->adapter);
530     }
531     /* sample count advanced below after buffer handling */
532   }
533
534   /* collect output */
535   if (G_LIKELY (buf)) {
536     GST_LOG_OBJECT (enc, "taking %d bytes for output", GST_BUFFER_SIZE (buf));
537     buf = gst_buffer_make_metadata_writable (buf);
538
539     /* decorate */
540     gst_buffer_set_caps (buf, GST_PAD_CAPS (enc->srcpad));
541     if (G_LIKELY (GST_CLOCK_TIME_IS_VALID (priv->base_ts))) {
542       /* FIXME ? lookahead could lead to weird ts and duration ?
543        * (particularly if not in perfect mode) */
544       /* mind sample rounding and produce perfect output */
545       GST_BUFFER_TIMESTAMP (buf) = priv->base_ts +
546           gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
547           ctx->state.rate);
548       GST_DEBUG_OBJECT (enc, "out samples %d", samples);
549       if (G_LIKELY (samples > 0)) {
550         priv->samples += samples;
551         GST_BUFFER_DURATION (buf) = priv->base_ts +
552             gst_util_uint64_scale (priv->samples - ctx->lookahead, GST_SECOND,
553             ctx->state.rate) - GST_BUFFER_TIMESTAMP (buf);
554         priv->last_duration = GST_BUFFER_DURATION (buf);
555       } else {
556         /* duration forecast in case of handling remainder;
557          * the last one is probably like the previous one ... */
558         GST_BUFFER_DURATION (buf) = priv->last_duration;
559       }
560       if (priv->base_gp >= 0) {
561         /* pamper oggmux */
562         /* FIXME: in longer run, muxer should take care of this ... */
563         /* offset_end = granulepos for ogg muxer */
564         GST_BUFFER_OFFSET_END (buf) = priv->base_gp + priv->samples -
565             enc->ctx->lookahead;
566         /* offset = timestamp corresponding to granulepos for ogg muxer */
567         GST_BUFFER_OFFSET (buf) =
568             GST_FRAMES_TO_CLOCK_TIME (GST_BUFFER_OFFSET_END (buf),
569             ctx->state.rate);
570       } else {
571         GST_BUFFER_OFFSET (buf) = priv->bytes_out;
572         GST_BUFFER_OFFSET_END (buf) = priv->bytes_out + GST_BUFFER_SIZE (buf);
573       }
574     }
575
576     priv->bytes_out += GST_BUFFER_SIZE (buf);
577
578     if (G_UNLIKELY (priv->discont)) {
579       GST_LOG_OBJECT (enc, "marking discont");
580       GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
581       priv->discont = FALSE;
582     }
583
584     if (klass->pre_push) {
585       /* last chance for subclass to do some dirty stuff */
586       ret = klass->pre_push (enc, &buf);
587       if (ret != GST_FLOW_OK || !buf) {
588         GST_DEBUG_OBJECT (enc, "subclass returned %s, buf %p",
589             gst_flow_get_name (ret), buf);
590         if (buf)
591           gst_buffer_unref (buf);
592         goto exit;
593       }
594     }
595
596     GST_LOG_OBJECT (enc, "pushing buffer of size %d with ts %" GST_TIME_FORMAT
597         ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buf),
598         GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)),
599         GST_TIME_ARGS (GST_BUFFER_DURATION (buf)));
600
601     ret = gst_pad_push (enc->srcpad, buf);
602     GST_LOG_OBJECT (enc, "buffer pushed: %s", gst_flow_get_name (ret));
603   } else {
604     /* merely advance samples, most work for that already done above */
605     priv->samples += samples;
606   }
607
608 exit:
609   return ret;
610
611   /* ERRORS */
612 overflow:
613   {
614     GST_ELEMENT_ERROR (enc, STREAM, ENCODE,
615         ("received more encoded samples %d than provided %d",
616             samples, priv->offset / ctx->state.bpf), (NULL));
617     if (buf)
618       gst_buffer_unref (buf);
619     return GST_FLOW_ERROR;
620   }
621 }
622
623  /* adapter tracking idea:
624   * - start of adapter corresponds with what has already been encoded
625   * (i.e. really returned by encoder subclass)
626   * - start + offset is what needs to be fed to subclass next */
627 static GstFlowReturn
628 gst_base_audio_encoder_push_buffers (GstBaseAudioEncoder * enc, gboolean force)
629 {
630   GstBaseAudioEncoderClass *klass;
631   GstBaseAudioEncoderPrivate *priv;
632   GstBaseAudioEncoderContext *ctx;
633   gint av, need;
634   GstBuffer *buf;
635   GstFlowReturn ret = GST_FLOW_OK;
636
637   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
638
639   g_return_val_if_fail (klass->handle_frame != NULL, GST_FLOW_ERROR);
640
641   priv = enc->priv;
642   ctx = enc->ctx;
643
644   while (ret == GST_FLOW_OK) {
645
646     buf = NULL;
647     av = gst_adapter_available (priv->adapter);
648
649     g_assert (priv->offset <= av);
650     av -= priv->offset;
651
652     need = ctx->frame_samples > 0 ? ctx->frame_samples * ctx->state.bpf : av;
653     GST_LOG_OBJECT (enc, "available: %d, needed: %d, force: %d",
654         av, need, force);
655
656     if ((need > av) || !av) {
657       if (G_UNLIKELY (force)) {
658         priv->force = TRUE;
659         need = av;
660       } else {
661         break;
662       }
663     } else {
664       priv->force = FALSE;
665     }
666
667     /* if we have some extra metadata,
668      * provide for integer multiple of frames to allow for better granularity
669      * of processing */
670     if (ctx->frame_samples > 0 && need) {
671       if (ctx->frame_max > 1)
672         need = need * MIN ((av / need), ctx->frame_max);
673       else if (ctx->frame_max == 0)
674         need = need * (av / need);
675     }
676
677     if (need) {
678       buf = gst_buffer_new ();
679       GST_BUFFER_DATA (buf) = (guint8 *)
680           gst_adapter_peek (priv->adapter, priv->offset + need) + priv->offset;
681       GST_BUFFER_SIZE (buf) = need;
682     }
683
684     GST_LOG_OBJECT (enc, "providing subclass with %d bytes at offset %d",
685         need, priv->offset);
686
687     /* mark this already as consumed,
688      * which it should be when subclass gives us data in exchange for samples */
689     priv->offset += need;
690     priv->samples_in += need / ctx->state.bpf;
691
692     priv->got_data = FALSE;
693     ret = klass->handle_frame (enc, buf);
694
695     if (G_LIKELY (buf))
696       gst_buffer_unref (buf);
697
698     /* no data to feed, no leftover provided, then bail out */
699     if (G_UNLIKELY (!buf && !priv->got_data)) {
700       priv->drained = TRUE;
701       GST_LOG_OBJECT (enc, "no more data drained from subclass");
702       break;
703     }
704   }
705
706   return ret;
707 }
708
709 static GstFlowReturn
710 gst_base_audio_encoder_drain (GstBaseAudioEncoder * enc)
711 {
712   if (enc->priv->drained)
713     return GST_FLOW_OK;
714   else
715     return gst_base_audio_encoder_push_buffers (enc, TRUE);
716 }
717
718 static void
719 gst_base_audio_encoder_set_base_gp (GstBaseAudioEncoder * enc)
720 {
721   GstClockTime ts;
722
723   if (!enc->granule)
724     return;
725
726   /* use running time for granule */
727   /* incoming data is clipped, so a valid input should yield a valid output */
728   ts = gst_segment_to_running_time (&enc->segment, GST_FORMAT_TIME,
729       enc->priv->base_ts);
730   if (GST_CLOCK_TIME_IS_VALID (ts)) {
731     enc->priv->base_gp =
732         GST_CLOCK_TIME_TO_FRAMES (enc->priv->base_ts, enc->ctx->state.rate);
733     GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT, enc->priv->base_gp);
734   } else {
735     /* should reasonably have a valid base,
736      * otherwise start at 0 if we did not already start there earlier */
737     if (enc->priv->base_gp < 0) {
738       enc->priv->base_gp = 0;
739       GST_DEBUG_OBJECT (enc, "new base gp %" G_GINT64_FORMAT,
740           enc->priv->base_gp);
741     }
742   }
743 }
744
745 static GstFlowReturn
746 gst_base_audio_encoder_chain (GstPad * pad, GstBuffer * buffer)
747 {
748   GstBaseAudioEncoderClass *bclass;
749   GstBaseAudioEncoder *enc;
750   GstBaseAudioEncoderPrivate *priv;
751   GstBaseAudioEncoderContext *ctx;
752   GstFlowReturn ret = GST_FLOW_OK;
753   gboolean discont;
754
755   enc = GST_BASE_AUDIO_ENCODER (GST_OBJECT_PARENT (pad));
756   bclass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
757
758   priv = enc->priv;
759   ctx = enc->ctx;
760
761   /* should know what is coming by now */
762   if (!ctx->state.bpf)
763     goto not_negotiated;
764
765   GST_LOG_OBJECT (enc,
766       "received buffer of size %d with ts %" GST_TIME_FORMAT
767       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
768       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
769       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
770
771   /* input shoud be whole number of sample frames */
772   if (GST_BUFFER_SIZE (buffer) % ctx->state.bpf)
773     goto wrong_buffer;
774
775 #ifndef GST_DISABLE_GST_DEBUG
776   {
777     GstClockTime duration;
778     GstClockTimeDiff diff;
779
780     /* verify buffer duration */
781     duration = gst_util_uint64_scale (GST_BUFFER_SIZE (buffer), GST_SECOND,
782         ctx->state.rate * ctx->state.bpf);
783     diff = GST_CLOCK_DIFF (duration, GST_BUFFER_DURATION (buffer));
784     if (GST_BUFFER_DURATION (buffer) != GST_CLOCK_TIME_NONE &&
785         (diff > GST_SECOND / ctx->state.rate / 2 ||
786             diff < -GST_SECOND / ctx->state.rate / 2)) {
787       GST_DEBUG_OBJECT (enc, "incoming buffer had incorrect duration %"
788           GST_TIME_FORMAT ", expected duration %" GST_TIME_FORMAT,
789           GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)),
790           GST_TIME_ARGS (duration));
791     }
792   }
793 #endif
794
795   discont = GST_BUFFER_FLAG_IS_SET (buffer, GST_BUFFER_FLAG_DISCONT);
796   if (G_UNLIKELY (discont)) {
797     GST_LOG_OBJECT (buffer, "marked discont");
798     enc->priv->discont = discont;
799   }
800
801   /* clip to segment */
802   /* NOTE: slightly painful linking -laudio only for this one ... */
803   buffer = gst_audio_buffer_clip (buffer, &enc->segment, ctx->state.rate,
804       ctx->state.bpf);
805   if (G_UNLIKELY (!buffer)) {
806     GST_DEBUG_OBJECT (buffer, "no data after clipping to segment");
807     goto done;
808   }
809
810   GST_LOG_OBJECT (enc,
811       "buffer after segment clipping has size %d with ts %" GST_TIME_FORMAT
812       ", duration %" GST_TIME_FORMAT, GST_BUFFER_SIZE (buffer),
813       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buffer)),
814       GST_TIME_ARGS (GST_BUFFER_DURATION (buffer)));
815
816   if (!GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
817     priv->base_ts = GST_BUFFER_TIMESTAMP (buffer);
818     GST_DEBUG_OBJECT (enc, "new base ts %" GST_TIME_FORMAT,
819         GST_TIME_ARGS (priv->base_ts));
820     gst_base_audio_encoder_set_base_gp (enc);
821   }
822
823   /* check for continuity;
824    * checked elsewhere in non-perfect case */
825   if (enc->perfect_ts) {
826     GstClockTimeDiff diff = 0;
827     GstClockTime next_ts = 0;
828
829     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer) &&
830         GST_CLOCK_TIME_IS_VALID (priv->base_ts)) {
831       guint64 samples;
832
833       samples = priv->samples +
834           gst_adapter_available (priv->adapter) / ctx->state.bpf;
835       next_ts = priv->base_ts +
836           gst_util_uint64_scale (samples, GST_SECOND, ctx->state.rate);
837       GST_LOG_OBJECT (enc, "buffer is %" G_GUINT64_FORMAT
838           " samples past base_ts %" GST_TIME_FORMAT
839           ", expected ts %" GST_TIME_FORMAT, samples,
840           GST_TIME_ARGS (priv->base_ts), GST_TIME_ARGS (next_ts));
841       diff = GST_CLOCK_DIFF (next_ts, GST_BUFFER_TIMESTAMP (buffer));
842       GST_LOG_OBJECT (enc, "ts diff %d ms", (gint) (diff / GST_MSECOND));
843       /* if within tolerance,
844        * discard buffer ts and carry on producing perfect stream,
845        * otherwise clip or resync to ts */
846       if (G_UNLIKELY (diff < -enc->tolerance || diff > enc->tolerance)) {
847         GST_DEBUG_OBJECT (enc, "marked discont");
848         discont = TRUE;
849       }
850     }
851
852     /* do some fancy tweaking in hard resync case */
853     if (discont && enc->hard_resync) {
854       if (diff < 0) {
855         guint64 diff_bytes;
856
857         GST_WARNING_OBJECT (enc, "Buffer is older than expected ts %"
858             GST_TIME_FORMAT ".  Clipping buffer", GST_TIME_ARGS (next_ts));
859
860         diff_bytes =
861             GST_CLOCK_TIME_TO_FRAMES (-diff, ctx->state.rate) * ctx->state.bpf;
862         if (diff_bytes >= GST_BUFFER_SIZE (buffer)) {
863           gst_buffer_unref (buffer);
864           goto done;
865         }
866         buffer = gst_buffer_make_metadata_writable (buffer);
867         GST_BUFFER_DATA (buffer) += diff_bytes;
868         GST_BUFFER_SIZE (buffer) -= diff_bytes;
869
870         GST_BUFFER_TIMESTAMP (buffer) += diff;
871         /* care even less about duration after this */
872       } else {
873         /* drain stuff prior to resync */
874         gst_base_audio_encoder_drain (enc);
875       }
876     }
877     /* now re-sync ts */
878     priv->base_ts += diff;
879     gst_base_audio_encoder_set_base_gp (enc);
880     priv->discont |= discont;
881   }
882
883   gst_adapter_push (enc->priv->adapter, buffer);
884   /* new stuff, so we can push subclass again */
885   enc->priv->drained = FALSE;
886
887   ret = gst_base_audio_encoder_push_buffers (enc, FALSE);
888
889 done:
890   GST_LOG_OBJECT (enc, "chain leaving");
891   return ret;
892
893   /* ERRORS */
894 not_negotiated:
895   {
896     GST_ELEMENT_ERROR (enc, CORE, NEGOTIATION, (NULL),
897         ("encoder not initialized"));
898     gst_buffer_unref (buffer);
899     return GST_FLOW_NOT_NEGOTIATED;
900   }
901 wrong_buffer:
902   {
903     GST_ELEMENT_ERROR (enc, STREAM, ENCODE, (NULL),
904         ("buffer size %d not a multiple of %d", GST_BUFFER_SIZE (buffer),
905             ctx->state.bpf));
906     gst_buffer_unref (buffer);
907     return GST_FLOW_ERROR;
908   }
909 }
910
911 static gboolean
912 gst_base_audio_encoder_sink_setcaps (GstPad * pad, GstCaps * caps)
913 {
914   GstBaseAudioEncoder *enc;
915   GstBaseAudioEncoderClass *klass;
916   GstBaseAudioEncoderContext *ctx;
917   GstAudioState *state;
918   gboolean res = TRUE, changed = FALSE;
919
920   enc = GST_BASE_AUDIO_ENCODER (GST_PAD_PARENT (pad));
921   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
922
923   /* subclass must do something here ... */
924   g_return_val_if_fail (klass->set_format != NULL, FALSE);
925
926   ctx = enc->ctx;
927   state = &ctx->state;
928
929   GST_DEBUG_OBJECT (enc, "caps: %" GST_PTR_FORMAT, caps);
930
931   if (!gst_caps_is_fixed (caps))
932     goto refuse_caps;
933
934   /* adjust ts tracking to new sample rate */
935   if (GST_CLOCK_TIME_IS_VALID (enc->priv->base_ts) && state->rate) {
936     enc->priv->base_ts +=
937         GST_FRAMES_TO_CLOCK_TIME (enc->priv->samples, state->rate);
938     enc->priv->samples = 0;
939   }
940
941   if (!gst_base_audio_parse_caps (caps, state, &changed))
942     goto refuse_caps;
943
944   if (changed) {
945     GstClockTime old_min_latency;
946     GstClockTime old_max_latency;
947
948     /* drain any pending old data stuff */
949     gst_base_audio_encoder_drain (enc);
950
951     /* context defaults */
952     enc->ctx->frame_samples = 0;
953     enc->ctx->frame_max = 0;
954     enc->ctx->lookahead = 0;
955
956     /* element might report latency */
957     GST_OBJECT_LOCK (enc);
958     old_min_latency = ctx->min_latency;
959     old_max_latency = ctx->max_latency;
960     GST_OBJECT_UNLOCK (enc);
961
962     if (klass->set_format)
963       res = klass->set_format (enc, state);
964
965     /* notify if new latency */
966     GST_OBJECT_LOCK (enc);
967     if ((ctx->min_latency > 0 && ctx->min_latency != old_min_latency) ||
968         (ctx->max_latency > 0 && ctx->max_latency != old_max_latency)) {
969       GST_OBJECT_UNLOCK (enc);
970       /* post latency message on the bus */
971       gst_element_post_message (GST_ELEMENT (enc),
972           gst_message_new_latency (GST_OBJECT (enc)));
973       GST_OBJECT_LOCK (enc);
974     }
975     GST_OBJECT_UNLOCK (enc);
976   } else {
977     GST_DEBUG_OBJECT (enc, "new audio format identical to configured format");
978   }
979
980   return res;
981
982   /* ERRORS */
983 refuse_caps:
984   {
985     GST_WARNING_OBJECT (enc, "rejected caps %" GST_PTR_FORMAT, caps);
986     return res;
987   }
988 }
989
990
991 /**
992  * gst_base_audio_encoder_proxy_getcaps:
993  * @enc: a #GstBaseAudioEncoder
994  * @caps: initial
995  *
996  * Returns caps that express @caps (or sink template caps if @caps == NULL)
997  * restricted to channel/rate combinations supported by downstream elements
998  * (e.g. muxers).
999  *
1000  * Returns: a #GstCaps owned by caller
1001  */
1002 GstCaps *
1003 gst_base_audio_encoder_proxy_getcaps (GstBaseAudioEncoder * enc, GstCaps * caps)
1004 {
1005   const GstCaps *templ_caps;
1006   GstCaps *allowed = NULL;
1007   GstCaps *fcaps, *filter_caps;
1008   gint i, j;
1009
1010   /* we want to be able to communicate to upstream elements like audioconvert
1011    * and audioresample any rate/channel restrictions downstream (e.g. muxer
1012    * only accepting certain sample rates) */
1013   templ_caps = caps ? caps : gst_pad_get_pad_template_caps (enc->sinkpad);
1014   allowed = gst_pad_get_allowed_caps (enc->srcpad);
1015   if (!allowed || gst_caps_is_empty (allowed) || gst_caps_is_any (allowed)) {
1016     fcaps = gst_caps_copy (templ_caps);
1017     goto done;
1018   }
1019
1020   GST_LOG_OBJECT (enc, "template caps %" GST_PTR_FORMAT, templ_caps);
1021   GST_LOG_OBJECT (enc, "allowed caps %" GST_PTR_FORMAT, allowed);
1022
1023   filter_caps = gst_caps_new_empty ();
1024
1025   for (i = 0; i < gst_caps_get_size (templ_caps); i++) {
1026     GQuark q_name;
1027
1028     q_name = gst_structure_get_name_id (gst_caps_get_structure (templ_caps, i));
1029
1030     /* pick rate + channel fields from allowed caps */
1031     for (j = 0; j < gst_caps_get_size (allowed); j++) {
1032       const GstStructure *allowed_s = gst_caps_get_structure (allowed, j);
1033       const GValue *val;
1034       GstStructure *s;
1035
1036       s = gst_structure_id_empty_new (q_name);
1037       if ((val = gst_structure_get_value (allowed_s, "rate")))
1038         gst_structure_set_value (s, "rate", val);
1039       if ((val = gst_structure_get_value (allowed_s, "channels")))
1040         gst_structure_set_value (s, "channels", val);
1041
1042       gst_caps_merge_structure (filter_caps, s);
1043     }
1044   }
1045
1046   fcaps = gst_caps_intersect (filter_caps, templ_caps);
1047   gst_caps_unref (filter_caps);
1048
1049 done:
1050   gst_caps_replace (&allowed, NULL);
1051
1052   GST_LOG_OBJECT (enc, "proxy caps %" GST_PTR_FORMAT, fcaps);
1053
1054   return fcaps;
1055 }
1056
1057 static GstCaps *
1058 gst_base_audio_encoder_sink_getcaps (GstPad * pad)
1059 {
1060   GstBaseAudioEncoder *enc;
1061   GstBaseAudioEncoderClass *klass;
1062   GstCaps *caps;
1063
1064   enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad));
1065   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
1066   g_assert (pad == enc->sinkpad);
1067
1068   if (klass->getcaps)
1069     caps = klass->getcaps (enc);
1070   else
1071     caps = gst_base_audio_encoder_proxy_getcaps (enc, NULL);
1072   gst_object_unref (enc);
1073
1074   GST_LOG_OBJECT (enc, "returning caps %" GST_PTR_FORMAT, caps);
1075
1076   return caps;
1077 }
1078
1079 static gboolean
1080 gst_base_audio_encoder_sink_eventfunc (GstBaseAudioEncoder * enc,
1081     GstEvent * event)
1082 {
1083   GstBaseAudioEncoderClass *klass;
1084   gboolean handled = FALSE;
1085
1086   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
1087
1088   switch (GST_EVENT_TYPE (event)) {
1089     case GST_EVENT_NEWSEGMENT:
1090     {
1091       GstFormat format;
1092       gdouble rate, arate;
1093       gint64 start, stop, time;
1094       gboolean update;
1095
1096       gst_event_parse_new_segment_full (event, &update, &rate, &arate, &format,
1097           &start, &stop, &time);
1098
1099       if (format == GST_FORMAT_TIME) {
1100         GST_DEBUG_OBJECT (enc, "received TIME NEW_SEGMENT %" GST_TIME_FORMAT
1101             " -- %" GST_TIME_FORMAT ", time %" GST_TIME_FORMAT
1102             ", rate %g, applied_rate %g",
1103             GST_TIME_ARGS (start), GST_TIME_ARGS (stop), GST_TIME_ARGS (time),
1104             rate, arate);
1105       } else {
1106         GST_DEBUG_OBJECT (enc, "received NEW_SEGMENT %" G_GINT64_FORMAT
1107             " -- %" G_GINT64_FORMAT ", time %" G_GINT64_FORMAT
1108             ", rate %g, applied_rate %g", start, stop, time, rate, arate);
1109         GST_DEBUG_OBJECT (enc, "unsupported format; ignoring");
1110         break;
1111       }
1112
1113       /* finish current segment */
1114       gst_base_audio_encoder_drain (enc);
1115       /* reset partially for new segment */
1116       gst_base_audio_encoder_reset (enc, FALSE);
1117       /* and follow along with segment */
1118       gst_segment_set_newsegment_full (&enc->segment, update, rate, arate,
1119           format, start, stop, time);
1120       break;
1121     }
1122
1123     case GST_EVENT_FLUSH_START:
1124       break;
1125
1126     case GST_EVENT_FLUSH_STOP:
1127       /* discard any pending stuff */
1128       /* TODO route through drain ?? */
1129       if (!enc->priv->drained && klass->flush)
1130         klass->flush (enc);
1131       /* and get (re)set for the sequel */
1132       gst_base_audio_encoder_reset (enc, FALSE);
1133       break;
1134
1135     case GST_EVENT_EOS:
1136       gst_base_audio_encoder_drain (enc);
1137       break;
1138
1139     default:
1140       break;
1141   }
1142
1143   return handled;
1144 }
1145
1146 static gboolean
1147 gst_base_audio_encoder_sink_event (GstPad * pad, GstEvent * event)
1148 {
1149   GstBaseAudioEncoder *enc;
1150   GstBaseAudioEncoderClass *klass;
1151   gboolean handled = FALSE;
1152   gboolean ret = TRUE;
1153
1154   enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad));
1155   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
1156
1157   GST_DEBUG_OBJECT (enc, "received event %d, %s", GST_EVENT_TYPE (event),
1158       GST_EVENT_TYPE_NAME (event));
1159
1160   if (klass->event)
1161     handled = klass->event (enc, event);
1162
1163   if (!handled)
1164     handled = gst_base_audio_encoder_sink_eventfunc (enc, event);
1165
1166   if (!handled)
1167     ret = gst_pad_event_default (pad, event);
1168
1169   GST_DEBUG_OBJECT (enc, "event handled");
1170
1171   gst_object_unref (enc);
1172   return ret;
1173 }
1174
1175 static gboolean
1176 gst_base_audio_encoder_sink_query (GstPad * pad, GstQuery * query)
1177 {
1178   gboolean res = TRUE;
1179   GstBaseAudioEncoder *enc;
1180
1181   enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad));
1182
1183   switch (GST_QUERY_TYPE (query)) {
1184     case GST_QUERY_FORMATS:
1185     {
1186       gst_query_set_formats (query, 3,
1187           GST_FORMAT_TIME, GST_FORMAT_BYTES, GST_FORMAT_DEFAULT);
1188       res = TRUE;
1189       break;
1190     }
1191     case GST_QUERY_CONVERT:
1192     {
1193       GstFormat src_fmt, dest_fmt;
1194       gint64 src_val, dest_val;
1195
1196       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1197       if (!(res = gst_base_audio_raw_audio_convert (&enc->ctx->state,
1198                   src_fmt, src_val, &dest_fmt, &dest_val)))
1199         goto error;
1200       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1201       break;
1202     }
1203     default:
1204       res = gst_pad_query_default (pad, query);
1205       break;
1206   }
1207
1208 error:
1209   gst_object_unref (enc);
1210   return res;
1211 }
1212
1213 static const GstQueryType *
1214 gst_base_audio_encoder_get_query_types (GstPad * pad)
1215 {
1216   static const GstQueryType gst_base_audio_encoder_src_query_types[] = {
1217     GST_QUERY_POSITION,
1218     GST_QUERY_DURATION,
1219     GST_QUERY_CONVERT,
1220     GST_QUERY_LATENCY,
1221     0
1222   };
1223
1224   return gst_base_audio_encoder_src_query_types;
1225 }
1226
1227 /* FIXME ? are any of these queries (other than latency) an encoder's business
1228  * also, the conversion stuff might seem to make sense, but seems to not mind
1229  * segment stuff etc at all
1230  * Supposedly that's backward compatibility ... */
1231 static gboolean
1232 gst_base_audio_encoder_src_query (GstPad * pad, GstQuery * query)
1233 {
1234   GstBaseAudioEncoder *enc;
1235   GstPad *peerpad;
1236   gboolean res = FALSE;
1237
1238   enc = GST_BASE_AUDIO_ENCODER (GST_PAD_PARENT (pad));
1239   peerpad = gst_pad_get_peer (GST_PAD (enc->sinkpad));
1240
1241   GST_LOG_OBJECT (enc, "handling query: %" GST_PTR_FORMAT, query);
1242
1243   switch (GST_QUERY_TYPE (query)) {
1244     case GST_QUERY_POSITION:
1245     {
1246       GstFormat fmt, req_fmt;
1247       gint64 pos, val;
1248
1249       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1250         GST_LOG_OBJECT (enc, "returning peer response");
1251         break;
1252       }
1253
1254       if (!peerpad) {
1255         GST_LOG_OBJECT (enc, "no peer");
1256         break;
1257       }
1258
1259       gst_query_parse_position (query, &req_fmt, NULL);
1260       fmt = GST_FORMAT_TIME;
1261       if (!(res = gst_pad_query_position (peerpad, &fmt, &pos)))
1262         break;
1263
1264       if ((res = gst_pad_query_convert (peerpad, fmt, pos, &req_fmt, &val))) {
1265         gst_query_set_position (query, req_fmt, val);
1266       }
1267       break;
1268     }
1269     case GST_QUERY_DURATION:
1270     {
1271       GstFormat fmt, req_fmt;
1272       gint64 dur, val;
1273
1274       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1275         GST_LOG_OBJECT (enc, "returning peer response");
1276         break;
1277       }
1278
1279       if (!peerpad) {
1280         GST_LOG_OBJECT (enc, "no peer");
1281         break;
1282       }
1283
1284       gst_query_parse_duration (query, &req_fmt, NULL);
1285       fmt = GST_FORMAT_TIME;
1286       if (!(res = gst_pad_query_duration (peerpad, &fmt, &dur)))
1287         break;
1288
1289       if ((res = gst_pad_query_convert (peerpad, fmt, dur, &req_fmt, &val))) {
1290         gst_query_set_duration (query, req_fmt, val);
1291       }
1292       break;
1293     }
1294     case GST_QUERY_FORMATS:
1295     {
1296       gst_query_set_formats (query, 2, GST_FORMAT_TIME, GST_FORMAT_BYTES);
1297       res = TRUE;
1298       break;
1299     }
1300     case GST_QUERY_CONVERT:
1301     {
1302       GstFormat src_fmt, dest_fmt;
1303       gint64 src_val, dest_val;
1304
1305       gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, &dest_val);
1306       if (!(res = gst_base_audio_encoded_audio_convert (&enc->ctx->state,
1307                   enc->priv->bytes_out, enc->priv->samples_in, src_fmt, src_val,
1308                   &dest_fmt, &dest_val)))
1309         break;
1310       gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
1311       break;
1312     }
1313     case GST_QUERY_LATENCY:
1314     {
1315       if ((res = gst_pad_peer_query (enc->sinkpad, query))) {
1316         gboolean live;
1317         GstClockTime min_latency, max_latency;
1318
1319         gst_query_parse_latency (query, &live, &min_latency, &max_latency);
1320         GST_DEBUG_OBJECT (enc, "Peer latency: live %d, min %"
1321             GST_TIME_FORMAT " max %" GST_TIME_FORMAT, live,
1322             GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
1323
1324         GST_OBJECT_LOCK (enc);
1325         /* add our latency */
1326         if (min_latency != -1)
1327           min_latency += enc->ctx->min_latency;
1328         if (max_latency != -1)
1329           max_latency += enc->ctx->max_latency;
1330         GST_OBJECT_UNLOCK (enc);
1331
1332         gst_query_set_latency (query, live, min_latency, max_latency);
1333       }
1334       break;
1335     }
1336     default:
1337       res = gst_pad_query_default (pad, query);
1338       break;
1339   }
1340
1341   gst_object_unref (peerpad);
1342   return res;
1343 }
1344
1345 static void
1346 gst_base_audio_encoder_set_property (GObject * object, guint prop_id,
1347     const GValue * value, GParamSpec * pspec)
1348 {
1349   GstBaseAudioEncoder *enc;
1350
1351   enc = GST_BASE_AUDIO_ENCODER (object);
1352
1353   switch (prop_id) {
1354     case PROP_PERFECT_TS:
1355       if (enc->granule && !g_value_get_boolean (value))
1356         GST_WARNING_OBJECT (enc, "perfect-ts can not be set FALSE");
1357       else
1358         enc->perfect_ts = g_value_get_boolean (value);
1359       break;
1360     case PROP_HARD_RESYNC:
1361       enc->hard_resync = g_value_get_boolean (value);
1362       break;
1363     case PROP_TOLERANCE:
1364       enc->tolerance = g_value_get_int64 (value);
1365       break;
1366     default:
1367       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1368       break;
1369   }
1370 }
1371
1372 static void
1373 gst_base_audio_encoder_get_property (GObject * object, guint prop_id,
1374     GValue * value, GParamSpec * pspec)
1375 {
1376   GstBaseAudioEncoder *enc;
1377
1378   enc = GST_BASE_AUDIO_ENCODER (object);
1379
1380   switch (prop_id) {
1381     case PROP_PERFECT_TS:
1382       g_value_set_boolean (value, enc->perfect_ts);
1383       break;
1384     case PROP_GRANULE:
1385       g_value_set_boolean (value, enc->granule);
1386       break;
1387     case PROP_HARD_RESYNC:
1388       g_value_set_boolean (value, enc->hard_resync);
1389       break;
1390     case PROP_TOLERANCE:
1391       g_value_set_int64 (value, enc->tolerance);
1392       break;
1393     default:
1394       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1395       break;
1396   }
1397 }
1398
1399 static gboolean
1400 gst_base_audio_encoder_activate (GstBaseAudioEncoder * enc, gboolean active)
1401 {
1402   GstBaseAudioEncoderClass *klass;
1403   gboolean result = FALSE;
1404
1405   klass = GST_BASE_AUDIO_ENCODER_GET_CLASS (enc);
1406
1407   g_return_val_if_fail (!enc->granule || enc->perfect_ts, FALSE);
1408
1409   GST_DEBUG_OBJECT (enc, "activate %d", active);
1410
1411   if (active) {
1412     if (!enc->priv->active && klass->start)
1413       result = klass->start (enc);
1414   } else {
1415     /* We must make sure streaming has finished before resetting things
1416      * and calling the ::stop vfunc */
1417     GST_PAD_STREAM_LOCK (enc->sinkpad);
1418     GST_PAD_STREAM_UNLOCK (enc->sinkpad);
1419
1420     if (enc->priv->active && klass->stop)
1421       result = klass->stop (enc);
1422
1423     /* clean up */
1424     gst_base_audio_encoder_reset (enc, TRUE);
1425   }
1426   GST_DEBUG_OBJECT (enc, "activate return: %d", result);
1427   return result;
1428 }
1429
1430
1431 static gboolean
1432 gst_base_audio_encoder_sink_activate_push (GstPad * pad, gboolean active)
1433 {
1434   gboolean result = TRUE;
1435   GstBaseAudioEncoder *enc;
1436
1437   enc = GST_BASE_AUDIO_ENCODER (gst_pad_get_parent (pad));
1438
1439   GST_DEBUG_OBJECT (enc, "sink activate push %d", active);
1440
1441   result = gst_base_audio_encoder_activate (enc, active);
1442
1443   if (result)
1444     enc->priv->active = active;
1445
1446   GST_DEBUG_OBJECT (enc, "sink activate push return: %d", result);
1447
1448   gst_object_unref (enc);
1449   return result;
1450 }