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