upload tizen1.0 source
[framework/multimedia/gst-plugins-good0.10.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     static const GInterfaceInfo preset_info = {                                 \
161       NULL,                                                                     \
162       NULL,                                                                     \
163       NULL                                                                      \
164     };                                                                          \
165     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER,                     \
166                                  &tag_setter_info);                             \
167     g_type_add_interface_static (type, GST_TYPE_PRESET,                         \
168                                  &preset_info);                                 \
169   }G_STMT_END
170
171 GST_BOILERPLATE_FULL (GstFlacEnc, gst_flac_enc, GstElement, GST_TYPE_ELEMENT,
172     _do_init);
173
174 static void gst_flac_enc_finalize (GObject * object);
175
176 static gboolean gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps);
177 static GstCaps *gst_flac_enc_sink_getcaps (GstPad * pad);
178 static gboolean gst_flac_enc_sink_event (GstPad * pad, GstEvent * event);
179 static GstFlowReturn gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer);
180
181 static gboolean gst_flac_enc_update_quality (GstFlacEnc * flacenc,
182     gint quality);
183 static void gst_flac_enc_set_property (GObject * object, guint prop_id,
184     const GValue * value, GParamSpec * pspec);
185 static void gst_flac_enc_get_property (GObject * object, guint prop_id,
186     GValue * value, GParamSpec * pspec);
187 static GstStateChangeReturn gst_flac_enc_change_state (GstElement * element,
188     GstStateChange transition);
189
190 static FLAC__StreamEncoderWriteStatus
191 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
192     const FLAC__byte buffer[], size_t bytes,
193     unsigned samples, unsigned current_frame, void *client_data);
194 static FLAC__StreamEncoderSeekStatus
195 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
196     FLAC__uint64 absolute_byte_offset, void *client_data);
197 static FLAC__StreamEncoderTellStatus
198 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
199     FLAC__uint64 * absolute_byte_offset, void *client_data);
200
201 typedef struct
202 {
203   gboolean exhaustive_model_search;
204   gboolean escape_coding;
205   gboolean mid_side;
206   gboolean loose_mid_side;
207   guint qlp_coeff_precision;
208   gboolean qlp_coeff_prec_search;
209   guint min_residual_partition_order;
210   guint max_residual_partition_order;
211   guint rice_parameter_search_dist;
212   guint max_lpc_order;
213   guint blocksize;
214 }
215 GstFlacEncParams;
216
217 static const GstFlacEncParams flacenc_params[] = {
218   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 2, 2, 0, 0, 1152},
219   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 2, 2, 0, 0, 1152},
220   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 3, 0, 0, 1152},
221   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 3, 3, 0, 6, 4608},
222   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 3, 3, 0, 8, 4608},
223   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 3, 3, 0, 8, 4608},
224   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 4, 0, 8, 4608},
225   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 8, 4608},
226   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 12, 4608},
227   {TRUE, TRUE, TRUE, FALSE, 0, FALSE, 0, 16, 0, 32, 4608},
228 };
229
230 #define DEFAULT_QUALITY 5
231 #define DEFAULT_PADDING 0
232 #define DEFAULT_SEEKPOINTS 0
233
234 #define GST_TYPE_FLAC_ENC_QUALITY (gst_flac_enc_quality_get_type ())
235 static GType
236 gst_flac_enc_quality_get_type (void)
237 {
238   static GType qtype = 0;
239
240   if (qtype == 0) {
241     static const GEnumValue values[] = {
242       {0, "0 - Fastest compression", "0"},
243       {1, "1", "1"},
244       {2, "2", "2"},
245       {3, "3", "3"},
246       {4, "4", "4"},
247       {5, "5 - Default", "5"},
248       {6, "6", "6"},
249       {7, "7", "7"},
250       {8, "8 - Highest compression", "8"},
251       {9, "9 - Insane", "9"},
252       {0, NULL, NULL}
253     };
254
255     qtype = g_enum_register_static ("GstFlacEncQuality", values);
256   }
257   return qtype;
258 }
259
260 static void
261 gst_flac_enc_base_init (gpointer g_class)
262 {
263   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
264
265   gst_element_class_add_pad_template (element_class,
266       gst_static_pad_template_get (&src_factory));
267   gst_element_class_add_pad_template (element_class,
268       gst_static_pad_template_get (&sink_factory));
269
270   gst_element_class_set_details_simple (element_class, "FLAC audio encoder",
271       "Codec/Encoder/Audio",
272       "Encodes audio with the FLAC lossless audio encoder",
273       "Wim Taymans <wim.taymans@chello.be>");
274
275   GST_DEBUG_CATEGORY_INIT (flacenc_debug, "flacenc", 0,
276       "Flac encoding element");
277 }
278
279 static void
280 gst_flac_enc_class_init (GstFlacEncClass * klass)
281 {
282   GObjectClass *gobject_class;
283   GstElementClass *gstelement_class;
284
285   gobject_class = (GObjectClass *) klass;
286   gstelement_class = (GstElementClass *) klass;
287
288   gobject_class->set_property = gst_flac_enc_set_property;
289   gobject_class->get_property = gst_flac_enc_get_property;
290   gobject_class->finalize = gst_flac_enc_finalize;
291
292   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QUALITY,
293       g_param_spec_enum ("quality",
294           "Quality",
295           "Speed versus compression tradeoff",
296           GST_TYPE_FLAC_ENC_QUALITY, DEFAULT_QUALITY,
297           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
298   g_object_class_install_property (G_OBJECT_CLASS (klass),
299       PROP_STREAMABLE_SUBSET, g_param_spec_boolean ("streamable-subset",
300           "Streamable subset",
301           "true to limit encoder to generating a Subset stream, else false",
302           TRUE,
303           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
304   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MID_SIDE_STEREO,
305       g_param_spec_boolean ("mid-side-stereo", "Do mid side stereo",
306           "Do mid side stereo (only for stereo input)",
307           flacenc_params[DEFAULT_QUALITY].mid_side,
308           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
309   g_object_class_install_property (G_OBJECT_CLASS (klass),
310       PROP_LOOSE_MID_SIDE_STEREO, g_param_spec_boolean ("loose-mid-side-stereo",
311           "Loose mid side stereo", "Loose mid side stereo",
312           flacenc_params[DEFAULT_QUALITY].loose_mid_side,
313           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
314   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BLOCKSIZE,
315       g_param_spec_uint ("blocksize", "Blocksize", "Blocksize in samples",
316           FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE,
317           flacenc_params[DEFAULT_QUALITY].blocksize,
318           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
319   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MAX_LPC_ORDER,
320       g_param_spec_uint ("max-lpc-order", "Max LPC order",
321           "Max LPC order; 0 => use only fixed predictors", 0,
322           FLAC__MAX_LPC_ORDER, flacenc_params[DEFAULT_QUALITY].max_lpc_order,
323           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
324   g_object_class_install_property (G_OBJECT_CLASS (klass),
325       PROP_QLP_COEFF_PRECISION, g_param_spec_uint ("qlp-coeff-precision",
326           "QLP coefficients precision",
327           "Precision in bits of quantized linear-predictor coefficients; 0 = automatic",
328           0, 32, flacenc_params[DEFAULT_QUALITY].qlp_coeff_precision,
329           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
330   g_object_class_install_property (G_OBJECT_CLASS (klass),
331       PROP_QLP_COEFF_PREC_SEARCH, g_param_spec_boolean ("qlp-coeff-prec-search",
332           "Do QLP coefficients precision search",
333           "false = use qlp_coeff_precision, "
334           "true = search around qlp_coeff_precision, take best",
335           flacenc_params[DEFAULT_QUALITY].qlp_coeff_prec_search,
336           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
337   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ESCAPE_CODING,
338       g_param_spec_boolean ("escape-coding", "Do Escape coding",
339           "search for escape codes in the entropy coding stage "
340           "for slightly better compression",
341           flacenc_params[DEFAULT_QUALITY].escape_coding,
342           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
343   g_object_class_install_property (G_OBJECT_CLASS (klass),
344       PROP_EXHAUSTIVE_MODEL_SEARCH,
345       g_param_spec_boolean ("exhaustive-model-search",
346           "Do exhaustive model search",
347           "do exhaustive search of LP coefficient quantization (expensive!)",
348           flacenc_params[DEFAULT_QUALITY].exhaustive_model_search,
349           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
350   g_object_class_install_property (G_OBJECT_CLASS (klass),
351       PROP_MIN_RESIDUAL_PARTITION_ORDER,
352       g_param_spec_uint ("min-residual-partition-order",
353           "Min residual partition order",
354           "Min residual partition order (above 4 doesn't usually help much)", 0,
355           16, flacenc_params[DEFAULT_QUALITY].min_residual_partition_order,
356           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
357   g_object_class_install_property (G_OBJECT_CLASS (klass),
358       PROP_MAX_RESIDUAL_PARTITION_ORDER,
359       g_param_spec_uint ("max-residual-partition-order",
360           "Max residual partition order",
361           "Max residual partition order (above 4 doesn't usually help much)", 0,
362           16, flacenc_params[DEFAULT_QUALITY].max_residual_partition_order,
363           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
364   g_object_class_install_property (G_OBJECT_CLASS (klass),
365       PROP_RICE_PARAMETER_SEARCH_DIST,
366       g_param_spec_uint ("rice-parameter-search-dist",
367           "rice_parameter_search_dist",
368           "0 = try only calc'd parameter k; else try all [k-dist..k+dist] "
369           "parameters, use best", 0, FLAC__MAX_RICE_PARTITION_ORDER,
370           flacenc_params[DEFAULT_QUALITY].rice_parameter_search_dist,
371           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
372
373   /**
374    * GstFlacEnc:padding
375    *
376    * Write a PADDING block with this length in bytes
377    *
378    * Since: 0.10.16
379    **/
380   g_object_class_install_property (G_OBJECT_CLASS (klass),
381       PROP_PADDING,
382       g_param_spec_uint ("padding",
383           "Padding",
384           "Write a PADDING block with this length in bytes", 0, G_MAXUINT,
385           DEFAULT_PADDING,
386           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
387
388   /**
389    * GstFlacEnc:seekpoints
390    *
391    * Write a SEEKTABLE block with a specific number of seekpoints
392    * or with a specific interval spacing.
393    *
394    * Since: 0.10.18
395    **/
396   g_object_class_install_property (G_OBJECT_CLASS (klass),
397       PROP_SEEKPOINTS,
398       g_param_spec_int ("seekpoints",
399           "Seekpoints",
400           "Add SEEKTABLE metadata (if > 0, number of entries, if < 0, interval in sec)",
401           -G_MAXINT, G_MAXINT,
402           DEFAULT_SEEKPOINTS,
403           G_PARAM_READWRITE | G_PARAM_CONSTRUCT | G_PARAM_STATIC_STRINGS));
404
405   gstelement_class->change_state = gst_flac_enc_change_state;
406 }
407
408 static void
409 gst_flac_enc_init (GstFlacEnc * flacenc, GstFlacEncClass * klass)
410 {
411   flacenc->sinkpad = gst_pad_new_from_static_template (&sink_factory, "sink");
412   gst_pad_set_chain_function (flacenc->sinkpad,
413       GST_DEBUG_FUNCPTR (gst_flac_enc_chain));
414   gst_pad_set_event_function (flacenc->sinkpad,
415       GST_DEBUG_FUNCPTR (gst_flac_enc_sink_event));
416   gst_pad_set_getcaps_function (flacenc->sinkpad,
417       GST_DEBUG_FUNCPTR (gst_flac_enc_sink_getcaps));
418   gst_pad_set_setcaps_function (flacenc->sinkpad,
419       GST_DEBUG_FUNCPTR (gst_flac_enc_sink_setcaps));
420   gst_element_add_pad (GST_ELEMENT (flacenc), flacenc->sinkpad);
421
422   flacenc->srcpad = gst_pad_new_from_static_template (&src_factory, "src");
423   gst_pad_use_fixed_caps (flacenc->srcpad);
424   gst_element_add_pad (GST_ELEMENT (flacenc), flacenc->srcpad);
425
426   flacenc->encoder = FLAC__stream_encoder_new ();
427
428   flacenc->offset = 0;
429   flacenc->samples_written = 0;
430   flacenc->channels = 0;
431   gst_flac_enc_update_quality (flacenc, DEFAULT_QUALITY);
432   flacenc->tags = gst_tag_list_new ();
433   flacenc->got_headers = FALSE;
434   flacenc->headers = NULL;
435   flacenc->last_flow = GST_FLOW_OK;
436 }
437
438 static void
439 gst_flac_enc_finalize (GObject * object)
440 {
441   GstFlacEnc *flacenc = GST_FLAC_ENC (object);
442
443   gst_tag_list_free (flacenc->tags);
444   FLAC__stream_encoder_delete (flacenc->encoder);
445
446   G_OBJECT_CLASS (parent_class)->finalize (object);
447 }
448
449 static void
450 add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
451 {
452   GList *comments;
453   GList *it;
454   GstFlacEnc *flacenc = GST_FLAC_ENC (user_data);
455
456   /* IMAGE and PREVIEW_IMAGE tags are already written
457    * differently, no need to store them inside the
458    * vorbiscomments too */
459   if (strcmp (tag, GST_TAG_IMAGE) == 0
460       || strcmp (tag, GST_TAG_PREVIEW_IMAGE) == 0)
461     return;
462
463   comments = gst_tag_to_vorbis_comments (list, tag);
464   for (it = comments; it != NULL; it = it->next) {
465     FLAC__StreamMetadata_VorbisComment_Entry commment_entry;
466
467     commment_entry.length = strlen (it->data);
468     commment_entry.entry = it->data;
469     FLAC__metadata_object_vorbiscomment_insert_comment (flacenc->meta[0],
470         flacenc->meta[0]->data.vorbis_comment.num_comments,
471         commment_entry, TRUE);
472     g_free (it->data);
473   }
474   g_list_free (comments);
475 }
476
477 static void
478 gst_flac_enc_set_metadata (GstFlacEnc * flacenc, guint64 total_samples)
479 {
480   const GstTagList *user_tags;
481   GstTagList *copy;
482   gint entries = 1;
483   gint n_images, n_preview_images;
484
485   g_return_if_fail (flacenc != NULL);
486   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (flacenc));
487   if ((flacenc->tags == NULL) && (user_tags == NULL)) {
488     return;
489   }
490   copy = gst_tag_list_merge (user_tags, flacenc->tags,
491       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
492   n_images = gst_tag_list_get_tag_size (copy, GST_TAG_IMAGE);
493   n_preview_images = gst_tag_list_get_tag_size (copy, GST_TAG_PREVIEW_IMAGE);
494
495   flacenc->meta =
496       g_new0 (FLAC__StreamMetadata *, 3 + n_images + n_preview_images);
497
498   flacenc->meta[0] =
499       FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT);
500   gst_tag_list_foreach (copy, add_one_tag, flacenc);
501
502   if (n_images + n_preview_images > 0) {
503     GstBuffer *buffer;
504     GstCaps *caps;
505     GstStructure *structure;
506     GstTagImageType image_type = GST_TAG_IMAGE_TYPE_NONE;
507     gint i;
508
509     for (i = 0; i < n_images + n_preview_images; i++) {
510       if (i < n_images) {
511         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_IMAGE, i, &buffer))
512           continue;
513       } else {
514         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_PREVIEW_IMAGE,
515                 i - n_images, &buffer))
516           continue;
517       }
518
519       flacenc->meta[entries] =
520           FLAC__metadata_object_new (FLAC__METADATA_TYPE_PICTURE);
521
522       caps = gst_buffer_get_caps (buffer);
523       structure = gst_caps_get_structure (caps, 0);
524
525       gst_structure_get (structure, "image-type", GST_TYPE_TAG_IMAGE_TYPE,
526           &image_type, NULL);
527       /* Convert to ID3v2 APIC image type */
528       if (image_type == GST_TAG_IMAGE_TYPE_NONE)
529         image_type = (i < n_images) ? 0x00 : 0x01;
530       else
531         image_type = image_type + 2;
532
533       FLAC__metadata_object_picture_set_data (flacenc->meta[entries],
534           GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), TRUE);
535       /* FIXME: There's no way to set the picture type in libFLAC */
536       flacenc->meta[entries]->data.picture.type = image_type;
537       FLAC__metadata_object_picture_set_mime_type (flacenc->meta[entries],
538           (char *) gst_structure_get_name (structure), TRUE);
539
540       gst_caps_unref (caps);
541       gst_buffer_unref (buffer);
542       entries++;
543     }
544   }
545
546   if (flacenc->seekpoints && total_samples != GST_CLOCK_TIME_NONE) {
547     gboolean res;
548     guint samples;
549
550     flacenc->meta[entries] =
551         FLAC__metadata_object_new (FLAC__METADATA_TYPE_SEEKTABLE);
552     if (flacenc->seekpoints > 0) {
553       res =
554           FLAC__metadata_object_seektable_template_append_spaced_points
555           (flacenc->meta[entries], flacenc->seekpoints, total_samples);
556     } else {
557       samples = -flacenc->seekpoints * flacenc->sample_rate;
558       res =
559           FLAC__metadata_object_seektable_template_append_spaced_points_by_samples
560           (flacenc->meta[entries], samples, total_samples);
561     }
562     if (!res) {
563       GST_DEBUG_OBJECT (flacenc, "adding seekpoint template %d failed",
564           flacenc->seekpoints);
565       FLAC__metadata_object_delete (flacenc->meta[1]);
566       flacenc->meta[entries] = NULL;
567     } else {
568       entries++;
569     }
570   } else if (flacenc->seekpoints && total_samples == GST_CLOCK_TIME_NONE) {
571     GST_WARNING_OBJECT (flacenc, "total time unknown; can not add seekpoints");
572   }
573
574   if (flacenc->padding > 0) {
575     flacenc->meta[entries] =
576         FLAC__metadata_object_new (FLAC__METADATA_TYPE_PADDING);
577     flacenc->meta[entries]->length = flacenc->padding;
578     entries++;
579   }
580
581   if (FLAC__stream_encoder_set_metadata (flacenc->encoder,
582           flacenc->meta, entries) != true)
583     g_warning ("Dude, i'm already initialized!");
584
585   gst_tag_list_free (copy);
586 }
587
588 static void
589 gst_flac_enc_caps_append_structure_with_widths (GstCaps * caps,
590     GstStructure * s)
591 {
592   GstStructure *tmp;
593   GValue list = { 0, };
594   GValue depth = { 0, };
595
596
597   tmp = gst_structure_copy (s);
598   gst_structure_set (tmp, "width", G_TYPE_INT, 8, "depth", G_TYPE_INT, 8, NULL);
599   gst_caps_append_structure (caps, tmp);
600
601   tmp = gst_structure_copy (s);
602
603   g_value_init (&depth, G_TYPE_INT);
604   g_value_init (&list, GST_TYPE_LIST);
605   g_value_set_int (&depth, 12);
606   gst_value_list_append_value (&list, &depth);
607   g_value_set_int (&depth, 16);
608   gst_value_list_append_value (&list, &depth);
609
610   gst_structure_set (tmp, "width", G_TYPE_INT, 16, NULL);
611   gst_structure_set_value (tmp, "depth", &list);
612   gst_caps_append_structure (caps, tmp);
613
614   g_value_reset (&list);
615
616   tmp = s;
617
618   g_value_set_int (&depth, 20);
619   gst_value_list_append_value (&list, &depth);
620   g_value_set_int (&depth, 24);
621   gst_value_list_append_value (&list, &depth);
622
623   gst_structure_set (tmp, "width", G_TYPE_INT, 32, NULL);
624   gst_structure_set_value (tmp, "depth", &list);
625   gst_caps_append_structure (caps, tmp);
626
627   g_value_unset (&list);
628   g_value_unset (&depth);
629 }
630
631 static GstCaps *
632 gst_flac_enc_sink_getcaps (GstPad * pad)
633 {
634   GstCaps *ret = NULL;
635
636   GST_OBJECT_LOCK (pad);
637
638   if (GST_PAD_CAPS (pad)) {
639     ret = gst_caps_ref (GST_PAD_CAPS (pad));
640   } else {
641     gint i, c;
642
643     ret = gst_caps_new_empty ();
644
645     gst_flac_enc_caps_append_structure_with_widths (ret,
646         gst_structure_new ("audio/x-raw-int",
647             "endianness", G_TYPE_INT, G_BYTE_ORDER,
648             "signed", G_TYPE_BOOLEAN, TRUE,
649             "rate", GST_TYPE_INT_RANGE, 1, 655350,
650             "channels", GST_TYPE_INT_RANGE, 1, 2, NULL));
651
652     for (i = 3; i <= 8; i++) {
653       GValue positions = { 0, };
654       GValue pos = { 0, };
655       GstStructure *s;
656
657       g_value_init (&positions, GST_TYPE_ARRAY);
658       g_value_init (&pos, GST_TYPE_AUDIO_CHANNEL_POSITION);
659
660       for (c = 0; c < i; c++) {
661         g_value_set_enum (&pos, channel_positions[i - 1][c]);
662         gst_value_array_append_value (&positions, &pos);
663       }
664       g_value_unset (&pos);
665
666       s = gst_structure_new ("audio/x-raw-int",
667           "endianness", G_TYPE_INT, G_BYTE_ORDER,
668           "signed", G_TYPE_BOOLEAN, TRUE,
669           "rate", GST_TYPE_INT_RANGE, 1, 655350,
670           "channels", G_TYPE_INT, i, NULL);
671       gst_structure_set_value (s, "channel-positions", &positions);
672       g_value_unset (&positions);
673
674       gst_flac_enc_caps_append_structure_with_widths (ret, s);
675     }
676   }
677
678   GST_OBJECT_UNLOCK (pad);
679
680   GST_DEBUG_OBJECT (pad, "Return caps %" GST_PTR_FORMAT, ret);
681
682   return ret;
683 }
684
685 static guint64
686 gst_flac_enc_query_peer_total_samples (GstFlacEnc * flacenc, GstPad * pad)
687 {
688   GstFormat fmt = GST_FORMAT_DEFAULT;
689   gint64 duration;
690
691   GST_DEBUG_OBJECT (flacenc, "querying peer for DEFAULT format duration");
692   if (gst_pad_query_peer_duration (pad, &fmt, &duration)
693       && fmt == GST_FORMAT_DEFAULT && duration != GST_CLOCK_TIME_NONE)
694     goto done;
695
696   fmt = GST_FORMAT_TIME;
697   GST_DEBUG_OBJECT (flacenc, "querying peer for TIME format duration");
698
699   if (gst_pad_query_peer_duration (pad, &fmt, &duration) &&
700       fmt == GST_FORMAT_TIME && duration != GST_CLOCK_TIME_NONE) {
701     GST_DEBUG_OBJECT (flacenc, "peer reported duration %" GST_TIME_FORMAT,
702         GST_TIME_ARGS (duration));
703     duration = GST_CLOCK_TIME_TO_FRAMES (duration, flacenc->sample_rate);
704
705     goto done;
706   }
707
708   GST_DEBUG_OBJECT (flacenc, "Upstream reported no total samples");
709   return GST_CLOCK_TIME_NONE;
710
711 done:
712   GST_DEBUG_OBJECT (flacenc,
713       "Upstream reported %" G_GUINT64_FORMAT " total samples", duration);
714
715   return duration;
716 }
717
718 static gboolean
719 gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps)
720 {
721   GstFlacEnc *flacenc;
722   GstStructure *structure;
723   guint64 total_samples = GST_CLOCK_TIME_NONE;
724   FLAC__StreamEncoderInitStatus init_status;
725   gint depth, chans, rate, width;
726
727   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
728
729   if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
730       FLAC__STREAM_ENCODER_UNINITIALIZED)
731     goto encoder_already_initialized;
732
733   structure = gst_caps_get_structure (caps, 0);
734
735   if (!gst_structure_get_int (structure, "channels", &chans) ||
736       !gst_structure_get_int (structure, "width", &width) ||
737       !gst_structure_get_int (structure, "depth", &depth) ||
738       !gst_structure_get_int (structure, "rate", &rate)) {
739     GST_DEBUG_OBJECT (flacenc, "incomplete caps: %" GST_PTR_FORMAT, caps);
740     return FALSE;
741   }
742
743   flacenc->channels = chans;
744   flacenc->width = width;
745   flacenc->depth = depth;
746   flacenc->sample_rate = rate;
747
748   caps = gst_caps_new_simple ("audio/x-flac",
749       "channels", G_TYPE_INT, flacenc->channels,
750       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
751
752   if (!gst_pad_set_caps (flacenc->srcpad, caps))
753     goto setting_src_caps_failed;
754
755   gst_caps_unref (caps);
756
757   total_samples = gst_flac_enc_query_peer_total_samples (flacenc, pad);
758
759   FLAC__stream_encoder_set_bits_per_sample (flacenc->encoder, flacenc->depth);
760   FLAC__stream_encoder_set_sample_rate (flacenc->encoder, flacenc->sample_rate);
761   FLAC__stream_encoder_set_channels (flacenc->encoder, flacenc->channels);
762
763   if (total_samples != GST_CLOCK_TIME_NONE)
764     FLAC__stream_encoder_set_total_samples_estimate (flacenc->encoder,
765         MIN (total_samples, G_GUINT64_CONSTANT (0x0FFFFFFFFF)));
766
767   gst_flac_enc_set_metadata (flacenc, total_samples);
768
769   init_status = FLAC__stream_encoder_init_stream (flacenc->encoder,
770       gst_flac_enc_write_callback, gst_flac_enc_seek_callback,
771       gst_flac_enc_tell_callback, NULL, flacenc);
772   if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
773     goto failed_to_initialize;
774
775   gst_object_unref (flacenc);
776
777   return TRUE;
778
779 encoder_already_initialized:
780   {
781     g_warning ("flac already initialized -- fixme allow this");
782     gst_object_unref (flacenc);
783     return FALSE;
784   }
785 setting_src_caps_failed:
786   {
787     GST_DEBUG_OBJECT (flacenc,
788         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
789     gst_caps_unref (caps);
790     gst_object_unref (flacenc);
791     return FALSE;
792   }
793 failed_to_initialize:
794   {
795     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
796         ("could not initialize encoder (wrong parameters?)"));
797     gst_object_unref (flacenc);
798     return FALSE;
799   }
800 }
801
802 static gboolean
803 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
804 {
805   flacenc->quality = quality;
806
807 #define DO_UPDATE(name, val, str)                                               \
808   G_STMT_START {                                                                \
809     if (FLAC__stream_encoder_get_##name (flacenc->encoder) !=                   \
810         flacenc_params[quality].val) {                                          \
811       FLAC__stream_encoder_set_##name (flacenc->encoder,                        \
812           flacenc_params[quality].val);                                         \
813       g_object_notify (G_OBJECT (flacenc), str);                                \
814     }                                                                           \
815   } G_STMT_END
816
817   g_object_freeze_notify (G_OBJECT (flacenc));
818
819   if (flacenc->channels == 2 || flacenc->channels == 0) {
820     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
821     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
822   }
823
824   DO_UPDATE (blocksize, blocksize, "blocksize");
825   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
826   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
827   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
828       "qlp_coeff_prec_search");
829   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
830   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
831       "exhaustive_model_search");
832   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
833       "min_residual_partition_order");
834   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
835       "max_residual_partition_order");
836   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
837       "rice_parameter_search_dist");
838
839 #undef DO_UPDATE
840
841   g_object_thaw_notify (G_OBJECT (flacenc));
842
843   return TRUE;
844 }
845
846 static FLAC__StreamEncoderSeekStatus
847 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
848     FLAC__uint64 absolute_byte_offset, void *client_data)
849 {
850   GstFlacEnc *flacenc;
851   GstEvent *event;
852   GstPad *peerpad;
853
854   flacenc = GST_FLAC_ENC (client_data);
855
856   if (flacenc->stopped)
857     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
858
859   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
860       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
861
862   if ((peerpad = gst_pad_get_peer (flacenc->srcpad))) {
863     gboolean ret = gst_pad_send_event (peerpad, event);
864
865     gst_object_unref (peerpad);
866
867     if (ret) {
868       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
869           (guint64) absolute_byte_offset, "succeeded");
870     } else {
871       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
872           (guint64) absolute_byte_offset, "failed");
873       return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
874     }
875   } else {
876     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
877         (guint64) absolute_byte_offset);
878   }
879
880   flacenc->offset = absolute_byte_offset;
881   return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
882 }
883
884 static void
885 notgst_value_array_append_buffer (GValue * array_val, GstBuffer * buf)
886 {
887   GValue value = { 0, };
888
889   g_value_init (&value, GST_TYPE_BUFFER);
890   /* copy buffer to avoid problems with circular refcounts */
891   buf = gst_buffer_copy (buf);
892   /* again, for good measure */
893   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
894   gst_value_set_buffer (&value, buf);
895   gst_buffer_unref (buf);
896   gst_value_array_append_value (array_val, &value);
897   g_value_unset (&value);
898 }
899
900 #define HDR_TYPE_STREAMINFO     0
901 #define HDR_TYPE_VORBISCOMMENT  4
902
903 static void
904 gst_flac_enc_process_stream_headers (GstFlacEnc * enc)
905 {
906   GstBuffer *vorbiscomment = NULL;
907   GstBuffer *streaminfo = NULL;
908   GstBuffer *marker = NULL;
909   GValue array = { 0, };
910   GstCaps *caps;
911   GList *l;
912
913   caps = gst_caps_new_simple ("audio/x-flac",
914       "channels", G_TYPE_INT, enc->channels,
915       "rate", G_TYPE_INT, enc->sample_rate, NULL);
916
917   for (l = enc->headers; l != NULL; l = l->next) {
918     const guint8 *data;
919     guint size;
920
921     /* mark buffers so oggmux will ignore them if it already muxed the
922      * header buffers from the streamheaders field in the caps */
923     l->data = gst_buffer_make_metadata_writable (GST_BUFFER (l->data));
924     GST_BUFFER_FLAG_SET (GST_BUFFER (l->data), GST_BUFFER_FLAG_IN_CAPS);
925
926     data = GST_BUFFER_DATA (GST_BUFFER_CAST (l->data));
927     size = GST_BUFFER_SIZE (GST_BUFFER_CAST (l->data));
928
929     /* find initial 4-byte marker which we need to skip later on */
930     if (size == 4 && memcmp (data, "fLaC", 4) == 0) {
931       marker = GST_BUFFER_CAST (l->data);
932     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_STREAMINFO) {
933       streaminfo = GST_BUFFER_CAST (l->data);
934     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_VORBISCOMMENT) {
935       vorbiscomment = GST_BUFFER_CAST (l->data);
936     }
937   }
938
939   if (marker == NULL || streaminfo == NULL || vorbiscomment == NULL) {
940     GST_WARNING_OBJECT (enc, "missing header %p %p %p, muxing into container "
941         "formats may be broken", marker, streaminfo, vorbiscomment);
942     goto push_headers;
943   }
944
945   g_value_init (&array, GST_TYPE_ARRAY);
946
947   /* add marker including STREAMINFO header */
948   {
949     GstBuffer *buf;
950     guint16 num;
951
952     /* minus one for the marker that is merged with streaminfo here */
953     num = g_list_length (enc->headers) - 1;
954
955     buf = gst_buffer_new_and_alloc (13 + GST_BUFFER_SIZE (streaminfo));
956     GST_BUFFER_DATA (buf)[0] = 0x7f;
957     memcpy (GST_BUFFER_DATA (buf) + 1, "FLAC", 4);
958     GST_BUFFER_DATA (buf)[5] = 0x01;    /* mapping version major */
959     GST_BUFFER_DATA (buf)[6] = 0x00;    /* mapping version minor */
960     GST_BUFFER_DATA (buf)[7] = (num & 0xFF00) >> 8;
961     GST_BUFFER_DATA (buf)[8] = (num & 0x00FF) >> 0;
962     memcpy (GST_BUFFER_DATA (buf) + 9, "fLaC", 4);
963     memcpy (GST_BUFFER_DATA (buf) + 13, GST_BUFFER_DATA (streaminfo),
964         GST_BUFFER_SIZE (streaminfo));
965     notgst_value_array_append_buffer (&array, buf);
966     gst_buffer_unref (buf);
967   }
968
969   /* add VORBISCOMMENT header */
970   notgst_value_array_append_buffer (&array, vorbiscomment);
971
972   /* add other headers, if there are any */
973   for (l = enc->headers; l != NULL; l = l->next) {
974     if (GST_BUFFER_CAST (l->data) != marker &&
975         GST_BUFFER_CAST (l->data) != streaminfo &&
976         GST_BUFFER_CAST (l->data) != vorbiscomment) {
977       notgst_value_array_append_buffer (&array, GST_BUFFER_CAST (l->data));
978     }
979   }
980
981   gst_structure_set_value (gst_caps_get_structure (caps, 0),
982       "streamheader", &array);
983   g_value_unset (&array);
984
985 push_headers:
986
987   gst_pad_set_caps (enc->srcpad, caps);
988
989   /* push header buffers; update caps, so when we push the first buffer the
990    * negotiated caps will change to caps that include the streamheader field */
991   for (l = enc->headers; l != NULL; l = l->next) {
992     GstBuffer *buf;
993
994     buf = GST_BUFFER (l->data);
995     gst_buffer_set_caps (buf, caps);
996     GST_LOG_OBJECT (enc, "Pushing header buffer, size %u bytes",
997         GST_BUFFER_SIZE (buf));
998     GST_MEMDUMP_OBJECT (enc, "header buffer", GST_BUFFER_DATA (buf),
999         GST_BUFFER_SIZE (buf));
1000     (void) gst_pad_push (enc->srcpad, buf);
1001     l->data = NULL;
1002   }
1003   g_list_free (enc->headers);
1004   enc->headers = NULL;
1005
1006   gst_caps_unref (caps);
1007 }
1008
1009 static FLAC__StreamEncoderWriteStatus
1010 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
1011     const FLAC__byte buffer[], size_t bytes,
1012     unsigned samples, unsigned current_frame, void *client_data)
1013 {
1014   GstFlowReturn ret = GST_FLOW_OK;
1015   GstFlacEnc *flacenc;
1016   GstBuffer *outbuf;
1017
1018   flacenc = GST_FLAC_ENC (client_data);
1019
1020   if (flacenc->stopped)
1021     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1022
1023   outbuf = gst_buffer_new_and_alloc (bytes);
1024   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
1025
1026   if (samples > 0 && flacenc->samples_written != (guint64) - 1) {
1027     guint64 granulepos;
1028
1029     GST_BUFFER_TIMESTAMP (outbuf) = flacenc->start_ts +
1030         GST_FRAMES_TO_CLOCK_TIME (flacenc->samples_written,
1031         flacenc->sample_rate);
1032     GST_BUFFER_DURATION (outbuf) =
1033         GST_FRAMES_TO_CLOCK_TIME (samples, flacenc->sample_rate);
1034     /* offset_end = granulepos for ogg muxer */
1035     granulepos =
1036         flacenc->granulepos_offset + flacenc->samples_written + samples;
1037     GST_BUFFER_OFFSET_END (outbuf) = granulepos;
1038     /* offset = timestamp corresponding to granulepos for ogg muxer
1039      * (see vorbisenc for a much more elaborate version of this) */
1040     GST_BUFFER_OFFSET (outbuf) =
1041         GST_FRAMES_TO_CLOCK_TIME (granulepos, flacenc->sample_rate);
1042   } else {
1043     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
1044     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
1045     GST_BUFFER_OFFSET (outbuf) =
1046         flacenc->samples_written * flacenc->width * flacenc->channels;
1047     GST_BUFFER_OFFSET_END (outbuf) = 0;
1048     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_IN_CAPS);
1049   }
1050
1051   /* we assume libflac passes us stuff neatly framed */
1052   if (!flacenc->got_headers) {
1053     if (samples == 0) {
1054       GST_DEBUG_OBJECT (flacenc, "Got header, queueing (%u bytes)",
1055           (guint) bytes);
1056       flacenc->headers = g_list_append (flacenc->headers, outbuf);
1057       /* note: it's important that we increase our byte offset */
1058       goto out;
1059     } else {
1060       GST_INFO_OBJECT (flacenc, "Non-header packet, we have all headers now");
1061       gst_flac_enc_process_stream_headers (flacenc);
1062       flacenc->got_headers = TRUE;
1063     }
1064   } else if (flacenc->got_headers && samples == 0) {
1065     GST_DEBUG_OBJECT (flacenc, "Fixing up headers at pos=%" G_GUINT64_FORMAT
1066         ", size=%u", flacenc->offset, (guint) bytes);
1067     GST_MEMDUMP_OBJECT (flacenc, "Presumed header fragment",
1068         GST_BUFFER_DATA (outbuf), GST_BUFFER_SIZE (outbuf));
1069   } else {
1070     GST_LOG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
1071         "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1072         samples, (guint) bytes, flacenc->offset);
1073   }
1074
1075   gst_buffer_set_caps (outbuf, GST_PAD_CAPS (flacenc->srcpad));
1076   ret = gst_pad_push (flacenc->srcpad, outbuf);
1077
1078   if (ret != GST_FLOW_OK)
1079     GST_DEBUG_OBJECT (flacenc, "flow: %s", gst_flow_get_name (ret));
1080
1081   flacenc->last_flow = ret;
1082
1083 out:
1084
1085   flacenc->offset += bytes;
1086   flacenc->samples_written += samples;
1087
1088   if (ret != GST_FLOW_OK)
1089     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1090
1091   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1092 }
1093
1094 static FLAC__StreamEncoderTellStatus
1095 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
1096     FLAC__uint64 * absolute_byte_offset, void *client_data)
1097 {
1098   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
1099
1100   *absolute_byte_offset = flacenc->offset;
1101
1102   return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
1103 }
1104
1105 static gboolean
1106 gst_flac_enc_sink_event (GstPad * pad, GstEvent * event)
1107 {
1108   GstFlacEnc *flacenc;
1109   GstTagList *taglist;
1110   gboolean ret = TRUE;
1111
1112   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
1113
1114   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
1115
1116   switch (GST_EVENT_TYPE (event)) {
1117     case GST_EVENT_NEWSEGMENT:{
1118       GstFormat format;
1119       gint64 start, stream_time;
1120
1121       if (flacenc->offset == 0) {
1122         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
1123             &stream_time);
1124       } else {
1125         start = -1;
1126         stream_time = -1;
1127       }
1128
1129       if (start > 0) {
1130         if (flacenc->offset > 0)
1131           GST_DEBUG ("Not handling mid-stream newsegment event");
1132         else
1133           GST_DEBUG ("Not handling newsegment event with non-zero start");
1134       } else {
1135         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1136             0, -1, 0);
1137
1138         ret = gst_pad_push_event (flacenc->srcpad, e);
1139       }
1140
1141       if (stream_time > 0) {
1142         GST_DEBUG ("Not handling non-zero stream time");
1143       }
1144
1145       gst_event_unref (event);
1146       /* don't push it downstream, we'll generate our own via seek to 0 */
1147       break;
1148     }
1149     case GST_EVENT_EOS:
1150       FLAC__stream_encoder_finish (flacenc->encoder);
1151       ret = gst_pad_event_default (pad, event);
1152       break;
1153     case GST_EVENT_TAG:
1154       if (flacenc->tags) {
1155         gst_event_parse_tag (event, &taglist);
1156         gst_tag_list_insert (flacenc->tags, taglist,
1157             gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
1158       } else {
1159         g_assert_not_reached ();
1160       }
1161       ret = gst_pad_event_default (pad, event);
1162       break;
1163     default:
1164       ret = gst_pad_event_default (pad, event);
1165       break;
1166   }
1167
1168   gst_object_unref (flacenc);
1169
1170   return ret;
1171 }
1172
1173 static gboolean
1174 gst_flac_enc_check_discont (GstFlacEnc * flacenc, GstClockTime expected,
1175     GstClockTime timestamp)
1176 {
1177   guint allowed_diff = GST_SECOND / flacenc->sample_rate / 2;
1178
1179   if ((timestamp + allowed_diff < expected)
1180       || (timestamp > expected + allowed_diff)) {
1181     GST_ELEMENT_WARNING (flacenc, STREAM, FORMAT, (NULL),
1182         ("Stream discontinuity detected (wanted %" GST_TIME_FORMAT " got %"
1183             GST_TIME_FORMAT "). The output will have wrong timestamps,"
1184             " consider using audiorate to handle discontinuities",
1185             GST_TIME_ARGS (expected), GST_TIME_ARGS (timestamp)));
1186     return TRUE;
1187   }
1188
1189   /* TODO: Do something to handle discontinuities in the stream. The FLAC encoder
1190    * unfortunately doesn't have any way to flush it's internal buffers */
1191
1192   return FALSE;
1193 }
1194
1195 static GstFlowReturn
1196 gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer)
1197 {
1198   GstFlacEnc *flacenc;
1199   FLAC__int32 *data;
1200   gulong insize;
1201   gint samples, width;
1202   gulong i;
1203   FLAC__bool res;
1204
1205   flacenc = GST_FLAC_ENC (GST_PAD_PARENT (pad));
1206
1207   /* make sure setcaps has been called and the encoder is set up */
1208   if (G_UNLIKELY (flacenc->depth == 0))
1209     return GST_FLOW_NOT_NEGOTIATED;
1210
1211   width = flacenc->width;
1212
1213   /* Save the timestamp of the first buffer. This will be later
1214    * used as offset for all following buffers */
1215   if (flacenc->start_ts == GST_CLOCK_TIME_NONE) {
1216     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1217       flacenc->start_ts = GST_BUFFER_TIMESTAMP (buffer);
1218       flacenc->granulepos_offset = gst_util_uint64_scale
1219           (GST_BUFFER_TIMESTAMP (buffer), flacenc->sample_rate, GST_SECOND);
1220     } else {
1221       flacenc->start_ts = 0;
1222       flacenc->granulepos_offset = 0;
1223     }
1224   }
1225
1226   /* Check if we have a continous stream, if not drop some samples or the buffer or
1227    * insert some silence samples */
1228   if (flacenc->next_ts != GST_CLOCK_TIME_NONE
1229       && GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1230     gst_flac_enc_check_discont (flacenc, flacenc->next_ts,
1231         GST_BUFFER_TIMESTAMP (buffer));
1232   }
1233
1234   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)
1235       && GST_BUFFER_DURATION_IS_VALID (buffer))
1236     flacenc->next_ts =
1237         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1238   else
1239     flacenc->next_ts = GST_CLOCK_TIME_NONE;
1240
1241   insize = GST_BUFFER_SIZE (buffer);
1242   samples = insize / (width >> 3);
1243
1244   data = g_malloc (samples * sizeof (FLAC__int32));
1245
1246   if (width == 8) {
1247     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
1248
1249     for (i = 0; i < samples; i++)
1250       data[i] = (FLAC__int32) indata[i];
1251   } else if (width == 16) {
1252     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
1253
1254     for (i = 0; i < samples; i++)
1255       data[i] = (FLAC__int32) indata[i];
1256   } else if (width == 32) {
1257     gint32 *indata = (gint32 *) GST_BUFFER_DATA (buffer);
1258
1259     for (i = 0; i < samples; i++)
1260       data[i] = (FLAC__int32) indata[i];
1261   } else {
1262     g_assert_not_reached ();
1263   }
1264
1265   gst_buffer_unref (buffer);
1266
1267   res = FLAC__stream_encoder_process_interleaved (flacenc->encoder,
1268       (const FLAC__int32 *) data, samples / flacenc->channels);
1269
1270   g_free (data);
1271
1272   if (!res) {
1273     if (flacenc->last_flow == GST_FLOW_OK)
1274       return GST_FLOW_ERROR;
1275     else
1276       return flacenc->last_flow;
1277   }
1278
1279   return GST_FLOW_OK;
1280 }
1281
1282 static void
1283 gst_flac_enc_set_property (GObject * object, guint prop_id,
1284     const GValue * value, GParamSpec * pspec)
1285 {
1286   GstFlacEnc *this = GST_FLAC_ENC (object);
1287
1288   GST_OBJECT_LOCK (this);
1289
1290   switch (prop_id) {
1291     case PROP_QUALITY:
1292       gst_flac_enc_update_quality (this, g_value_get_enum (value));
1293       break;
1294     case PROP_STREAMABLE_SUBSET:
1295       FLAC__stream_encoder_set_streamable_subset (this->encoder,
1296           g_value_get_boolean (value));
1297       break;
1298     case PROP_MID_SIDE_STEREO:
1299       FLAC__stream_encoder_set_do_mid_side_stereo (this->encoder,
1300           g_value_get_boolean (value));
1301       break;
1302     case PROP_LOOSE_MID_SIDE_STEREO:
1303       FLAC__stream_encoder_set_loose_mid_side_stereo (this->encoder,
1304           g_value_get_boolean (value));
1305       break;
1306     case PROP_BLOCKSIZE:
1307       FLAC__stream_encoder_set_blocksize (this->encoder,
1308           g_value_get_uint (value));
1309       break;
1310     case PROP_MAX_LPC_ORDER:
1311       FLAC__stream_encoder_set_max_lpc_order (this->encoder,
1312           g_value_get_uint (value));
1313       break;
1314     case PROP_QLP_COEFF_PRECISION:
1315       FLAC__stream_encoder_set_qlp_coeff_precision (this->encoder,
1316           g_value_get_uint (value));
1317       break;
1318     case PROP_QLP_COEFF_PREC_SEARCH:
1319       FLAC__stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
1320           g_value_get_boolean (value));
1321       break;
1322     case PROP_ESCAPE_CODING:
1323       FLAC__stream_encoder_set_do_escape_coding (this->encoder,
1324           g_value_get_boolean (value));
1325       break;
1326     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1327       FLAC__stream_encoder_set_do_exhaustive_model_search (this->encoder,
1328           g_value_get_boolean (value));
1329       break;
1330     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1331       FLAC__stream_encoder_set_min_residual_partition_order (this->encoder,
1332           g_value_get_uint (value));
1333       break;
1334     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1335       FLAC__stream_encoder_set_max_residual_partition_order (this->encoder,
1336           g_value_get_uint (value));
1337       break;
1338     case PROP_RICE_PARAMETER_SEARCH_DIST:
1339       FLAC__stream_encoder_set_rice_parameter_search_dist (this->encoder,
1340           g_value_get_uint (value));
1341       break;
1342     case PROP_PADDING:
1343       this->padding = g_value_get_uint (value);
1344       break;
1345     case PROP_SEEKPOINTS:
1346       this->seekpoints = g_value_get_int (value);
1347       break;
1348     default:
1349       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1350       break;
1351   }
1352
1353   GST_OBJECT_UNLOCK (this);
1354 }
1355
1356 static void
1357 gst_flac_enc_get_property (GObject * object, guint prop_id,
1358     GValue * value, GParamSpec * pspec)
1359 {
1360   GstFlacEnc *this = GST_FLAC_ENC (object);
1361
1362   GST_OBJECT_LOCK (this);
1363
1364   switch (prop_id) {
1365     case PROP_QUALITY:
1366       g_value_set_enum (value, this->quality);
1367       break;
1368     case PROP_STREAMABLE_SUBSET:
1369       g_value_set_boolean (value,
1370           FLAC__stream_encoder_get_streamable_subset (this->encoder));
1371       break;
1372     case PROP_MID_SIDE_STEREO:
1373       g_value_set_boolean (value,
1374           FLAC__stream_encoder_get_do_mid_side_stereo (this->encoder));
1375       break;
1376     case PROP_LOOSE_MID_SIDE_STEREO:
1377       g_value_set_boolean (value,
1378           FLAC__stream_encoder_get_loose_mid_side_stereo (this->encoder));
1379       break;
1380     case PROP_BLOCKSIZE:
1381       g_value_set_uint (value,
1382           FLAC__stream_encoder_get_blocksize (this->encoder));
1383       break;
1384     case PROP_MAX_LPC_ORDER:
1385       g_value_set_uint (value,
1386           FLAC__stream_encoder_get_max_lpc_order (this->encoder));
1387       break;
1388     case PROP_QLP_COEFF_PRECISION:
1389       g_value_set_uint (value,
1390           FLAC__stream_encoder_get_qlp_coeff_precision (this->encoder));
1391       break;
1392     case PROP_QLP_COEFF_PREC_SEARCH:
1393       g_value_set_boolean (value,
1394           FLAC__stream_encoder_get_do_qlp_coeff_prec_search (this->encoder));
1395       break;
1396     case PROP_ESCAPE_CODING:
1397       g_value_set_boolean (value,
1398           FLAC__stream_encoder_get_do_escape_coding (this->encoder));
1399       break;
1400     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1401       g_value_set_boolean (value,
1402           FLAC__stream_encoder_get_do_exhaustive_model_search (this->encoder));
1403       break;
1404     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1405       g_value_set_uint (value,
1406           FLAC__stream_encoder_get_min_residual_partition_order
1407           (this->encoder));
1408       break;
1409     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1410       g_value_set_uint (value,
1411           FLAC__stream_encoder_get_max_residual_partition_order
1412           (this->encoder));
1413       break;
1414     case PROP_RICE_PARAMETER_SEARCH_DIST:
1415       g_value_set_uint (value,
1416           FLAC__stream_encoder_get_rice_parameter_search_dist (this->encoder));
1417       break;
1418     case PROP_PADDING:
1419       g_value_set_uint (value, this->padding);
1420       break;
1421     case PROP_SEEKPOINTS:
1422       g_value_set_int (value, this->seekpoints);
1423       break;
1424     default:
1425       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1426       break;
1427   }
1428
1429   GST_OBJECT_UNLOCK (this);
1430 }
1431
1432 static GstStateChangeReturn
1433 gst_flac_enc_change_state (GstElement * element, GstStateChange transition)
1434 {
1435   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1436   GstFlacEnc *flacenc = GST_FLAC_ENC (element);
1437
1438   switch (transition) {
1439     case GST_STATE_CHANGE_NULL_TO_READY:
1440     case GST_STATE_CHANGE_READY_TO_PAUSED:
1441       flacenc->stopped = FALSE;
1442       flacenc->start_ts = GST_CLOCK_TIME_NONE;
1443       flacenc->next_ts = GST_CLOCK_TIME_NONE;
1444       flacenc->granulepos_offset = 0;
1445       break;
1446     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1447     default:
1448       break;
1449   }
1450
1451   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1452
1453   switch (transition) {
1454     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1455       break;
1456     case GST_STATE_CHANGE_PAUSED_TO_READY:
1457       if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
1458           FLAC__STREAM_ENCODER_UNINITIALIZED) {
1459         flacenc->stopped = TRUE;
1460         FLAC__stream_encoder_finish (flacenc->encoder);
1461       }
1462       flacenc->offset = 0;
1463       flacenc->samples_written = 0;
1464       flacenc->channels = 0;
1465       flacenc->depth = 0;
1466       flacenc->sample_rate = 0;
1467       if (flacenc->meta) {
1468         FLAC__metadata_object_delete (flacenc->meta[0]);
1469
1470         if (flacenc->meta[1])
1471           FLAC__metadata_object_delete (flacenc->meta[1]);
1472
1473         if (flacenc->meta[2])
1474           FLAC__metadata_object_delete (flacenc->meta[2]);
1475
1476         g_free (flacenc->meta);
1477         flacenc->meta = NULL;
1478       }
1479       g_list_foreach (flacenc->headers, (GFunc) gst_mini_object_unref, NULL);
1480       g_list_free (flacenc->headers);
1481       flacenc->headers = NULL;
1482       flacenc->got_headers = FALSE;
1483       flacenc->last_flow = GST_FLOW_OK;
1484       break;
1485     case GST_STATE_CHANGE_READY_TO_NULL:
1486     default:
1487       break;
1488   }
1489
1490   return ret;
1491 }