flacdec: improve upstream peer duration querying
[platform/upstream/gst-plugins-good.git] / ext / flac / gstflacenc.c
1 /* GStreamer
2  * Copyright (C) <1999> Erik Walthinsen <omega@cse.ogi.edu>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19 /**
20  * SECTION:element-flacenc
21  * @see_also: #GstFlacDec
22  *
23  * flacenc encodes FLAC streams.
24  * <ulink url="http://flac.sourceforge.net/">FLAC</ulink>
25  * is a Free Lossless Audio Codec.
26  *
27  * <refsect2>
28  * <title>Example launch line</title>
29  * |[
30  * gst-launch audiotestsrc num-buffers=100 ! flacenc ! filesink location=beep.flac
31  * ]|
32  * </refsect2>
33  */
34
35 /* TODO: - We currently don't handle discontinuities in the stream in a useful
36  *         way and instead rely on the developer plugging in audiorate if
37  *         the stream contains discontinuities.
38  */
39
40 #ifdef HAVE_CONFIG_H
41 #include "config.h"
42 #endif
43 #include <stdlib.h>
44 #include <string.h>
45
46 #include <gstflacenc.h>
47 #include <gst/audio/audio.h>
48 #include <gst/audio/multichannel.h>
49 #include <gst/tag/tag.h>
50 #include <gst/gsttagsetter.h>
51
52 /* Taken from http://flac.sourceforge.net/format.html#frame_header */
53 static const GstAudioChannelPosition channel_positions[8][8] = {
54   {GST_AUDIO_CHANNEL_POSITION_FRONT_MONO},
55   {GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
56       GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT}, {
57         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
58         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
59       GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER}, {
60         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
61         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
62         GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
63       GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT}, {
64         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
65         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
66         GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
67         GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
68       GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT}, {
69         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
70         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
71         GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
72         GST_AUDIO_CHANNEL_POSITION_LFE,
73         GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
74       GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT},
75   /* FIXME: 7/8 channel layouts are not defined in the FLAC specs */
76   {
77         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
78         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
79         GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
80         GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT,
81         GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
82         GST_AUDIO_CHANNEL_POSITION_LFE,
83       GST_AUDIO_CHANNEL_POSITION_REAR_CENTER}, {
84         GST_AUDIO_CHANNEL_POSITION_FRONT_LEFT,
85         GST_AUDIO_CHANNEL_POSITION_FRONT_RIGHT,
86         GST_AUDIO_CHANNEL_POSITION_REAR_LEFT,
87         GST_AUDIO_CHANNEL_POSITION_REAR_RIGHT,
88         GST_AUDIO_CHANNEL_POSITION_FRONT_CENTER,
89         GST_AUDIO_CHANNEL_POSITION_LFE,
90         GST_AUDIO_CHANNEL_POSITION_SIDE_LEFT,
91       GST_AUDIO_CHANNEL_POSITION_SIDE_RIGHT}
92 };
93
94 #define FLAC_SINK_CAPS \
95   "audio/x-raw-int, "               \
96   "endianness = (int) BYTE_ORDER, " \
97   "signed = (boolean) TRUE, "       \
98   "width = (int) 8, "               \
99   "depth = (int) 8, "               \
100   "rate = (int) [ 1, 655350 ], "    \
101   "channels = (int) [ 1, 8 ]; "     \
102   "audio/x-raw-int, "               \
103   "endianness = (int) BYTE_ORDER, " \
104   "signed = (boolean) TRUE, "       \
105   "width = (int) 16, "              \
106   "depth = (int) { 12, 16 }, "      \
107   "rate = (int) [ 1, 655350 ], "    \
108   "channels = (int) [ 1, 8 ]; "     \
109   "audio/x-raw-int, "               \
110   "endianness = (int) BYTE_ORDER, " \
111   "signed = (boolean) TRUE, "       \
112   "width = (int) 32, "              \
113   "depth = (int) { 20, 24 }, "      \
114   "rate = (int) [ 1, 655350 ], "    \
115   "channels = (int) [ 1, 8 ]"
116
117 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
118     GST_PAD_SRC,
119     GST_PAD_ALWAYS,
120     GST_STATIC_CAPS ("audio/x-flac")
121     );
122
123 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
124     GST_PAD_SINK,
125     GST_PAD_ALWAYS,
126     GST_STATIC_CAPS (FLAC_SINK_CAPS)
127     );
128
129 enum
130 {
131   PROP_0,
132   PROP_QUALITY,
133   PROP_STREAMABLE_SUBSET,
134   PROP_MID_SIDE_STEREO,
135   PROP_LOOSE_MID_SIDE_STEREO,
136   PROP_BLOCKSIZE,
137   PROP_MAX_LPC_ORDER,
138   PROP_QLP_COEFF_PRECISION,
139   PROP_QLP_COEFF_PREC_SEARCH,
140   PROP_ESCAPE_CODING,
141   PROP_EXHAUSTIVE_MODEL_SEARCH,
142   PROP_MIN_RESIDUAL_PARTITION_ORDER,
143   PROP_MAX_RESIDUAL_PARTITION_ORDER,
144   PROP_RICE_PARAMETER_SEARCH_DIST,
145   PROP_PADDING,
146   PROP_SEEKPOINTS
147 };
148
149 GST_DEBUG_CATEGORY_STATIC (flacenc_debug);
150 #define GST_CAT_DEFAULT flacenc_debug
151
152
153 #define _do_init(type)                                                          \
154   G_STMT_START{                                                                 \
155     static const GInterfaceInfo tag_setter_info = {                             \
156       NULL,                                                                     \
157       NULL,                                                                     \
158       NULL                                                                      \
159     };                                                                          \
160     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER,                     \
161                                  &tag_setter_info);                             \
162   }G_STMT_END
163
164 GST_BOILERPLATE_FULL (GstFlacEnc, gst_flac_enc, GstAudioEncoder,
165     GST_TYPE_AUDIO_ENCODER, _do_init);
166
167 static gboolean gst_flac_enc_start (GstAudioEncoder * enc);
168 static gboolean gst_flac_enc_stop (GstAudioEncoder * enc);
169 static gboolean gst_flac_enc_set_format (GstAudioEncoder * enc,
170     GstAudioInfo * info);
171 static GstFlowReturn gst_flac_enc_handle_frame (GstAudioEncoder * enc,
172     GstBuffer * in_buf);
173 static GstCaps *gst_flac_enc_getcaps (GstAudioEncoder * enc);
174 static gboolean gst_flac_enc_sink_event (GstAudioEncoder * enc,
175     GstEvent * event);
176
177 static void gst_flac_enc_finalize (GObject * object);
178
179 static gboolean gst_flac_enc_update_quality (GstFlacEnc * flacenc,
180     gint quality);
181 static void gst_flac_enc_set_property (GObject * object, guint prop_id,
182     const GValue * value, GParamSpec * pspec);
183 static void gst_flac_enc_get_property (GObject * object, guint prop_id,
184     GValue * value, GParamSpec * pspec);
185
186 static FLAC__StreamEncoderWriteStatus
187 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
188     const FLAC__byte buffer[], size_t bytes,
189     unsigned samples, unsigned current_frame, void *client_data);
190 static FLAC__StreamEncoderSeekStatus
191 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
192     FLAC__uint64 absolute_byte_offset, void *client_data);
193 static FLAC__StreamEncoderTellStatus
194 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
195     FLAC__uint64 * absolute_byte_offset, void *client_data);
196
197 typedef struct
198 {
199   gboolean exhaustive_model_search;
200   gboolean escape_coding;
201   gboolean mid_side;
202   gboolean loose_mid_side;
203   guint qlp_coeff_precision;
204   gboolean qlp_coeff_prec_search;
205   guint min_residual_partition_order;
206   guint max_residual_partition_order;
207   guint rice_parameter_search_dist;
208   guint max_lpc_order;
209   guint blocksize;
210 }
211 GstFlacEncParams;
212
213 static const GstFlacEncParams flacenc_params[] = {
214   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 2, 2, 0, 0, 1152},
215   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 2, 2, 0, 0, 1152},
216   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 3, 0, 0, 1152},
217   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 3, 3, 0, 6, 4608},
218   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 3, 3, 0, 8, 4608},
219   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 3, 3, 0, 8, 4608},
220   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 4, 0, 8, 4608},
221   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 8, 4608},
222   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 12, 4608},
223   {TRUE, TRUE, TRUE, FALSE, 0, FALSE, 0, 16, 0, 32, 4608},
224 };
225
226 #define DEFAULT_QUALITY 5
227 #define DEFAULT_PADDING 0
228 #define DEFAULT_SEEKPOINTS 0
229
230 #define GST_TYPE_FLAC_ENC_QUALITY (gst_flac_enc_quality_get_type ())
231 static GType
232 gst_flac_enc_quality_get_type (void)
233 {
234   static GType qtype = 0;
235
236   if (qtype == 0) {
237     static const GEnumValue values[] = {
238       {0, "0 - Fastest compression", "0"},
239       {1, "1", "1"},
240       {2, "2", "2"},
241       {3, "3", "3"},
242       {4, "4", "4"},
243       {5, "5 - Default", "5"},
244       {6, "6", "6"},
245       {7, "7", "7"},
246       {8, "8 - Highest compression", "8"},
247       {9, "9 - Insane", "9"},
248       {0, NULL, NULL}
249     };
250
251     qtype = g_enum_register_static ("GstFlacEncQuality", values);
252   }
253   return qtype;
254 }
255
256 static void
257 gst_flac_enc_base_init (gpointer g_class)
258 {
259   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
260
261   gst_element_class_add_static_pad_template (element_class, &src_factory);
262   gst_element_class_add_static_pad_template (element_class, &sink_factory);
263
264   gst_element_class_set_details_simple (element_class, "FLAC audio encoder",
265       "Codec/Encoder/Audio",
266       "Encodes audio with the FLAC lossless audio encoder",
267       "Wim Taymans <wim.taymans@chello.be>");
268
269   GST_DEBUG_CATEGORY_INIT (flacenc_debug, "flacenc", 0,
270       "Flac encoding element");
271 }
272
273 static void
274 gst_flac_enc_class_init (GstFlacEncClass * klass)
275 {
276   GObjectClass *gobject_class;
277   GstAudioEncoderClass *base_class;
278
279   gobject_class = (GObjectClass *) klass;
280   base_class = (GstAudioEncoderClass *) (klass);
281
282   gobject_class->set_property = gst_flac_enc_set_property;
283   gobject_class->get_property = gst_flac_enc_get_property;
284   gobject_class->finalize = gst_flac_enc_finalize;
285
286   base_class->start = GST_DEBUG_FUNCPTR (gst_flac_enc_start);
287   base_class->stop = GST_DEBUG_FUNCPTR (gst_flac_enc_stop);
288   base_class->set_format = GST_DEBUG_FUNCPTR (gst_flac_enc_set_format);
289   base_class->handle_frame = GST_DEBUG_FUNCPTR (gst_flac_enc_handle_frame);
290   base_class->getcaps = GST_DEBUG_FUNCPTR (gst_flac_enc_getcaps);
291   base_class->event = GST_DEBUG_FUNCPTR (gst_flac_enc_sink_event);
292
293   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QUALITY,
294       g_param_spec_enum ("quality",
295           "Quality",
296           "Speed versus compression tradeoff",
297           GST_TYPE_FLAC_ENC_QUALITY, DEFAULT_QUALITY,
298           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
299   g_object_class_install_property (G_OBJECT_CLASS (klass),
300       PROP_STREAMABLE_SUBSET, g_param_spec_boolean ("streamable-subset",
301           "Streamable subset",
302           "true to limit encoder to generating a Subset stream, else false",
303           TRUE,
304           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
305   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MID_SIDE_STEREO,
306       g_param_spec_boolean ("mid-side-stereo", "Do mid side stereo",
307           "Do mid side stereo (only for stereo input)",
308           flacenc_params[DEFAULT_QUALITY].mid_side,
309           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
310   g_object_class_install_property (G_OBJECT_CLASS (klass),
311       PROP_LOOSE_MID_SIDE_STEREO, g_param_spec_boolean ("loose-mid-side-stereo",
312           "Loose mid side stereo", "Loose mid side stereo",
313           flacenc_params[DEFAULT_QUALITY].loose_mid_side,
314           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
315   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BLOCKSIZE,
316       g_param_spec_uint ("blocksize", "Blocksize", "Blocksize in samples",
317           FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE,
318           flacenc_params[DEFAULT_QUALITY].blocksize,
319           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
320   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MAX_LPC_ORDER,
321       g_param_spec_uint ("max-lpc-order", "Max LPC order",
322           "Max LPC order; 0 => use only fixed predictors", 0,
323           FLAC__MAX_LPC_ORDER, flacenc_params[DEFAULT_QUALITY].max_lpc_order,
324           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
325   g_object_class_install_property (G_OBJECT_CLASS (klass),
326       PROP_QLP_COEFF_PRECISION, g_param_spec_uint ("qlp-coeff-precision",
327           "QLP coefficients precision",
328           "Precision in bits of quantized linear-predictor coefficients; 0 = automatic",
329           0, 32, flacenc_params[DEFAULT_QUALITY].qlp_coeff_precision,
330           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
331   g_object_class_install_property (G_OBJECT_CLASS (klass),
332       PROP_QLP_COEFF_PREC_SEARCH, g_param_spec_boolean ("qlp-coeff-prec-search",
333           "Do QLP coefficients precision search",
334           "false = use qlp_coeff_precision, "
335           "true = search around qlp_coeff_precision, take best",
336           flacenc_params[DEFAULT_QUALITY].qlp_coeff_prec_search,
337           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
338   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ESCAPE_CODING,
339       g_param_spec_boolean ("escape-coding", "Do Escape coding",
340           "search for escape codes in the entropy coding stage "
341           "for slightly better compression",
342           flacenc_params[DEFAULT_QUALITY].escape_coding,
343           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
344   g_object_class_install_property (G_OBJECT_CLASS (klass),
345       PROP_EXHAUSTIVE_MODEL_SEARCH,
346       g_param_spec_boolean ("exhaustive-model-search",
347           "Do exhaustive model search",
348           "do exhaustive search of LP coefficient quantization (expensive!)",
349           flacenc_params[DEFAULT_QUALITY].exhaustive_model_search,
350           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
351   g_object_class_install_property (G_OBJECT_CLASS (klass),
352       PROP_MIN_RESIDUAL_PARTITION_ORDER,
353       g_param_spec_uint ("min-residual-partition-order",
354           "Min residual partition order",
355           "Min residual partition order (above 4 doesn't usually help much)", 0,
356           16, flacenc_params[DEFAULT_QUALITY].min_residual_partition_order,
357           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
358   g_object_class_install_property (G_OBJECT_CLASS (klass),
359       PROP_MAX_RESIDUAL_PARTITION_ORDER,
360       g_param_spec_uint ("max-residual-partition-order",
361           "Max residual partition order",
362           "Max residual partition order (above 4 doesn't usually help much)", 0,
363           16, flacenc_params[DEFAULT_QUALITY].max_residual_partition_order,
364           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
365   g_object_class_install_property (G_OBJECT_CLASS (klass),
366       PROP_RICE_PARAMETER_SEARCH_DIST,
367       g_param_spec_uint ("rice-parameter-search-dist",
368           "rice_parameter_search_dist",
369           "0 = try only calc'd parameter k; else try all [k-dist..k+dist] "
370           "parameters, use best", 0, FLAC__MAX_RICE_PARTITION_ORDER,
371           flacenc_params[DEFAULT_QUALITY].rice_parameter_search_dist,
372           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
373
374   /**
375    * GstFlacEnc:padding
376    *
377    * Write a PADDING block with this length in bytes
378    *
379    * Since: 0.10.16
380    **/
381   g_object_class_install_property (G_OBJECT_CLASS (klass),
382       PROP_PADDING,
383       g_param_spec_uint ("padding",
384           "Padding",
385           "Write a PADDING block with this length in bytes", 0, G_MAXUINT,
386           DEFAULT_PADDING,
387           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
388
389   /**
390    * GstFlacEnc:seekpoints
391    *
392    * Write a SEEKTABLE block with a specific number of seekpoints
393    * or with a specific interval spacing.
394    *
395    * Since: 0.10.18
396    **/
397   g_object_class_install_property (G_OBJECT_CLASS (klass),
398       PROP_SEEKPOINTS,
399       g_param_spec_int ("seekpoints",
400           "Seekpoints",
401           "Add SEEKTABLE metadata (if > 0, number of entries, if < 0, interval in sec)",
402           -G_MAXINT, G_MAXINT,
403           DEFAULT_SEEKPOINTS,
404           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
405 }
406
407 static void
408 gst_flac_enc_init (GstFlacEnc * flacenc, GstFlacEncClass * klass)
409 {
410   GstAudioEncoder *enc = GST_AUDIO_ENCODER (flacenc);
411
412   flacenc->encoder = FLAC__stream_encoder_new ();
413   gst_flac_enc_update_quality (flacenc, DEFAULT_QUALITY);
414
415   /* arrange granulepos marking (and required perfect ts) */
416   gst_audio_encoder_set_mark_granule (enc, TRUE);
417   gst_audio_encoder_set_perfect_timestamp (enc, TRUE);
418 }
419
420 static void
421 gst_flac_enc_finalize (GObject * object)
422 {
423   GstFlacEnc *flacenc = GST_FLAC_ENC (object);
424
425   FLAC__stream_encoder_delete (flacenc->encoder);
426
427   G_OBJECT_CLASS (parent_class)->finalize (object);
428 }
429
430 static gboolean
431 gst_flac_enc_start (GstAudioEncoder * enc)
432 {
433   GstFlacEnc *flacenc = GST_FLAC_ENC (enc);
434
435   GST_DEBUG_OBJECT (enc, "start");
436   flacenc->stopped = TRUE;
437   flacenc->got_headers = FALSE;
438   flacenc->last_flow = GST_FLOW_OK;
439   flacenc->offset = 0;
440   flacenc->channels = 0;
441   flacenc->depth = 0;
442   flacenc->sample_rate = 0;
443   flacenc->eos = FALSE;
444   flacenc->tags = gst_tag_list_new ();
445
446   return TRUE;
447 }
448
449 static gboolean
450 gst_flac_enc_stop (GstAudioEncoder * enc)
451 {
452   GstFlacEnc *flacenc = GST_FLAC_ENC (enc);
453
454   GST_DEBUG_OBJECT (enc, "stop");
455   gst_tag_list_free (flacenc->tags);
456   flacenc->tags = NULL;
457   if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
458       FLAC__STREAM_ENCODER_UNINITIALIZED) {
459     flacenc->stopped = TRUE;
460     FLAC__stream_encoder_finish (flacenc->encoder);
461   }
462   if (flacenc->meta) {
463     FLAC__metadata_object_delete (flacenc->meta[0]);
464
465     if (flacenc->meta[1])
466       FLAC__metadata_object_delete (flacenc->meta[1]);
467
468     if (flacenc->meta[2])
469       FLAC__metadata_object_delete (flacenc->meta[2]);
470
471     g_free (flacenc->meta);
472     flacenc->meta = NULL;
473   }
474   g_list_foreach (flacenc->headers, (GFunc) gst_mini_object_unref, NULL);
475   g_list_free (flacenc->headers);
476   flacenc->headers = NULL;
477
478   gst_tag_setter_reset_tags (GST_TAG_SETTER (enc));
479
480   return TRUE;
481 }
482
483 static void
484 add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
485 {
486   GList *comments;
487   GList *it;
488   GstFlacEnc *flacenc = GST_FLAC_ENC (user_data);
489
490   /* IMAGE and PREVIEW_IMAGE tags are already written
491    * differently, no need to store them inside the
492    * vorbiscomments too */
493   if (strcmp (tag, GST_TAG_IMAGE) == 0
494       || strcmp (tag, GST_TAG_PREVIEW_IMAGE) == 0)
495     return;
496
497   comments = gst_tag_to_vorbis_comments (list, tag);
498   for (it = comments; it != NULL; it = it->next) {
499     FLAC__StreamMetadata_VorbisComment_Entry commment_entry;
500
501     commment_entry.length = strlen (it->data);
502     commment_entry.entry = it->data;
503     FLAC__metadata_object_vorbiscomment_insert_comment (flacenc->meta[0],
504         flacenc->meta[0]->data.vorbis_comment.num_comments,
505         commment_entry, TRUE);
506     g_free (it->data);
507   }
508   g_list_free (comments);
509 }
510
511 static void
512 gst_flac_enc_set_metadata (GstFlacEnc * flacenc, guint64 total_samples)
513 {
514   const GstTagList *user_tags;
515   GstTagList *copy;
516   gint entries = 1;
517   gint n_images, n_preview_images;
518
519   g_return_if_fail (flacenc != NULL);
520   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (flacenc));
521   if ((flacenc->tags == NULL) && (user_tags == NULL)) {
522     return;
523   }
524   copy = gst_tag_list_merge (user_tags, flacenc->tags,
525       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
526   n_images = gst_tag_list_get_tag_size (copy, GST_TAG_IMAGE);
527   n_preview_images = gst_tag_list_get_tag_size (copy, GST_TAG_PREVIEW_IMAGE);
528
529   flacenc->meta =
530       g_new0 (FLAC__StreamMetadata *, 3 + n_images + n_preview_images);
531
532   flacenc->meta[0] =
533       FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT);
534   gst_tag_list_foreach (copy, add_one_tag, flacenc);
535
536   if (n_images + n_preview_images > 0) {
537     GstBuffer *buffer;
538     GstCaps *caps;
539     GstStructure *structure;
540     GstTagImageType image_type = GST_TAG_IMAGE_TYPE_NONE;
541     gint i;
542
543     for (i = 0; i < n_images + n_preview_images; i++) {
544       if (i < n_images) {
545         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_IMAGE, i, &buffer))
546           continue;
547       } else {
548         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_PREVIEW_IMAGE,
549                 i - n_images, &buffer))
550           continue;
551       }
552
553       flacenc->meta[entries] =
554           FLAC__metadata_object_new (FLAC__METADATA_TYPE_PICTURE);
555
556       caps = gst_buffer_get_caps (buffer);
557       structure = gst_caps_get_structure (caps, 0);
558
559       gst_structure_get (structure, "image-type", GST_TYPE_TAG_IMAGE_TYPE,
560           &image_type, NULL);
561       /* Convert to ID3v2 APIC image type */
562       if (image_type == GST_TAG_IMAGE_TYPE_NONE)
563         image_type = (i < n_images) ? 0x00 : 0x01;
564       else
565         image_type = image_type + 2;
566
567       FLAC__metadata_object_picture_set_data (flacenc->meta[entries],
568           GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), TRUE);
569       /* FIXME: There's no way to set the picture type in libFLAC */
570       flacenc->meta[entries]->data.picture.type = image_type;
571       FLAC__metadata_object_picture_set_mime_type (flacenc->meta[entries],
572           (char *) gst_structure_get_name (structure), TRUE);
573
574       gst_caps_unref (caps);
575       gst_buffer_unref (buffer);
576       entries++;
577     }
578   }
579
580   if (flacenc->seekpoints && total_samples != GST_CLOCK_TIME_NONE) {
581     gboolean res;
582     guint samples;
583
584     flacenc->meta[entries] =
585         FLAC__metadata_object_new (FLAC__METADATA_TYPE_SEEKTABLE);
586     if (flacenc->seekpoints > 0) {
587       res =
588           FLAC__metadata_object_seektable_template_append_spaced_points
589           (flacenc->meta[entries], flacenc->seekpoints, total_samples);
590     } else {
591       samples = -flacenc->seekpoints * flacenc->sample_rate;
592       res =
593           FLAC__metadata_object_seektable_template_append_spaced_points_by_samples
594           (flacenc->meta[entries], samples, total_samples);
595     }
596     if (!res) {
597       GST_DEBUG_OBJECT (flacenc, "adding seekpoint template %d failed",
598           flacenc->seekpoints);
599       FLAC__metadata_object_delete (flacenc->meta[1]);
600       flacenc->meta[entries] = NULL;
601     } else {
602       entries++;
603     }
604   } else if (flacenc->seekpoints && total_samples == GST_CLOCK_TIME_NONE) {
605     GST_WARNING_OBJECT (flacenc, "total time unknown; can not add seekpoints");
606   }
607
608   if (flacenc->padding > 0) {
609     flacenc->meta[entries] =
610         FLAC__metadata_object_new (FLAC__METADATA_TYPE_PADDING);
611     flacenc->meta[entries]->length = flacenc->padding;
612     entries++;
613   }
614
615   if (FLAC__stream_encoder_set_metadata (flacenc->encoder,
616           flacenc->meta, entries) != true)
617     g_warning ("Dude, i'm already initialized!");
618
619   gst_tag_list_free (copy);
620 }
621
622 static void
623 gst_flac_enc_caps_append_structure_with_widths (GstCaps * caps,
624     GstStructure * s)
625 {
626   GstStructure *tmp;
627   GValue list = { 0, };
628   GValue depth = { 0, };
629
630
631   tmp = gst_structure_copy (s);
632   gst_structure_set (tmp, "width", G_TYPE_INT, 8, "depth", G_TYPE_INT, 8, NULL);
633   gst_caps_append_structure (caps, tmp);
634
635   tmp = gst_structure_copy (s);
636
637   g_value_init (&depth, G_TYPE_INT);
638   g_value_init (&list, GST_TYPE_LIST);
639   g_value_set_int (&depth, 12);
640   gst_value_list_append_value (&list, &depth);
641   g_value_set_int (&depth, 16);
642   gst_value_list_append_value (&list, &depth);
643
644   gst_structure_set (tmp, "width", G_TYPE_INT, 16, NULL);
645   gst_structure_set_value (tmp, "depth", &list);
646   gst_caps_append_structure (caps, tmp);
647
648   g_value_reset (&list);
649
650   tmp = s;
651
652   g_value_set_int (&depth, 20);
653   gst_value_list_append_value (&list, &depth);
654   g_value_set_int (&depth, 24);
655   gst_value_list_append_value (&list, &depth);
656
657   gst_structure_set (tmp, "width", G_TYPE_INT, 32, NULL);
658   gst_structure_set_value (tmp, "depth", &list);
659   gst_caps_append_structure (caps, tmp);
660
661   g_value_unset (&list);
662   g_value_unset (&depth);
663 }
664
665 static GstCaps *
666 gst_flac_enc_getcaps (GstAudioEncoder * enc)
667 {
668   GstCaps *ret = NULL, *caps = NULL;
669   GstPad *pad;
670
671   pad = GST_AUDIO_ENCODER_SINK_PAD (enc);
672
673   GST_OBJECT_LOCK (pad);
674
675   if (GST_PAD_CAPS (pad)) {
676     ret = gst_caps_ref (GST_PAD_CAPS (pad));
677   } else {
678     gint i, c;
679
680     ret = gst_caps_new_empty ();
681
682     gst_flac_enc_caps_append_structure_with_widths (ret,
683         gst_structure_new ("audio/x-raw-int",
684             "endianness", G_TYPE_INT, G_BYTE_ORDER,
685             "signed", G_TYPE_BOOLEAN, TRUE,
686             "rate", GST_TYPE_INT_RANGE, 1, 655350,
687             "channels", GST_TYPE_INT_RANGE, 1, 2, NULL));
688
689     for (i = 3; i <= 8; i++) {
690       GValue positions = { 0, };
691       GValue pos = { 0, };
692       GstStructure *s;
693
694       g_value_init (&positions, GST_TYPE_ARRAY);
695       g_value_init (&pos, GST_TYPE_AUDIO_CHANNEL_POSITION);
696
697       for (c = 0; c < i; c++) {
698         g_value_set_enum (&pos, channel_positions[i - 1][c]);
699         gst_value_array_append_value (&positions, &pos);
700       }
701       g_value_unset (&pos);
702
703       s = gst_structure_new ("audio/x-raw-int",
704           "endianness", G_TYPE_INT, G_BYTE_ORDER,
705           "signed", G_TYPE_BOOLEAN, TRUE,
706           "rate", GST_TYPE_INT_RANGE, 1, 655350,
707           "channels", G_TYPE_INT, i, NULL);
708       gst_structure_set_value (s, "channel-positions", &positions);
709       g_value_unset (&positions);
710
711       gst_flac_enc_caps_append_structure_with_widths (ret, s);
712     }
713   }
714
715   GST_OBJECT_UNLOCK (pad);
716
717   GST_DEBUG_OBJECT (pad, "Return caps %" GST_PTR_FORMAT, ret);
718
719   caps = gst_audio_encoder_proxy_getcaps (enc, ret);
720   gst_caps_unref (ret);
721
722   return caps;
723 }
724
725 static guint64
726 gst_flac_enc_query_peer_total_samples (GstFlacEnc * flacenc, GstPad * pad)
727 {
728   GstFormat fmt = GST_FORMAT_DEFAULT;
729   gint64 duration;
730
731   GST_DEBUG_OBJECT (flacenc, "querying peer for DEFAULT format duration");
732   if (gst_pad_query_peer_duration (pad, &fmt, &duration)
733       && fmt == GST_FORMAT_DEFAULT && duration != GST_CLOCK_TIME_NONE)
734     goto done;
735
736   fmt = GST_FORMAT_TIME;
737   GST_DEBUG_OBJECT (flacenc, "querying peer for TIME format duration");
738
739   if (gst_pad_query_peer_duration (pad, &fmt, &duration) &&
740       fmt == GST_FORMAT_TIME && duration != GST_CLOCK_TIME_NONE) {
741     GST_DEBUG_OBJECT (flacenc, "peer reported duration %" GST_TIME_FORMAT,
742         GST_TIME_ARGS (duration));
743     duration = GST_CLOCK_TIME_TO_FRAMES (duration, flacenc->sample_rate);
744
745     goto done;
746   }
747
748   GST_DEBUG_OBJECT (flacenc, "Upstream reported no total samples");
749   return GST_CLOCK_TIME_NONE;
750
751 done:
752   GST_DEBUG_OBJECT (flacenc,
753       "Upstream reported %" G_GUINT64_FORMAT " total samples", duration);
754
755   return duration;
756 }
757
758 static gboolean
759 gst_flac_enc_set_format (GstAudioEncoder * enc, GstAudioInfo * info)
760 {
761   GstFlacEnc *flacenc;
762   guint64 total_samples = GST_CLOCK_TIME_NONE;
763   FLAC__StreamEncoderInitStatus init_status;
764   GstCaps *caps;
765
766   flacenc = GST_FLAC_ENC (enc);
767
768   /* if configured again, means something changed, can't handle that */
769   if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
770       FLAC__STREAM_ENCODER_UNINITIALIZED)
771     goto encoder_already_initialized;
772
773   flacenc->channels = GST_AUDIO_INFO_CHANNELS (info);
774   flacenc->width = GST_AUDIO_INFO_WIDTH (info);
775   flacenc->depth = GST_AUDIO_INFO_DEPTH (info);
776   flacenc->sample_rate = GST_AUDIO_INFO_RATE (info);
777
778   caps = gst_caps_new_simple ("audio/x-flac",
779       "channels", G_TYPE_INT, flacenc->channels,
780       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
781
782   if (!gst_pad_set_caps (GST_AUDIO_ENCODER_SRC_PAD (enc), caps))
783     goto setting_src_caps_failed;
784
785   gst_caps_unref (caps);
786
787   total_samples = gst_flac_enc_query_peer_total_samples (flacenc,
788       GST_AUDIO_ENCODER_SINK_PAD (enc));
789
790   FLAC__stream_encoder_set_bits_per_sample (flacenc->encoder, flacenc->depth);
791   FLAC__stream_encoder_set_sample_rate (flacenc->encoder, flacenc->sample_rate);
792   FLAC__stream_encoder_set_channels (flacenc->encoder, flacenc->channels);
793
794   if (total_samples != GST_CLOCK_TIME_NONE)
795     FLAC__stream_encoder_set_total_samples_estimate (flacenc->encoder,
796         MIN (total_samples, G_GUINT64_CONSTANT (0x0FFFFFFFFF)));
797
798   gst_flac_enc_set_metadata (flacenc, total_samples);
799
800   /* callbacks clear to go now;
801    * write callbacks receives headers during init */
802   flacenc->stopped = FALSE;
803
804   init_status = FLAC__stream_encoder_init_stream (flacenc->encoder,
805       gst_flac_enc_write_callback, gst_flac_enc_seek_callback,
806       gst_flac_enc_tell_callback, NULL, flacenc);
807   if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
808     goto failed_to_initialize;
809
810   /* no special feedback to base class; should provide all available samples */
811
812   return TRUE;
813
814 encoder_already_initialized:
815   {
816     g_warning ("flac already initialized -- fixme allow this");
817     gst_object_unref (flacenc);
818     return FALSE;
819   }
820 setting_src_caps_failed:
821   {
822     GST_DEBUG_OBJECT (flacenc,
823         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
824     gst_caps_unref (caps);
825     gst_object_unref (flacenc);
826     return FALSE;
827   }
828 failed_to_initialize:
829   {
830     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
831         ("could not initialize encoder (wrong parameters?)"));
832     gst_object_unref (flacenc);
833     return FALSE;
834   }
835 }
836
837 static gboolean
838 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
839 {
840   flacenc->quality = quality;
841
842 #define DO_UPDATE(name, val, str)                                               \
843   G_STMT_START {                                                                \
844     if (FLAC__stream_encoder_get_##name (flacenc->encoder) !=                   \
845         flacenc_params[quality].val) {                                          \
846       FLAC__stream_encoder_set_##name (flacenc->encoder,                        \
847           flacenc_params[quality].val);                                         \
848       g_object_notify (G_OBJECT (flacenc), str);                                \
849     }                                                                           \
850   } G_STMT_END
851
852   g_object_freeze_notify (G_OBJECT (flacenc));
853
854   if (flacenc->channels == 2 || flacenc->channels == 0) {
855     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
856     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
857   }
858
859   DO_UPDATE (blocksize, blocksize, "blocksize");
860   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
861   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
862   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
863       "qlp_coeff_prec_search");
864   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
865   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
866       "exhaustive_model_search");
867   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
868       "min_residual_partition_order");
869   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
870       "max_residual_partition_order");
871   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
872       "rice_parameter_search_dist");
873
874 #undef DO_UPDATE
875
876   g_object_thaw_notify (G_OBJECT (flacenc));
877
878   return TRUE;
879 }
880
881 static FLAC__StreamEncoderSeekStatus
882 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
883     FLAC__uint64 absolute_byte_offset, void *client_data)
884 {
885   GstFlacEnc *flacenc;
886   GstEvent *event;
887   GstPad *peerpad;
888
889   flacenc = GST_FLAC_ENC (client_data);
890
891   if (flacenc->stopped)
892     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
893
894   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
895       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
896
897   if ((peerpad = gst_pad_get_peer (GST_AUDIO_ENCODER_SRC_PAD (flacenc)))) {
898     gboolean ret = gst_pad_send_event (peerpad, event);
899
900     gst_object_unref (peerpad);
901
902     if (ret) {
903       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
904           (guint64) absolute_byte_offset, "succeeded");
905     } else {
906       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
907           (guint64) absolute_byte_offset, "failed");
908       return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
909     }
910   } else {
911     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
912         (guint64) absolute_byte_offset);
913   }
914
915   flacenc->offset = absolute_byte_offset;
916   return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
917 }
918
919 static void
920 notgst_value_array_append_buffer (GValue * array_val, GstBuffer * buf)
921 {
922   GValue value = { 0, };
923
924   g_value_init (&value, GST_TYPE_BUFFER);
925   /* copy buffer to avoid problems with circular refcounts */
926   buf = gst_buffer_copy (buf);
927   /* again, for good measure */
928   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
929   gst_value_set_buffer (&value, buf);
930   gst_buffer_unref (buf);
931   gst_value_array_append_value (array_val, &value);
932   g_value_unset (&value);
933 }
934
935 #define HDR_TYPE_STREAMINFO     0
936 #define HDR_TYPE_VORBISCOMMENT  4
937
938 static GstFlowReturn
939 gst_flac_enc_process_stream_headers (GstFlacEnc * enc)
940 {
941   GstBuffer *vorbiscomment = NULL;
942   GstBuffer *streaminfo = NULL;
943   GstBuffer *marker = NULL;
944   GValue array = { 0, };
945   GstCaps *caps;
946   GList *l;
947   GstFlowReturn ret = GST_FLOW_OK;
948
949   caps = gst_caps_new_simple ("audio/x-flac",
950       "channels", G_TYPE_INT, enc->channels,
951       "rate", G_TYPE_INT, enc->sample_rate, NULL);
952
953   for (l = enc->headers; l != NULL; l = l->next) {
954     const guint8 *data;
955     guint size;
956
957     /* mark buffers so oggmux will ignore them if it already muxed the
958      * header buffers from the streamheaders field in the caps */
959     l->data = gst_buffer_make_metadata_writable (GST_BUFFER (l->data));
960     GST_BUFFER_FLAG_SET (GST_BUFFER (l->data), GST_BUFFER_FLAG_IN_CAPS);
961
962     data = GST_BUFFER_DATA (GST_BUFFER_CAST (l->data));
963     size = GST_BUFFER_SIZE (GST_BUFFER_CAST (l->data));
964
965     /* find initial 4-byte marker which we need to skip later on */
966     if (size == 4 && memcmp (data, "fLaC", 4) == 0) {
967       marker = GST_BUFFER_CAST (l->data);
968     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_STREAMINFO) {
969       streaminfo = GST_BUFFER_CAST (l->data);
970     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_VORBISCOMMENT) {
971       vorbiscomment = GST_BUFFER_CAST (l->data);
972     }
973   }
974
975   if (marker == NULL || streaminfo == NULL || vorbiscomment == NULL) {
976     GST_WARNING_OBJECT (enc, "missing header %p %p %p, muxing into container "
977         "formats may be broken", marker, streaminfo, vorbiscomment);
978     goto push_headers;
979   }
980
981   g_value_init (&array, GST_TYPE_ARRAY);
982
983   /* add marker including STREAMINFO header */
984   {
985     GstBuffer *buf;
986     guint16 num;
987
988     /* minus one for the marker that is merged with streaminfo here */
989     num = g_list_length (enc->headers) - 1;
990
991     buf = gst_buffer_new_and_alloc (13 + GST_BUFFER_SIZE (streaminfo));
992     GST_BUFFER_DATA (buf)[0] = 0x7f;
993     memcpy (GST_BUFFER_DATA (buf) + 1, "FLAC", 4);
994     GST_BUFFER_DATA (buf)[5] = 0x01;    /* mapping version major */
995     GST_BUFFER_DATA (buf)[6] = 0x00;    /* mapping version minor */
996     GST_BUFFER_DATA (buf)[7] = (num & 0xFF00) >> 8;
997     GST_BUFFER_DATA (buf)[8] = (num & 0x00FF) >> 0;
998     memcpy (GST_BUFFER_DATA (buf) + 9, "fLaC", 4);
999     memcpy (GST_BUFFER_DATA (buf) + 13, GST_BUFFER_DATA (streaminfo),
1000         GST_BUFFER_SIZE (streaminfo));
1001     notgst_value_array_append_buffer (&array, buf);
1002     gst_buffer_unref (buf);
1003   }
1004
1005   /* add VORBISCOMMENT header */
1006   notgst_value_array_append_buffer (&array, vorbiscomment);
1007
1008   /* add other headers, if there are any */
1009   for (l = enc->headers; l != NULL; l = l->next) {
1010     if (GST_BUFFER_CAST (l->data) != marker &&
1011         GST_BUFFER_CAST (l->data) != streaminfo &&
1012         GST_BUFFER_CAST (l->data) != vorbiscomment) {
1013       notgst_value_array_append_buffer (&array, GST_BUFFER_CAST (l->data));
1014     }
1015   }
1016
1017   gst_structure_set_value (gst_caps_get_structure (caps, 0),
1018       "streamheader", &array);
1019   g_value_unset (&array);
1020
1021 push_headers:
1022
1023   /* push header buffers; update caps, so when we push the first buffer the
1024    * negotiated caps will change to caps that include the streamheader field */
1025   for (l = enc->headers; l != NULL; l = l->next) {
1026     GstBuffer *buf;
1027
1028     buf = GST_BUFFER (l->data);
1029     gst_buffer_set_caps (buf, caps);
1030     GST_LOG_OBJECT (enc, "Pushing header buffer, size %u bytes",
1031         GST_BUFFER_SIZE (buf));
1032     GST_MEMDUMP_OBJECT (enc, "header buffer", GST_BUFFER_DATA (buf),
1033         GST_BUFFER_SIZE (buf));
1034     ret = gst_pad_push (GST_AUDIO_ENCODER_SRC_PAD (enc), buf);
1035     l->data = NULL;
1036   }
1037   g_list_free (enc->headers);
1038   enc->headers = NULL;
1039
1040   gst_caps_unref (caps);
1041
1042   return ret;
1043 }
1044
1045 static FLAC__StreamEncoderWriteStatus
1046 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
1047     const FLAC__byte buffer[], size_t bytes,
1048     unsigned samples, unsigned current_frame, void *client_data)
1049 {
1050   GstFlowReturn ret = GST_FLOW_OK;
1051   GstFlacEnc *flacenc;
1052   GstBuffer *outbuf;
1053
1054   flacenc = GST_FLAC_ENC (client_data);
1055
1056   if (flacenc->stopped)
1057     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1058
1059   outbuf = gst_buffer_new_and_alloc (bytes);
1060   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
1061
1062   /* we assume libflac passes us stuff neatly framed */
1063   if (!flacenc->got_headers) {
1064     if (samples == 0) {
1065       GST_DEBUG_OBJECT (flacenc, "Got header, queueing (%u bytes)",
1066           (guint) bytes);
1067       flacenc->headers = g_list_append (flacenc->headers, outbuf);
1068       /* note: it's important that we increase our byte offset */
1069       goto out;
1070     } else {
1071       GST_INFO_OBJECT (flacenc, "Non-header packet, we have all headers now");
1072       ret = gst_flac_enc_process_stream_headers (flacenc);
1073       flacenc->got_headers = TRUE;
1074     }
1075   }
1076
1077   if (flacenc->got_headers && samples == 0) {
1078     /* header fixup, push downstream directly */
1079     GST_DEBUG_OBJECT (flacenc, "Fixing up headers at pos=%" G_GUINT64_FORMAT
1080         ", size=%u", flacenc->offset, (guint) bytes);
1081     GST_MEMDUMP_OBJECT (flacenc, "Presumed header fragment",
1082         GST_BUFFER_DATA (outbuf), GST_BUFFER_SIZE (outbuf));
1083     gst_buffer_set_caps (outbuf,
1084         GST_PAD_CAPS (GST_AUDIO_ENCODER_SRC_PAD (flacenc)));
1085     ret = gst_pad_push (GST_AUDIO_ENCODER_SRC_PAD (flacenc), outbuf);
1086   } else {
1087     /* regular frame data, pass to base class */
1088     GST_LOG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
1089         "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1090         samples, (guint) bytes, flacenc->offset);
1091     ret = gst_audio_encoder_finish_frame (GST_AUDIO_ENCODER (flacenc),
1092         outbuf, samples);
1093   }
1094
1095   if (ret != GST_FLOW_OK)
1096     GST_DEBUG_OBJECT (flacenc, "flow: %s", gst_flow_get_name (ret));
1097
1098   flacenc->last_flow = ret;
1099
1100 out:
1101   flacenc->offset += bytes;
1102
1103   if (ret != GST_FLOW_OK)
1104     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1105
1106   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1107 }
1108
1109 static FLAC__StreamEncoderTellStatus
1110 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
1111     FLAC__uint64 * absolute_byte_offset, void *client_data)
1112 {
1113   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
1114
1115   *absolute_byte_offset = flacenc->offset;
1116
1117   return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
1118 }
1119
1120 static gboolean
1121 gst_flac_enc_sink_event (GstAudioEncoder * enc, GstEvent * event)
1122 {
1123   GstFlacEnc *flacenc;
1124   GstTagList *taglist;
1125   gboolean ret = FALSE;
1126
1127   flacenc = GST_FLAC_ENC (enc);
1128
1129   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
1130
1131   switch (GST_EVENT_TYPE (event)) {
1132     case GST_EVENT_NEWSEGMENT:{
1133       GstFormat format;
1134       gint64 start, stream_time;
1135
1136       if (flacenc->offset == 0) {
1137         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
1138             &stream_time);
1139       } else {
1140         start = -1;
1141         stream_time = -1;
1142       }
1143
1144       if (start > 0) {
1145         if (flacenc->offset > 0)
1146           GST_DEBUG ("Not handling mid-stream newsegment event");
1147         else
1148           GST_DEBUG ("Not handling newsegment event with non-zero start");
1149       } else {
1150         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1151             0, -1, 0);
1152
1153         ret = gst_pad_push_event (GST_AUDIO_ENCODER_SRC_PAD (enc), e);
1154       }
1155
1156       if (stream_time > 0) {
1157         GST_DEBUG ("Not handling non-zero stream time");
1158       }
1159
1160       /* don't push it downstream, we'll generate our own via seek to 0 */
1161       gst_event_unref (event);
1162       ret = TRUE;
1163       break;
1164     }
1165     case GST_EVENT_EOS:
1166       flacenc->eos = TRUE;
1167       break;
1168     case GST_EVENT_TAG:
1169       if (flacenc->tags) {
1170         gst_event_parse_tag (event, &taglist);
1171         gst_tag_list_insert (flacenc->tags, taglist,
1172             gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
1173       } else {
1174         g_assert_not_reached ();
1175       }
1176       break;
1177     default:
1178       break;
1179   }
1180
1181   return ret;
1182 }
1183
1184 static GstFlowReturn
1185 gst_flac_enc_handle_frame (GstAudioEncoder * enc, GstBuffer * buffer)
1186 {
1187   GstFlacEnc *flacenc;
1188   FLAC__int32 *data;
1189   gulong insize;
1190   gint samples, width;
1191   gulong i;
1192   FLAC__bool res;
1193
1194   flacenc = GST_FLAC_ENC (enc);
1195
1196   /* base class ensures configuration */
1197   g_return_val_if_fail (flacenc->depth != 0, GST_FLOW_NOT_NEGOTIATED);
1198
1199   width = flacenc->width;
1200
1201   if (G_UNLIKELY (!buffer)) {
1202     if (flacenc->eos) {
1203       FLAC__stream_encoder_finish (flacenc->encoder);
1204     } else {
1205       /* can't handle intermittent draining/resyncing */
1206       GST_ELEMENT_WARNING (flacenc, STREAM, FORMAT, (NULL),
1207           ("Stream discontinuity detected. "
1208               "The output may have wrong timestamps, "
1209               "consider using audiorate to handle discontinuities"));
1210     }
1211     return flacenc->last_flow;
1212   }
1213
1214   insize = GST_BUFFER_SIZE (buffer);
1215   samples = insize / (width >> 3);
1216
1217   data = g_malloc (samples * sizeof (FLAC__int32));
1218
1219   if (width == 8) {
1220     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
1221
1222     for (i = 0; i < samples; i++)
1223       data[i] = (FLAC__int32) indata[i];
1224   } else if (width == 16) {
1225     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
1226
1227     for (i = 0; i < samples; i++)
1228       data[i] = (FLAC__int32) indata[i];
1229   } else if (width == 32) {
1230     gint32 *indata = (gint32 *) GST_BUFFER_DATA (buffer);
1231
1232     for (i = 0; i < samples; i++)
1233       data[i] = (FLAC__int32) indata[i];
1234   } else {
1235     g_assert_not_reached ();
1236   }
1237
1238   res = FLAC__stream_encoder_process_interleaved (flacenc->encoder,
1239       (const FLAC__int32 *) data, samples / flacenc->channels);
1240
1241   g_free (data);
1242
1243   if (!res) {
1244     if (flacenc->last_flow == GST_FLOW_OK)
1245       return GST_FLOW_ERROR;
1246     else
1247       return flacenc->last_flow;
1248   }
1249
1250   return GST_FLOW_OK;
1251 }
1252
1253 static void
1254 gst_flac_enc_set_property (GObject * object, guint prop_id,
1255     const GValue * value, GParamSpec * pspec)
1256 {
1257   GstFlacEnc *this = GST_FLAC_ENC (object);
1258
1259   GST_OBJECT_LOCK (this);
1260
1261   switch (prop_id) {
1262     case PROP_QUALITY:
1263       gst_flac_enc_update_quality (this, g_value_get_enum (value));
1264       break;
1265     case PROP_STREAMABLE_SUBSET:
1266       FLAC__stream_encoder_set_streamable_subset (this->encoder,
1267           g_value_get_boolean (value));
1268       break;
1269     case PROP_MID_SIDE_STEREO:
1270       FLAC__stream_encoder_set_do_mid_side_stereo (this->encoder,
1271           g_value_get_boolean (value));
1272       break;
1273     case PROP_LOOSE_MID_SIDE_STEREO:
1274       FLAC__stream_encoder_set_loose_mid_side_stereo (this->encoder,
1275           g_value_get_boolean (value));
1276       break;
1277     case PROP_BLOCKSIZE:
1278       FLAC__stream_encoder_set_blocksize (this->encoder,
1279           g_value_get_uint (value));
1280       break;
1281     case PROP_MAX_LPC_ORDER:
1282       FLAC__stream_encoder_set_max_lpc_order (this->encoder,
1283           g_value_get_uint (value));
1284       break;
1285     case PROP_QLP_COEFF_PRECISION:
1286       FLAC__stream_encoder_set_qlp_coeff_precision (this->encoder,
1287           g_value_get_uint (value));
1288       break;
1289     case PROP_QLP_COEFF_PREC_SEARCH:
1290       FLAC__stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
1291           g_value_get_boolean (value));
1292       break;
1293     case PROP_ESCAPE_CODING:
1294       FLAC__stream_encoder_set_do_escape_coding (this->encoder,
1295           g_value_get_boolean (value));
1296       break;
1297     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1298       FLAC__stream_encoder_set_do_exhaustive_model_search (this->encoder,
1299           g_value_get_boolean (value));
1300       break;
1301     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1302       FLAC__stream_encoder_set_min_residual_partition_order (this->encoder,
1303           g_value_get_uint (value));
1304       break;
1305     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1306       FLAC__stream_encoder_set_max_residual_partition_order (this->encoder,
1307           g_value_get_uint (value));
1308       break;
1309     case PROP_RICE_PARAMETER_SEARCH_DIST:
1310       FLAC__stream_encoder_set_rice_parameter_search_dist (this->encoder,
1311           g_value_get_uint (value));
1312       break;
1313     case PROP_PADDING:
1314       this->padding = g_value_get_uint (value);
1315       break;
1316     case PROP_SEEKPOINTS:
1317       this->seekpoints = g_value_get_int (value);
1318       break;
1319     default:
1320       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1321       break;
1322   }
1323
1324   GST_OBJECT_UNLOCK (this);
1325 }
1326
1327 static void
1328 gst_flac_enc_get_property (GObject * object, guint prop_id,
1329     GValue * value, GParamSpec * pspec)
1330 {
1331   GstFlacEnc *this = GST_FLAC_ENC (object);
1332
1333   GST_OBJECT_LOCK (this);
1334
1335   switch (prop_id) {
1336     case PROP_QUALITY:
1337       g_value_set_enum (value, this->quality);
1338       break;
1339     case PROP_STREAMABLE_SUBSET:
1340       g_value_set_boolean (value,
1341           FLAC__stream_encoder_get_streamable_subset (this->encoder));
1342       break;
1343     case PROP_MID_SIDE_STEREO:
1344       g_value_set_boolean (value,
1345           FLAC__stream_encoder_get_do_mid_side_stereo (this->encoder));
1346       break;
1347     case PROP_LOOSE_MID_SIDE_STEREO:
1348       g_value_set_boolean (value,
1349           FLAC__stream_encoder_get_loose_mid_side_stereo (this->encoder));
1350       break;
1351     case PROP_BLOCKSIZE:
1352       g_value_set_uint (value,
1353           FLAC__stream_encoder_get_blocksize (this->encoder));
1354       break;
1355     case PROP_MAX_LPC_ORDER:
1356       g_value_set_uint (value,
1357           FLAC__stream_encoder_get_max_lpc_order (this->encoder));
1358       break;
1359     case PROP_QLP_COEFF_PRECISION:
1360       g_value_set_uint (value,
1361           FLAC__stream_encoder_get_qlp_coeff_precision (this->encoder));
1362       break;
1363     case PROP_QLP_COEFF_PREC_SEARCH:
1364       g_value_set_boolean (value,
1365           FLAC__stream_encoder_get_do_qlp_coeff_prec_search (this->encoder));
1366       break;
1367     case PROP_ESCAPE_CODING:
1368       g_value_set_boolean (value,
1369           FLAC__stream_encoder_get_do_escape_coding (this->encoder));
1370       break;
1371     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1372       g_value_set_boolean (value,
1373           FLAC__stream_encoder_get_do_exhaustive_model_search (this->encoder));
1374       break;
1375     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1376       g_value_set_uint (value,
1377           FLAC__stream_encoder_get_min_residual_partition_order
1378           (this->encoder));
1379       break;
1380     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1381       g_value_set_uint (value,
1382           FLAC__stream_encoder_get_max_residual_partition_order
1383           (this->encoder));
1384       break;
1385     case PROP_RICE_PARAMETER_SEARCH_DIST:
1386       g_value_set_uint (value,
1387           FLAC__stream_encoder_get_rice_parameter_search_dist (this->encoder));
1388       break;
1389     case PROP_PADDING:
1390       g_value_set_uint (value, this->padding);
1391       break;
1392     case PROP_SEEKPOINTS:
1393       g_value_set_int (value, this->seekpoints);
1394       break;
1395     default:
1396       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1397       break;
1398   }
1399
1400   GST_OBJECT_UNLOCK (this);
1401 }