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