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