flacenc: Don't store image tags inside the vorbiscomments and the flac metadata
[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     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 || strcmp (tag, GST_TAG_PREVIEW_IMAGE))
460     return;
461
462   comments = gst_tag_to_vorbis_comments (list, tag);
463   for (it = comments; it != NULL; it = it->next) {
464     FLAC__StreamMetadata_VorbisComment_Entry commment_entry;
465
466     commment_entry.length = strlen (it->data);
467     commment_entry.entry = it->data;
468     FLAC__metadata_object_vorbiscomment_insert_comment (flacenc->meta[0],
469         flacenc->meta[0]->data.vorbis_comment.num_comments,
470         commment_entry, TRUE);
471     g_free (it->data);
472   }
473   g_list_free (comments);
474 }
475
476 static void
477 gst_flac_enc_set_metadata (GstFlacEnc * flacenc, guint64 total_samples)
478 {
479   const GstTagList *user_tags;
480   GstTagList *copy;
481   gint entries = 1;
482   gint n_images, n_preview_images;
483
484   g_return_if_fail (flacenc != NULL);
485   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (flacenc));
486   if ((flacenc->tags == NULL) && (user_tags == NULL)) {
487     return;
488   }
489   copy = gst_tag_list_merge (user_tags, flacenc->tags,
490       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
491   n_images = gst_tag_list_get_tag_size (copy, GST_TAG_IMAGE);
492   n_preview_images = gst_tag_list_get_tag_size (copy, GST_TAG_PREVIEW_IMAGE);
493
494   flacenc->meta =
495       g_new0 (FLAC__StreamMetadata *, 3 + n_images + n_preview_images);
496
497   flacenc->meta[0] =
498       FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT);
499   gst_tag_list_foreach (copy, add_one_tag, flacenc);
500
501   if (n_images + n_preview_images > 0) {
502     GstBuffer *buffer;
503     GstCaps *caps;
504     GstStructure *structure;
505     GstTagImageType image_type = GST_TAG_IMAGE_TYPE_NONE;
506     gint i;
507
508     for (i = 0; i < n_images + n_preview_images; i++) {
509       if (i < n_images) {
510         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_IMAGE, i, &buffer))
511           continue;
512       } else {
513         if (!gst_tag_list_get_buffer_index (copy, GST_TAG_PREVIEW_IMAGE,
514                 i - n_images, &buffer))
515           continue;
516       }
517
518       flacenc->meta[entries] =
519           FLAC__metadata_object_new (FLAC__METADATA_TYPE_PICTURE);
520
521       caps = gst_buffer_get_caps (buffer);
522       structure = gst_caps_get_structure (caps, 0);
523
524       gst_structure_get (structure, "image-type", GST_TYPE_TAG_IMAGE_TYPE,
525           &image_type, NULL);
526       /* Convert to ID3v2 APIC image type */
527       if (image_type == GST_TAG_IMAGE_TYPE_NONE)
528         image_type = (i < n_images) ? 0x00 : 0x01;
529       else
530         image_type = image_type + 2;
531
532       FLAC__metadata_object_picture_set_data (flacenc->meta[entries],
533           GST_BUFFER_DATA (buffer), GST_BUFFER_SIZE (buffer), TRUE);
534       /* FIXME: There's no way to set the picture type in libFLAC */
535       flacenc->meta[entries]->data.picture.type = image_type;
536       FLAC__metadata_object_picture_set_mime_type (flacenc->meta[entries],
537           (char *) gst_structure_get_name (structure), TRUE);
538
539       gst_caps_unref (caps);
540       gst_buffer_unref (buffer);
541       entries++;
542     }
543   }
544
545   if (flacenc->seekpoints && total_samples != GST_CLOCK_TIME_NONE) {
546     gboolean res;
547     guint samples;
548
549     flacenc->meta[entries] =
550         FLAC__metadata_object_new (FLAC__METADATA_TYPE_SEEKTABLE);
551     if (flacenc->seekpoints > 0) {
552       res =
553           FLAC__metadata_object_seektable_template_append_spaced_points
554           (flacenc->meta[entries], flacenc->seekpoints, total_samples);
555     } else {
556       samples = -flacenc->seekpoints * flacenc->sample_rate;
557       res =
558           FLAC__metadata_object_seektable_template_append_spaced_points_by_samples
559           (flacenc->meta[entries], samples, total_samples);
560     }
561     if (!res) {
562       GST_DEBUG_OBJECT (flacenc, "adding seekpoint template %d failed",
563           flacenc->seekpoints);
564       FLAC__metadata_object_delete (flacenc->meta[1]);
565       flacenc->meta[entries] = NULL;
566     } else {
567       entries++;
568     }
569   } else if (flacenc->seekpoints && total_samples == GST_CLOCK_TIME_NONE) {
570     GST_WARNING_OBJECT (flacenc, "total time unknown; can not add seekpoints");
571   }
572
573   if (flacenc->padding > 0) {
574     flacenc->meta[entries] =
575         FLAC__metadata_object_new (FLAC__METADATA_TYPE_PADDING);
576     flacenc->meta[entries]->length = flacenc->padding;
577     entries++;
578   }
579
580   if (FLAC__stream_encoder_set_metadata (flacenc->encoder,
581           flacenc->meta, entries) != true)
582     g_warning ("Dude, i'm already initialized!");
583
584   gst_tag_list_free (copy);
585 }
586
587 static void
588 gst_flac_enc_caps_append_structure_with_widths (GstCaps * caps,
589     GstStructure * s)
590 {
591   GstStructure *tmp;
592   GValue list = { 0, };
593   GValue depth = { 0, };
594
595
596   tmp = gst_structure_copy (s);
597   gst_structure_set (tmp, "width", G_TYPE_INT, 8, "depth", G_TYPE_INT, 8, NULL);
598   gst_caps_append_structure (caps, tmp);
599
600   tmp = gst_structure_copy (s);
601
602   g_value_init (&depth, G_TYPE_INT);
603   g_value_init (&list, GST_TYPE_LIST);
604   g_value_set_int (&depth, 12);
605   gst_value_list_append_value (&list, &depth);
606   g_value_set_int (&depth, 16);
607   gst_value_list_append_value (&list, &depth);
608
609   gst_structure_set (tmp, "width", G_TYPE_INT, 16, NULL);
610   gst_structure_set_value (tmp, "depth", &list);
611   gst_caps_append_structure (caps, tmp);
612
613   g_value_reset (&list);
614
615   tmp = s;
616
617   g_value_set_int (&depth, 20);
618   gst_value_list_append_value (&list, &depth);
619   g_value_set_int (&depth, 24);
620   gst_value_list_append_value (&list, &depth);
621
622   gst_structure_set (tmp, "width", G_TYPE_INT, 32, NULL);
623   gst_structure_set_value (tmp, "depth", &list);
624   gst_caps_append_structure (caps, tmp);
625
626   g_value_unset (&list);
627   g_value_unset (&depth);
628 }
629
630 static GstCaps *
631 gst_flac_enc_sink_getcaps (GstPad * pad)
632 {
633   GstCaps *ret = NULL;
634
635   GST_OBJECT_LOCK (pad);
636
637   if (GST_PAD_CAPS (pad)) {
638     ret = gst_caps_ref (GST_PAD_CAPS (pad));
639   } else {
640     gint i, c;
641
642     ret = gst_caps_new_empty ();
643
644     gst_flac_enc_caps_append_structure_with_widths (ret,
645         gst_structure_new ("audio/x-raw-int",
646             "endianness", G_TYPE_INT, G_BYTE_ORDER,
647             "signed", G_TYPE_BOOLEAN, TRUE,
648             "rate", GST_TYPE_INT_RANGE, 1, 655350,
649             "channels", GST_TYPE_INT_RANGE, 1, 2, NULL));
650
651     for (i = 3; i <= 8; i++) {
652       GValue positions = { 0, };
653       GValue pos = { 0, };
654       GstStructure *s;
655
656       g_value_init (&positions, GST_TYPE_ARRAY);
657       g_value_init (&pos, GST_TYPE_AUDIO_CHANNEL_POSITION);
658
659       for (c = 0; c < i; c++) {
660         g_value_set_enum (&pos, channel_positions[i - 1][c]);
661         gst_value_array_append_value (&positions, &pos);
662       }
663       g_value_unset (&pos);
664
665       s = gst_structure_new ("audio/x-raw-int",
666           "endianness", G_TYPE_INT, G_BYTE_ORDER,
667           "signed", G_TYPE_BOOLEAN, TRUE,
668           "rate", GST_TYPE_INT_RANGE, 1, 655350,
669           "channels", G_TYPE_INT, i, NULL);
670       gst_structure_set_value (s, "channel-positions", &positions);
671       g_value_unset (&positions);
672
673       gst_flac_enc_caps_append_structure_with_widths (ret, s);
674     }
675   }
676
677   GST_OBJECT_UNLOCK (pad);
678
679   GST_DEBUG_OBJECT (pad, "Return caps %" GST_PTR_FORMAT, ret);
680
681   return ret;
682 }
683
684 static guint64
685 gst_flac_enc_query_peer_total_samples (GstFlacEnc * flacenc, GstPad * pad)
686 {
687   GstFormat fmt = GST_FORMAT_DEFAULT;
688   gint64 duration;
689
690   GST_DEBUG_OBJECT (flacenc, "querying peer for DEFAULT format duration");
691   if (gst_pad_query_peer_duration (pad, &fmt, &duration)
692       && fmt == GST_FORMAT_DEFAULT && duration != GST_CLOCK_TIME_NONE)
693     goto done;
694
695   fmt = GST_FORMAT_TIME;
696   GST_DEBUG_OBJECT (flacenc, "querying peer for TIME format duration");
697
698   if (gst_pad_query_peer_duration (pad, &fmt, &duration) &&
699       fmt == GST_FORMAT_TIME && duration != GST_CLOCK_TIME_NONE) {
700     GST_DEBUG_OBJECT (flacenc, "peer reported duration %" GST_TIME_FORMAT,
701         GST_TIME_ARGS (duration));
702     duration = GST_CLOCK_TIME_TO_FRAMES (duration, flacenc->sample_rate);
703
704     goto done;
705   }
706
707   GST_DEBUG_OBJECT (flacenc, "Upstream reported no total samples");
708   return GST_CLOCK_TIME_NONE;
709
710 done:
711   GST_DEBUG_OBJECT (flacenc,
712       "Upstream reported %" G_GUINT64_FORMAT " total samples", duration);
713
714   return duration;
715 }
716
717 static gboolean
718 gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps)
719 {
720   GstFlacEnc *flacenc;
721   GstStructure *structure;
722   guint64 total_samples = GST_CLOCK_TIME_NONE;
723   FLAC__StreamEncoderInitStatus init_status;
724   gint depth, chans, rate, width;
725
726   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
727
728   if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
729       FLAC__STREAM_ENCODER_UNINITIALIZED)
730     goto encoder_already_initialized;
731
732   structure = gst_caps_get_structure (caps, 0);
733
734   if (!gst_structure_get_int (structure, "channels", &chans) ||
735       !gst_structure_get_int (structure, "width", &width) ||
736       !gst_structure_get_int (structure, "depth", &depth) ||
737       !gst_structure_get_int (structure, "rate", &rate)) {
738     GST_DEBUG_OBJECT (flacenc, "incomplete caps: %" GST_PTR_FORMAT, caps);
739     return FALSE;
740   }
741
742   flacenc->channels = chans;
743   flacenc->width = width;
744   flacenc->depth = depth;
745   flacenc->sample_rate = rate;
746
747   caps = gst_caps_new_simple ("audio/x-flac",
748       "channels", G_TYPE_INT, flacenc->channels,
749       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
750
751   if (!gst_pad_set_caps (flacenc->srcpad, caps))
752     goto setting_src_caps_failed;
753
754   gst_caps_unref (caps);
755
756   total_samples = gst_flac_enc_query_peer_total_samples (flacenc, pad);
757
758   FLAC__stream_encoder_set_bits_per_sample (flacenc->encoder, flacenc->depth);
759   FLAC__stream_encoder_set_sample_rate (flacenc->encoder, flacenc->sample_rate);
760   FLAC__stream_encoder_set_channels (flacenc->encoder, flacenc->channels);
761
762   if (total_samples != GST_CLOCK_TIME_NONE)
763     FLAC__stream_encoder_set_total_samples_estimate (flacenc->encoder,
764         MIN (total_samples, G_GUINT64_CONSTANT (0x0FFFFFFFFF)));
765
766   gst_flac_enc_set_metadata (flacenc, total_samples);
767
768   init_status = FLAC__stream_encoder_init_stream (flacenc->encoder,
769       gst_flac_enc_write_callback, gst_flac_enc_seek_callback,
770       gst_flac_enc_tell_callback, NULL, flacenc);
771   if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
772     goto failed_to_initialize;
773
774   gst_object_unref (flacenc);
775
776   return TRUE;
777
778 encoder_already_initialized:
779   {
780     g_warning ("flac already initialized -- fixme allow this");
781     gst_object_unref (flacenc);
782     return FALSE;
783   }
784 setting_src_caps_failed:
785   {
786     GST_DEBUG_OBJECT (flacenc,
787         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
788     gst_caps_unref (caps);
789     gst_object_unref (flacenc);
790     return FALSE;
791   }
792 failed_to_initialize:
793   {
794     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
795         ("could not initialize encoder (wrong parameters?)"));
796     gst_object_unref (flacenc);
797     return FALSE;
798   }
799 }
800
801 static gboolean
802 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
803 {
804   flacenc->quality = quality;
805
806 #define DO_UPDATE(name, val, str)                                               \
807   G_STMT_START {                                                                \
808     if (FLAC__stream_encoder_get_##name (flacenc->encoder) !=                   \
809         flacenc_params[quality].val) {                                          \
810       FLAC__stream_encoder_set_##name (flacenc->encoder,                        \
811           flacenc_params[quality].val);                                         \
812       g_object_notify (G_OBJECT (flacenc), str);                                \
813     }                                                                           \
814   } G_STMT_END
815
816   g_object_freeze_notify (G_OBJECT (flacenc));
817
818   if (flacenc->channels == 2 || flacenc->channels == 0) {
819     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
820     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
821   }
822
823   DO_UPDATE (blocksize, blocksize, "blocksize");
824   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
825   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
826   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
827       "qlp_coeff_prec_search");
828   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
829   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
830       "exhaustive_model_search");
831   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
832       "min_residual_partition_order");
833   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
834       "max_residual_partition_order");
835   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
836       "rice_parameter_search_dist");
837
838 #undef DO_UPDATE
839
840   g_object_thaw_notify (G_OBJECT (flacenc));
841
842   return TRUE;
843 }
844
845 static FLAC__StreamEncoderSeekStatus
846 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
847     FLAC__uint64 absolute_byte_offset, void *client_data)
848 {
849   GstFlacEnc *flacenc;
850   GstEvent *event;
851   GstPad *peerpad;
852
853   flacenc = GST_FLAC_ENC (client_data);
854
855   if (flacenc->stopped)
856     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
857
858   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
859       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
860
861   if ((peerpad = gst_pad_get_peer (flacenc->srcpad))) {
862     gboolean ret = gst_pad_send_event (peerpad, event);
863
864     gst_object_unref (peerpad);
865
866     if (ret) {
867       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
868           (guint64) absolute_byte_offset, "succeeded");
869     } else {
870       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s",
871           (guint64) absolute_byte_offset, "failed");
872       return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
873     }
874   } else {
875     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
876         (guint64) absolute_byte_offset);
877   }
878
879   flacenc->offset = absolute_byte_offset;
880   return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
881 }
882
883 static void
884 notgst_value_array_append_buffer (GValue * array_val, GstBuffer * buf)
885 {
886   GValue value = { 0, };
887
888   g_value_init (&value, GST_TYPE_BUFFER);
889   /* copy buffer to avoid problems with circular refcounts */
890   buf = gst_buffer_copy (buf);
891   /* again, for good measure */
892   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
893   gst_value_set_buffer (&value, buf);
894   gst_buffer_unref (buf);
895   gst_value_array_append_value (array_val, &value);
896   g_value_unset (&value);
897 }
898
899 #define HDR_TYPE_STREAMINFO     0
900 #define HDR_TYPE_VORBISCOMMENT  4
901
902 static void
903 gst_flac_enc_process_stream_headers (GstFlacEnc * enc)
904 {
905   GstBuffer *vorbiscomment = NULL;
906   GstBuffer *streaminfo = NULL;
907   GstBuffer *marker = NULL;
908   GValue array = { 0, };
909   GstCaps *caps;
910   GList *l;
911
912   caps = gst_caps_new_simple ("audio/x-flac",
913       "channels", G_TYPE_INT, enc->channels,
914       "rate", G_TYPE_INT, enc->sample_rate, NULL);
915
916   for (l = enc->headers; l != NULL; l = l->next) {
917     const guint8 *data;
918     guint size;
919
920     /* mark buffers so oggmux will ignore them if it already muxed the
921      * header buffers from the streamheaders field in the caps */
922     l->data = gst_buffer_make_metadata_writable (GST_BUFFER (l->data));
923     GST_BUFFER_FLAG_SET (GST_BUFFER (l->data), GST_BUFFER_FLAG_IN_CAPS);
924
925     data = GST_BUFFER_DATA (GST_BUFFER_CAST (l->data));
926     size = GST_BUFFER_SIZE (GST_BUFFER_CAST (l->data));
927
928     /* find initial 4-byte marker which we need to skip later on */
929     if (size == 4 && memcmp (data, "fLaC", 4) == 0) {
930       marker = GST_BUFFER_CAST (l->data);
931     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_STREAMINFO) {
932       streaminfo = GST_BUFFER_CAST (l->data);
933     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_VORBISCOMMENT) {
934       vorbiscomment = GST_BUFFER_CAST (l->data);
935     }
936   }
937
938   if (marker == NULL || streaminfo == NULL || vorbiscomment == NULL) {
939     GST_WARNING_OBJECT (enc, "missing header %p %p %p, muxing into container "
940         "formats may be broken", marker, streaminfo, vorbiscomment);
941     goto push_headers;
942   }
943
944   g_value_init (&array, GST_TYPE_ARRAY);
945
946   /* add marker including STREAMINFO header */
947   {
948     GstBuffer *buf;
949     guint16 num;
950
951     /* minus one for the marker that is merged with streaminfo here */
952     num = g_list_length (enc->headers) - 1;
953
954     buf = gst_buffer_new_and_alloc (13 + GST_BUFFER_SIZE (streaminfo));
955     GST_BUFFER_DATA (buf)[0] = 0x7f;
956     memcpy (GST_BUFFER_DATA (buf) + 1, "FLAC", 4);
957     GST_BUFFER_DATA (buf)[5] = 0x01;    /* mapping version major */
958     GST_BUFFER_DATA (buf)[6] = 0x00;    /* mapping version minor */
959     GST_BUFFER_DATA (buf)[7] = (num & 0xFF00) >> 8;
960     GST_BUFFER_DATA (buf)[8] = (num & 0x00FF) >> 0;
961     memcpy (GST_BUFFER_DATA (buf) + 9, "fLaC", 4);
962     memcpy (GST_BUFFER_DATA (buf) + 13, GST_BUFFER_DATA (streaminfo),
963         GST_BUFFER_SIZE (streaminfo));
964     notgst_value_array_append_buffer (&array, buf);
965     gst_buffer_unref (buf);
966   }
967
968   /* add VORBISCOMMENT header */
969   notgst_value_array_append_buffer (&array, vorbiscomment);
970
971   /* add other headers, if there are any */
972   for (l = enc->headers; l != NULL; l = l->next) {
973     if (GST_BUFFER_CAST (l->data) != marker &&
974         GST_BUFFER_CAST (l->data) != streaminfo &&
975         GST_BUFFER_CAST (l->data) != vorbiscomment) {
976       notgst_value_array_append_buffer (&array, GST_BUFFER_CAST (l->data));
977     }
978   }
979
980   gst_structure_set_value (gst_caps_get_structure (caps, 0),
981       "streamheader", &array);
982   g_value_unset (&array);
983
984 push_headers:
985
986   gst_pad_set_caps (enc->srcpad, caps);
987
988   /* push header buffers; update caps, so when we push the first buffer the
989    * negotiated caps will change to caps that include the streamheader field */
990   for (l = enc->headers; l != NULL; l = l->next) {
991     GstBuffer *buf;
992
993     buf = GST_BUFFER (l->data);
994     gst_buffer_set_caps (buf, caps);
995     GST_LOG_OBJECT (enc, "Pushing header buffer, size %u bytes",
996         GST_BUFFER_SIZE (buf));
997     GST_MEMDUMP_OBJECT (enc, "header buffer", GST_BUFFER_DATA (buf),
998         GST_BUFFER_SIZE (buf));
999     (void) gst_pad_push (enc->srcpad, buf);
1000     l->data = NULL;
1001   }
1002   g_list_free (enc->headers);
1003   enc->headers = NULL;
1004
1005   gst_caps_unref (caps);
1006 }
1007
1008 static FLAC__StreamEncoderWriteStatus
1009 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
1010     const FLAC__byte buffer[], size_t bytes,
1011     unsigned samples, unsigned current_frame, void *client_data)
1012 {
1013   GstFlowReturn ret = GST_FLOW_OK;
1014   GstFlacEnc *flacenc;
1015   GstBuffer *outbuf;
1016
1017   flacenc = GST_FLAC_ENC (client_data);
1018
1019   if (flacenc->stopped)
1020     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1021
1022   outbuf = gst_buffer_new_and_alloc (bytes);
1023   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
1024
1025   if (samples > 0 && flacenc->samples_written != (guint64) - 1) {
1026     guint64 granulepos;
1027
1028     GST_BUFFER_TIMESTAMP (outbuf) = flacenc->start_ts +
1029         GST_FRAMES_TO_CLOCK_TIME (flacenc->samples_written,
1030         flacenc->sample_rate);
1031     GST_BUFFER_DURATION (outbuf) =
1032         GST_FRAMES_TO_CLOCK_TIME (samples, flacenc->sample_rate);
1033     /* offset_end = granulepos for ogg muxer */
1034     granulepos =
1035         flacenc->granulepos_offset + flacenc->samples_written + samples;
1036     GST_BUFFER_OFFSET_END (outbuf) = granulepos;
1037     /* offset = timestamp corresponding to granulepos for ogg muxer
1038      * (see vorbisenc for a much more elaborate version of this) */
1039     GST_BUFFER_OFFSET (outbuf) =
1040         GST_FRAMES_TO_CLOCK_TIME (granulepos, flacenc->sample_rate);
1041   } else {
1042     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
1043     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
1044     GST_BUFFER_OFFSET (outbuf) =
1045         flacenc->samples_written * flacenc->width * flacenc->channels;
1046     GST_BUFFER_OFFSET_END (outbuf) = 0;
1047     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_IN_CAPS);
1048   }
1049
1050   /* we assume libflac passes us stuff neatly framed */
1051   if (!flacenc->got_headers) {
1052     if (samples == 0) {
1053       GST_DEBUG_OBJECT (flacenc, "Got header, queueing (%u bytes)",
1054           (guint) bytes);
1055       flacenc->headers = g_list_append (flacenc->headers, outbuf);
1056       /* note: it's important that we increase our byte offset */
1057       goto out;
1058     } else {
1059       GST_INFO_OBJECT (flacenc, "Non-header packet, we have all headers now");
1060       gst_flac_enc_process_stream_headers (flacenc);
1061       flacenc->got_headers = TRUE;
1062     }
1063   } else if (flacenc->got_headers && samples == 0) {
1064     GST_DEBUG_OBJECT (flacenc, "Fixing up headers at pos=%" G_GUINT64_FORMAT
1065         ", size=%u", flacenc->offset, (guint) bytes);
1066     GST_MEMDUMP_OBJECT (flacenc, "Presumed header fragment",
1067         GST_BUFFER_DATA (outbuf), GST_BUFFER_SIZE (outbuf));
1068   } else {
1069     GST_LOG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
1070         "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
1071         samples, (guint) bytes, flacenc->offset);
1072   }
1073
1074   gst_buffer_set_caps (outbuf, GST_PAD_CAPS (flacenc->srcpad));
1075   ret = gst_pad_push (flacenc->srcpad, outbuf);
1076
1077   if (ret != GST_FLOW_OK)
1078     GST_DEBUG_OBJECT (flacenc, "flow: %s", gst_flow_get_name (ret));
1079
1080   flacenc->last_flow = ret;
1081
1082 out:
1083
1084   flacenc->offset += bytes;
1085   flacenc->samples_written += samples;
1086
1087   if (ret != GST_FLOW_OK)
1088     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
1089
1090   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
1091 }
1092
1093 static FLAC__StreamEncoderTellStatus
1094 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
1095     FLAC__uint64 * absolute_byte_offset, void *client_data)
1096 {
1097   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
1098
1099   *absolute_byte_offset = flacenc->offset;
1100
1101   return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
1102 }
1103
1104 static gboolean
1105 gst_flac_enc_sink_event (GstPad * pad, GstEvent * event)
1106 {
1107   GstFlacEnc *flacenc;
1108   GstTagList *taglist;
1109   gboolean ret = TRUE;
1110
1111   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
1112
1113   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
1114
1115   switch (GST_EVENT_TYPE (event)) {
1116     case GST_EVENT_NEWSEGMENT:{
1117       GstFormat format;
1118       gint64 start, stream_time;
1119
1120       if (flacenc->offset == 0) {
1121         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
1122             &stream_time);
1123       } else {
1124         start = -1;
1125         stream_time = -1;
1126       }
1127
1128       if (start > 0) {
1129         if (flacenc->offset > 0)
1130           GST_DEBUG ("Not handling mid-stream newsegment event");
1131         else
1132           GST_DEBUG ("Not handling newsegment event with non-zero start");
1133       } else {
1134         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
1135             0, -1, 0);
1136
1137         ret = gst_pad_push_event (flacenc->srcpad, e);
1138       }
1139
1140       if (stream_time > 0) {
1141         GST_DEBUG ("Not handling non-zero stream time");
1142       }
1143
1144       gst_event_unref (event);
1145       /* don't push it downstream, we'll generate our own via seek to 0 */
1146       break;
1147     }
1148     case GST_EVENT_EOS:
1149       FLAC__stream_encoder_finish (flacenc->encoder);
1150       ret = gst_pad_event_default (pad, event);
1151       break;
1152     case GST_EVENT_TAG:
1153       if (flacenc->tags) {
1154         gst_event_parse_tag (event, &taglist);
1155         gst_tag_list_insert (flacenc->tags, taglist,
1156             gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
1157       } else {
1158         g_assert_not_reached ();
1159       }
1160       ret = gst_pad_event_default (pad, event);
1161       break;
1162     default:
1163       ret = gst_pad_event_default (pad, event);
1164       break;
1165   }
1166
1167   gst_object_unref (flacenc);
1168
1169   return ret;
1170 }
1171
1172 static gboolean
1173 gst_flac_enc_check_discont (GstFlacEnc * flacenc, GstClockTime expected,
1174     GstClockTime timestamp)
1175 {
1176   guint allowed_diff = GST_SECOND / flacenc->sample_rate / 2;
1177
1178   if ((timestamp + allowed_diff < expected)
1179       || (timestamp > expected + allowed_diff)) {
1180     GST_ELEMENT_WARNING (flacenc, STREAM, FORMAT, (NULL),
1181         ("Stream discontinuity detected (wanted %" GST_TIME_FORMAT " got %"
1182             GST_TIME_FORMAT "). The output will have wrong timestamps,"
1183             " consider using audiorate to handle discontinuities",
1184             GST_TIME_ARGS (expected), GST_TIME_ARGS (timestamp)));
1185     return TRUE;
1186   }
1187
1188   /* TODO: Do something to handle discontinuities in the stream. The FLAC encoder
1189    * unfortunately doesn't have any way to flush it's internal buffers */
1190
1191   return FALSE;
1192 }
1193
1194 static GstFlowReturn
1195 gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer)
1196 {
1197   GstFlacEnc *flacenc;
1198   FLAC__int32 *data;
1199   gulong insize;
1200   gint samples, width;
1201   gulong i;
1202   FLAC__bool res;
1203
1204   flacenc = GST_FLAC_ENC (GST_PAD_PARENT (pad));
1205
1206   /* make sure setcaps has been called and the encoder is set up */
1207   if (G_UNLIKELY (flacenc->depth == 0))
1208     return GST_FLOW_NOT_NEGOTIATED;
1209
1210   width = flacenc->width;
1211
1212   /* Save the timestamp of the first buffer. This will be later
1213    * used as offset for all following buffers */
1214   if (flacenc->start_ts == GST_CLOCK_TIME_NONE) {
1215     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1216       flacenc->start_ts = GST_BUFFER_TIMESTAMP (buffer);
1217       flacenc->granulepos_offset = gst_util_uint64_scale
1218           (GST_BUFFER_TIMESTAMP (buffer), flacenc->sample_rate, GST_SECOND);
1219     } else {
1220       flacenc->start_ts = 0;
1221       flacenc->granulepos_offset = 0;
1222     }
1223   }
1224
1225   /* Check if we have a continous stream, if not drop some samples or the buffer or
1226    * insert some silence samples */
1227   if (flacenc->next_ts != GST_CLOCK_TIME_NONE
1228       && GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1229     gst_flac_enc_check_discont (flacenc, flacenc->next_ts,
1230         GST_BUFFER_TIMESTAMP (buffer));
1231   }
1232
1233   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)
1234       && GST_BUFFER_DURATION_IS_VALID (buffer))
1235     flacenc->next_ts =
1236         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1237   else
1238     flacenc->next_ts = GST_CLOCK_TIME_NONE;
1239
1240   insize = GST_BUFFER_SIZE (buffer);
1241   samples = insize / (width >> 3);
1242
1243   data = g_malloc (samples * sizeof (FLAC__int32));
1244
1245   if (width == 8) {
1246     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
1247
1248     for (i = 0; i < samples; i++)
1249       data[i] = (FLAC__int32) indata[i];
1250   } else if (width == 16) {
1251     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
1252
1253     for (i = 0; i < samples; i++)
1254       data[i] = (FLAC__int32) indata[i];
1255   } else if (width == 32) {
1256     gint32 *indata = (gint32 *) GST_BUFFER_DATA (buffer);
1257
1258     for (i = 0; i < samples; i++)
1259       data[i] = (FLAC__int32) indata[i];
1260   } else {
1261     g_assert_not_reached ();
1262   }
1263
1264   gst_buffer_unref (buffer);
1265
1266   res = FLAC__stream_encoder_process_interleaved (flacenc->encoder,
1267       (const FLAC__int32 *) data, samples / flacenc->channels);
1268
1269   g_free (data);
1270
1271   if (!res) {
1272     if (flacenc->last_flow == GST_FLOW_OK)
1273       return GST_FLOW_ERROR;
1274     else
1275       return flacenc->last_flow;
1276   }
1277
1278   return GST_FLOW_OK;
1279 }
1280
1281 static void
1282 gst_flac_enc_set_property (GObject * object, guint prop_id,
1283     const GValue * value, GParamSpec * pspec)
1284 {
1285   GstFlacEnc *this = GST_FLAC_ENC (object);
1286
1287   GST_OBJECT_LOCK (this);
1288
1289   switch (prop_id) {
1290     case PROP_QUALITY:
1291       gst_flac_enc_update_quality (this, g_value_get_enum (value));
1292       break;
1293     case PROP_STREAMABLE_SUBSET:
1294       FLAC__stream_encoder_set_streamable_subset (this->encoder,
1295           g_value_get_boolean (value));
1296       break;
1297     case PROP_MID_SIDE_STEREO:
1298       FLAC__stream_encoder_set_do_mid_side_stereo (this->encoder,
1299           g_value_get_boolean (value));
1300       break;
1301     case PROP_LOOSE_MID_SIDE_STEREO:
1302       FLAC__stream_encoder_set_loose_mid_side_stereo (this->encoder,
1303           g_value_get_boolean (value));
1304       break;
1305     case PROP_BLOCKSIZE:
1306       FLAC__stream_encoder_set_blocksize (this->encoder,
1307           g_value_get_uint (value));
1308       break;
1309     case PROP_MAX_LPC_ORDER:
1310       FLAC__stream_encoder_set_max_lpc_order (this->encoder,
1311           g_value_get_uint (value));
1312       break;
1313     case PROP_QLP_COEFF_PRECISION:
1314       FLAC__stream_encoder_set_qlp_coeff_precision (this->encoder,
1315           g_value_get_uint (value));
1316       break;
1317     case PROP_QLP_COEFF_PREC_SEARCH:
1318       FLAC__stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
1319           g_value_get_boolean (value));
1320       break;
1321     case PROP_ESCAPE_CODING:
1322       FLAC__stream_encoder_set_do_escape_coding (this->encoder,
1323           g_value_get_boolean (value));
1324       break;
1325     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1326       FLAC__stream_encoder_set_do_exhaustive_model_search (this->encoder,
1327           g_value_get_boolean (value));
1328       break;
1329     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1330       FLAC__stream_encoder_set_min_residual_partition_order (this->encoder,
1331           g_value_get_uint (value));
1332       break;
1333     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1334       FLAC__stream_encoder_set_max_residual_partition_order (this->encoder,
1335           g_value_get_uint (value));
1336       break;
1337     case PROP_RICE_PARAMETER_SEARCH_DIST:
1338       FLAC__stream_encoder_set_rice_parameter_search_dist (this->encoder,
1339           g_value_get_uint (value));
1340       break;
1341     case PROP_PADDING:
1342       this->padding = g_value_get_uint (value);
1343       break;
1344     case PROP_SEEKPOINTS:
1345       this->seekpoints = g_value_get_int (value);
1346       break;
1347     default:
1348       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1349       break;
1350   }
1351
1352   GST_OBJECT_UNLOCK (this);
1353 }
1354
1355 static void
1356 gst_flac_enc_get_property (GObject * object, guint prop_id,
1357     GValue * value, GParamSpec * pspec)
1358 {
1359   GstFlacEnc *this = GST_FLAC_ENC (object);
1360
1361   GST_OBJECT_LOCK (this);
1362
1363   switch (prop_id) {
1364     case PROP_QUALITY:
1365       g_value_set_enum (value, this->quality);
1366       break;
1367     case PROP_STREAMABLE_SUBSET:
1368       g_value_set_boolean (value,
1369           FLAC__stream_encoder_get_streamable_subset (this->encoder));
1370       break;
1371     case PROP_MID_SIDE_STEREO:
1372       g_value_set_boolean (value,
1373           FLAC__stream_encoder_get_do_mid_side_stereo (this->encoder));
1374       break;
1375     case PROP_LOOSE_MID_SIDE_STEREO:
1376       g_value_set_boolean (value,
1377           FLAC__stream_encoder_get_loose_mid_side_stereo (this->encoder));
1378       break;
1379     case PROP_BLOCKSIZE:
1380       g_value_set_uint (value,
1381           FLAC__stream_encoder_get_blocksize (this->encoder));
1382       break;
1383     case PROP_MAX_LPC_ORDER:
1384       g_value_set_uint (value,
1385           FLAC__stream_encoder_get_max_lpc_order (this->encoder));
1386       break;
1387     case PROP_QLP_COEFF_PRECISION:
1388       g_value_set_uint (value,
1389           FLAC__stream_encoder_get_qlp_coeff_precision (this->encoder));
1390       break;
1391     case PROP_QLP_COEFF_PREC_SEARCH:
1392       g_value_set_boolean (value,
1393           FLAC__stream_encoder_get_do_qlp_coeff_prec_search (this->encoder));
1394       break;
1395     case PROP_ESCAPE_CODING:
1396       g_value_set_boolean (value,
1397           FLAC__stream_encoder_get_do_escape_coding (this->encoder));
1398       break;
1399     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1400       g_value_set_boolean (value,
1401           FLAC__stream_encoder_get_do_exhaustive_model_search (this->encoder));
1402       break;
1403     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1404       g_value_set_uint (value,
1405           FLAC__stream_encoder_get_min_residual_partition_order
1406           (this->encoder));
1407       break;
1408     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1409       g_value_set_uint (value,
1410           FLAC__stream_encoder_get_max_residual_partition_order
1411           (this->encoder));
1412       break;
1413     case PROP_RICE_PARAMETER_SEARCH_DIST:
1414       g_value_set_uint (value,
1415           FLAC__stream_encoder_get_rice_parameter_search_dist (this->encoder));
1416       break;
1417     case PROP_PADDING:
1418       g_value_set_uint (value, this->padding);
1419       break;
1420     case PROP_SEEKPOINTS:
1421       g_value_set_int (value, this->seekpoints);
1422       break;
1423     default:
1424       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1425       break;
1426   }
1427
1428   GST_OBJECT_UNLOCK (this);
1429 }
1430
1431 static GstStateChangeReturn
1432 gst_flac_enc_change_state (GstElement * element, GstStateChange transition)
1433 {
1434   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1435   GstFlacEnc *flacenc = GST_FLAC_ENC (element);
1436
1437   switch (transition) {
1438     case GST_STATE_CHANGE_NULL_TO_READY:
1439     case GST_STATE_CHANGE_READY_TO_PAUSED:
1440       flacenc->stopped = FALSE;
1441       flacenc->start_ts = GST_CLOCK_TIME_NONE;
1442       flacenc->next_ts = GST_CLOCK_TIME_NONE;
1443       flacenc->granulepos_offset = 0;
1444       break;
1445     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1446     default:
1447       break;
1448   }
1449
1450   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1451
1452   switch (transition) {
1453     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1454       break;
1455     case GST_STATE_CHANGE_PAUSED_TO_READY:
1456       if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
1457           FLAC__STREAM_ENCODER_UNINITIALIZED) {
1458         flacenc->stopped = TRUE;
1459         FLAC__stream_encoder_finish (flacenc->encoder);
1460       }
1461       flacenc->offset = 0;
1462       flacenc->samples_written = 0;
1463       flacenc->channels = 0;
1464       flacenc->depth = 0;
1465       flacenc->sample_rate = 0;
1466       if (flacenc->meta) {
1467         FLAC__metadata_object_delete (flacenc->meta[0]);
1468
1469         if (flacenc->meta[1])
1470           FLAC__metadata_object_delete (flacenc->meta[1]);
1471
1472         if (flacenc->meta[2])
1473           FLAC__metadata_object_delete (flacenc->meta[2]);
1474
1475         g_free (flacenc->meta);
1476         flacenc->meta = NULL;
1477       }
1478       g_list_foreach (flacenc->headers, (GFunc) gst_mini_object_unref, NULL);
1479       g_list_free (flacenc->headers);
1480       flacenc->headers = NULL;
1481       flacenc->got_headers = FALSE;
1482       flacenc->last_flow = GST_FLOW_OK;
1483       break;
1484     case GST_STATE_CHANGE_READY_TO_NULL:
1485     default:
1486       break;
1487   }
1488
1489   return ret;
1490 }