flac: Implement preset interface
[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   if (gst_pad_query_peer_duration (pad, &fmt, &duration)
563       && fmt == GST_FORMAT_DEFAULT && duration != GST_CLOCK_TIME_NONE)
564     goto done;
565
566   fmt = GST_FORMAT_TIME;
567
568   if (gst_pad_query_peer_duration (pad, &fmt, &duration) &&
569       fmt == GST_FORMAT_TIME && duration != GST_CLOCK_TIME_NONE) {
570     duration = GST_FRAMES_TO_CLOCK_TIME (duration, flacenc->sample_rate);
571
572     goto done;
573   }
574
575   GST_DEBUG_OBJECT (flacenc, "Upstream reported no total samples");
576   return GST_CLOCK_TIME_NONE;
577
578 done:
579   GST_DEBUG_OBJECT (flacenc,
580       "Upstream reported %" G_GUINT64_FORMAT " total samples", duration);
581
582   return duration;
583 }
584
585 static gboolean
586 gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps)
587 {
588   GstFlacEnc *flacenc;
589   GstStructure *structure;
590   guint64 total_samples = GST_CLOCK_TIME_NONE;
591   FLAC__StreamEncoderInitStatus init_status;
592   gint depth, chans, rate, width;
593
594   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
595
596   if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
597       FLAC__STREAM_ENCODER_UNINITIALIZED)
598     goto encoder_already_initialized;
599
600   structure = gst_caps_get_structure (caps, 0);
601
602   if (!gst_structure_get_int (structure, "channels", &chans) ||
603       !gst_structure_get_int (structure, "width", &width) ||
604       !gst_structure_get_int (structure, "depth", &depth) ||
605       !gst_structure_get_int (structure, "rate", &rate)) {
606     GST_DEBUG_OBJECT (flacenc, "incomplete caps: %" GST_PTR_FORMAT, caps);
607     return FALSE;
608   }
609
610   flacenc->channels = chans;
611   flacenc->width = width;
612   flacenc->depth = depth;
613   flacenc->sample_rate = rate;
614
615   caps = gst_caps_new_simple ("audio/x-flac",
616       "channels", G_TYPE_INT, flacenc->channels,
617       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
618
619   if (!gst_pad_set_caps (flacenc->srcpad, caps))
620     goto setting_src_caps_failed;
621
622   gst_caps_unref (caps);
623
624   total_samples = gst_flac_enc_query_peer_total_samples (flacenc, pad);
625
626   FLAC__stream_encoder_set_bits_per_sample (flacenc->encoder, flacenc->depth);
627   FLAC__stream_encoder_set_sample_rate (flacenc->encoder, flacenc->sample_rate);
628   FLAC__stream_encoder_set_channels (flacenc->encoder, flacenc->channels);
629
630   if (total_samples != GST_CLOCK_TIME_NONE)
631     FLAC__stream_encoder_set_total_samples_estimate (flacenc->encoder,
632         total_samples);
633
634   gst_flac_enc_set_metadata (flacenc);
635
636   init_status = FLAC__stream_encoder_init_stream (flacenc->encoder,
637       gst_flac_enc_write_callback, gst_flac_enc_seek_callback,
638       gst_flac_enc_tell_callback, NULL, flacenc);
639   if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
640     goto failed_to_initialize;
641
642   gst_object_unref (flacenc);
643
644   return TRUE;
645
646 encoder_already_initialized:
647   {
648     g_warning ("flac already initialized -- fixme allow this");
649     gst_object_unref (flacenc);
650     return FALSE;
651   }
652 setting_src_caps_failed:
653   {
654     GST_DEBUG_OBJECT (flacenc,
655         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
656     gst_caps_unref (caps);
657     gst_object_unref (flacenc);
658     return FALSE;
659   }
660 failed_to_initialize:
661   {
662     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
663         ("could not initialize encoder (wrong parameters?)"));
664     gst_object_unref (flacenc);
665     return FALSE;
666   }
667 }
668
669 static gboolean
670 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
671 {
672   flacenc->quality = quality;
673
674 #define DO_UPDATE(name, val, str)                                               \
675   G_STMT_START {                                                                \
676     if (FLAC__stream_encoder_get_##name (flacenc->encoder) !=                   \
677         flacenc_params[quality].val) {                                          \
678       FLAC__stream_encoder_set_##name (flacenc->encoder,                        \
679           flacenc_params[quality].val);                                         \
680       g_object_notify (G_OBJECT (flacenc), str);                                \
681     }                                                                           \
682   } G_STMT_END
683
684   g_object_freeze_notify (G_OBJECT (flacenc));
685
686   if (flacenc->channels == 2 || flacenc->channels == 0) {
687     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
688     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
689   }
690
691   DO_UPDATE (blocksize, blocksize, "blocksize");
692   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
693   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
694   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
695       "qlp_coeff_prec_search");
696   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
697   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
698       "exhaustive_model_search");
699   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
700       "min_residual_partition_order");
701   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
702       "max_residual_partition_order");
703   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
704       "rice_parameter_search_dist");
705
706 #undef DO_UPDATE
707
708   g_object_thaw_notify (G_OBJECT (flacenc));
709
710   return TRUE;
711 }
712
713 static FLAC__StreamEncoderSeekStatus
714 gst_flac_enc_seek_callback (const FLAC__StreamEncoder * encoder,
715     FLAC__uint64 absolute_byte_offset, void *client_data)
716 {
717   GstFlacEnc *flacenc;
718   GstEvent *event;
719   GstPad *peerpad;
720
721   flacenc = GST_FLAC_ENC (client_data);
722
723   if (flacenc->stopped)
724     return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
725
726   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
727       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
728
729   if ((peerpad = gst_pad_get_peer (flacenc->srcpad))) {
730     gboolean ret = gst_pad_send_event (peerpad, event);
731
732     gst_object_unref (peerpad);
733
734     if (ret) {
735       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
736           "succeeded");
737     } else {
738       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
739           "failed");
740       return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
741     }
742   } else {
743     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
744         absolute_byte_offset);
745   }
746
747   flacenc->offset = absolute_byte_offset;
748   return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
749 }
750
751 static void
752 notgst_value_array_append_buffer (GValue * array_val, GstBuffer * buf)
753 {
754   GValue value = { 0, };
755
756   g_value_init (&value, GST_TYPE_BUFFER);
757   /* copy buffer to avoid problems with circular refcounts */
758   buf = gst_buffer_copy (buf);
759   /* again, for good measure */
760   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
761   gst_value_set_buffer (&value, buf);
762   gst_buffer_unref (buf);
763   gst_value_array_append_value (array_val, &value);
764   g_value_unset (&value);
765 }
766
767 #define HDR_TYPE_STREAMINFO     0
768 #define HDR_TYPE_VORBISCOMMENT  4
769
770 static void
771 gst_flac_enc_process_stream_headers (GstFlacEnc * enc)
772 {
773   GstBuffer *vorbiscomment = NULL;
774   GstBuffer *streaminfo = NULL;
775   GstBuffer *marker = NULL;
776   GValue array = { 0, };
777   GstCaps *caps;
778   GList *l;
779
780   caps = gst_caps_new_simple ("audio/x-flac",
781       "channels", G_TYPE_INT, enc->channels,
782       "rate", G_TYPE_INT, enc->sample_rate, NULL);
783
784   for (l = enc->headers; l != NULL; l = l->next) {
785     const guint8 *data;
786     guint size;
787
788     /* mark buffers so oggmux will ignore them if it already muxed the
789      * header buffers from the streamheaders field in the caps */
790     l->data = gst_buffer_make_metadata_writable (GST_BUFFER (l->data));
791     GST_BUFFER_FLAG_SET (GST_BUFFER (l->data), GST_BUFFER_FLAG_IN_CAPS);
792
793     data = GST_BUFFER_DATA (GST_BUFFER_CAST (l->data));
794     size = GST_BUFFER_SIZE (GST_BUFFER_CAST (l->data));
795
796     /* find initial 4-byte marker which we need to skip later on */
797     if (size == 4 && memcmp (data, "fLaC", 4) == 0) {
798       marker = GST_BUFFER_CAST (l->data);
799     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_STREAMINFO) {
800       streaminfo = GST_BUFFER_CAST (l->data);
801     } else if (size > 1 && (data[0] & 0x7f) == HDR_TYPE_VORBISCOMMENT) {
802       vorbiscomment = GST_BUFFER_CAST (l->data);
803     }
804   }
805
806   if (marker == NULL || streaminfo == NULL || vorbiscomment == NULL) {
807     GST_WARNING_OBJECT (enc, "missing header %p %p %p, muxing into container "
808         "formats may be broken", marker, streaminfo, vorbiscomment);
809     goto push_headers;
810   }
811
812   g_value_init (&array, GST_TYPE_ARRAY);
813
814   /* add marker including STREAMINFO header */
815   {
816     GstBuffer *buf;
817     guint16 num;
818
819     /* minus one for the marker that is merged with streaminfo here */
820     num = g_list_length (enc->headers) - 1;
821
822     buf = gst_buffer_new_and_alloc (13 + GST_BUFFER_SIZE (streaminfo));
823     GST_BUFFER_DATA (buf)[0] = 0x7f;
824     memcpy (GST_BUFFER_DATA (buf) + 1, "FLAC", 4);
825     GST_BUFFER_DATA (buf)[5] = 0x01;    /* mapping version major */
826     GST_BUFFER_DATA (buf)[6] = 0x00;    /* mapping version minor */
827     GST_BUFFER_DATA (buf)[7] = (num & 0xFF00) >> 8;
828     GST_BUFFER_DATA (buf)[8] = (num & 0x00FF) >> 0;
829     memcpy (GST_BUFFER_DATA (buf) + 9, "fLaC", 4);
830     memcpy (GST_BUFFER_DATA (buf) + 13, GST_BUFFER_DATA (streaminfo),
831         GST_BUFFER_SIZE (streaminfo));
832     notgst_value_array_append_buffer (&array, buf);
833     gst_buffer_unref (buf);
834   }
835
836   /* add VORBISCOMMENT header */
837   notgst_value_array_append_buffer (&array, vorbiscomment);
838
839   /* add other headers, if there are any */
840   for (l = enc->headers; l != NULL; l = l->next) {
841     if (GST_BUFFER_CAST (l->data) != marker &&
842         GST_BUFFER_CAST (l->data) != streaminfo &&
843         GST_BUFFER_CAST (l->data) != vorbiscomment) {
844       notgst_value_array_append_buffer (&array, GST_BUFFER_CAST (l->data));
845     }
846   }
847
848   gst_structure_set_value (gst_caps_get_structure (caps, 0),
849       "streamheader", &array);
850   g_value_unset (&array);
851
852 push_headers:
853
854   gst_pad_set_caps (enc->srcpad, caps);
855
856   /* push header buffers; update caps, so when we push the first buffer the
857    * negotiated caps will change to caps that include the streamheader field */
858   for (l = enc->headers; l != NULL; l = l->next) {
859     GstBuffer *buf;
860
861     buf = GST_BUFFER (l->data);
862     gst_buffer_set_caps (buf, caps);
863     GST_LOG ("Pushing header buffer, size %u bytes", GST_BUFFER_SIZE (buf));
864     (void) gst_pad_push (enc->srcpad, buf);
865     l->data = NULL;
866   }
867   g_list_free (enc->headers);
868   enc->headers = NULL;
869
870   gst_caps_unref (caps);
871 }
872
873 static FLAC__StreamEncoderWriteStatus
874 gst_flac_enc_write_callback (const FLAC__StreamEncoder * encoder,
875     const FLAC__byte buffer[], size_t bytes,
876     unsigned samples, unsigned current_frame, void *client_data)
877 {
878   GstFlowReturn ret = GST_FLOW_OK;
879   GstFlacEnc *flacenc;
880   GstBuffer *outbuf;
881
882   flacenc = GST_FLAC_ENC (client_data);
883
884   if (flacenc->stopped)
885     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
886
887   outbuf = gst_buffer_new_and_alloc (bytes);
888   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
889
890   if (samples > 0 && flacenc->samples_written != (guint64) - 1) {
891     guint64 granulepos;
892
893     GST_BUFFER_TIMESTAMP (outbuf) = flacenc->start_ts +
894         GST_FRAMES_TO_CLOCK_TIME (flacenc->samples_written,
895         flacenc->sample_rate);
896     GST_BUFFER_DURATION (outbuf) =
897         GST_FRAMES_TO_CLOCK_TIME (samples, flacenc->sample_rate);
898     /* offset_end = granulepos for ogg muxer */
899     granulepos =
900         flacenc->granulepos_offset + flacenc->samples_written + samples;
901     GST_BUFFER_OFFSET_END (outbuf) = granulepos;
902     /* offset = timestamp corresponding to granulepos for ogg muxer
903      * (see vorbisenc for a much more elaborate version of this) */
904     GST_BUFFER_OFFSET (outbuf) =
905         GST_FRAMES_TO_CLOCK_TIME (granulepos, flacenc->sample_rate);
906   } else {
907     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
908     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
909     GST_BUFFER_OFFSET (outbuf) =
910         flacenc->samples_written * flacenc->width * flacenc->channels;
911     GST_BUFFER_OFFSET_END (outbuf) = 0;
912     GST_BUFFER_FLAG_SET (outbuf, GST_BUFFER_FLAG_IN_CAPS);
913   }
914
915   /* we assume libflac passes us stuff neatly framed */
916   if (!flacenc->got_headers) {
917     if (samples == 0) {
918       GST_DEBUG_OBJECT (flacenc, "Got header, queueing (%u bytes)",
919           (guint) bytes);
920       flacenc->headers = g_list_append (flacenc->headers, outbuf);
921       /* note: it's important that we increase our byte offset */
922       goto out;
923     } else {
924       GST_INFO_OBJECT (flacenc, "Non-header packet, we have all headers now");
925       gst_flac_enc_process_stream_headers (flacenc);
926       flacenc->got_headers = TRUE;
927     }
928   } else if (flacenc->got_headers && samples == 0) {
929     GST_WARNING_OBJECT (flacenc, "Got header packet after data packets");
930   }
931
932   GST_LOG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
933       "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
934       samples, (guint) bytes, flacenc->offset);
935
936   gst_buffer_set_caps (outbuf, GST_PAD_CAPS (flacenc->srcpad));
937   ret = gst_pad_push (flacenc->srcpad, outbuf);
938
939   if (ret != GST_FLOW_OK)
940     GST_DEBUG_OBJECT (flacenc, "flow: %s", gst_flow_get_name (ret));
941
942   flacenc->last_flow = ret;
943
944 out:
945
946   flacenc->offset += bytes;
947   flacenc->samples_written += samples;
948
949   if (GST_FLOW_IS_FATAL (ret) || ret == GST_FLOW_NOT_LINKED)
950     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
951
952   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
953 }
954
955 static FLAC__StreamEncoderTellStatus
956 gst_flac_enc_tell_callback (const FLAC__StreamEncoder * encoder,
957     FLAC__uint64 * absolute_byte_offset, void *client_data)
958 {
959   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
960
961   *absolute_byte_offset = flacenc->offset;
962
963   return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
964 }
965
966 static gboolean
967 gst_flac_enc_sink_event (GstPad * pad, GstEvent * event)
968 {
969   GstFlacEnc *flacenc;
970   GstTagList *taglist;
971   gboolean ret = TRUE;
972
973   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
974
975   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
976
977   switch (GST_EVENT_TYPE (event)) {
978     case GST_EVENT_NEWSEGMENT:{
979       GstFormat format;
980       gint64 start, stream_time;
981
982       if (flacenc->offset == 0) {
983         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
984             &stream_time);
985       } else {
986         start = -1;
987       }
988       if (start != 0) {
989         if (flacenc->offset > 0)
990           GST_DEBUG ("Not handling mid-stream newsegment event");
991         else
992           GST_DEBUG ("Not handling newsegment event with non-zero start");
993       } else {
994         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
995             0, -1, 0);
996
997         ret = gst_pad_push_event (flacenc->srcpad, e);
998       }
999       if (stream_time != 0) {
1000         GST_DEBUG ("Not handling non-zero stream time");
1001       }
1002       gst_event_unref (event);
1003       /* don't push it downstream, we'll generate our own via seek to 0 */
1004       break;
1005     }
1006     case GST_EVENT_EOS:
1007       FLAC__stream_encoder_finish (flacenc->encoder);
1008       ret = gst_pad_event_default (pad, event);
1009       break;
1010     case GST_EVENT_TAG:
1011       if (flacenc->tags) {
1012         gst_event_parse_tag (event, &taglist);
1013         gst_tag_list_insert (flacenc->tags, taglist,
1014             gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
1015       } else {
1016         g_assert_not_reached ();
1017       }
1018       ret = gst_pad_event_default (pad, event);
1019       break;
1020     default:
1021       ret = gst_pad_event_default (pad, event);
1022       break;
1023   }
1024
1025   gst_object_unref (flacenc);
1026
1027   return ret;
1028 }
1029
1030 static gboolean
1031 gst_flac_enc_check_discont (GstFlacEnc * flacenc, GstClockTime expected,
1032     GstClockTime timestamp)
1033 {
1034   guint allowed_diff = GST_SECOND / flacenc->sample_rate / 2;
1035
1036   if ((timestamp + allowed_diff < expected)
1037       || (timestamp > expected + allowed_diff)) {
1038     GST_ELEMENT_WARNING (flacenc, STREAM, FORMAT, (NULL),
1039         ("Stream discontinuity detected (wanted %" GST_TIME_FORMAT " got %"
1040             GST_TIME_FORMAT "). The output will have wrong timestamps,"
1041             " consider using audiorate to handle discontinuities",
1042             GST_TIME_ARGS (expected), GST_TIME_ARGS (timestamp)));
1043     return TRUE;
1044   }
1045
1046   /* TODO: Do something to handle discontinuities in the stream. The FLAC encoder
1047    * unfortunately doesn't have any way to flush it's internal buffers */
1048
1049   return FALSE;
1050 }
1051
1052 static GstFlowReturn
1053 gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer)
1054 {
1055   GstFlacEnc *flacenc;
1056   FLAC__int32 *data;
1057   gulong insize;
1058   gint samples, width;
1059   gulong i;
1060   FLAC__bool res;
1061
1062   flacenc = GST_FLAC_ENC (GST_PAD_PARENT (pad));
1063
1064   /* make sure setcaps has been called and the encoder is set up */
1065   if (G_UNLIKELY (flacenc->depth == 0))
1066     return GST_FLOW_NOT_NEGOTIATED;
1067
1068   width = flacenc->width;
1069
1070   /* Save the timestamp of the first buffer. This will be later
1071    * used as offset for all following buffers */
1072   if (flacenc->start_ts == GST_CLOCK_TIME_NONE) {
1073     if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1074       flacenc->start_ts = GST_BUFFER_TIMESTAMP (buffer);
1075       flacenc->granulepos_offset = gst_util_uint64_scale
1076           (GST_BUFFER_TIMESTAMP (buffer), flacenc->sample_rate, GST_SECOND);
1077     } else {
1078       flacenc->start_ts = 0;
1079       flacenc->granulepos_offset = 0;
1080     }
1081   }
1082
1083   /* Check if we have a continous stream, if not drop some samples or the buffer or
1084    * insert some silence samples */
1085   if (flacenc->next_ts != GST_CLOCK_TIME_NONE
1086       && GST_BUFFER_TIMESTAMP_IS_VALID (buffer)) {
1087     gst_flac_enc_check_discont (flacenc, flacenc->next_ts,
1088         GST_BUFFER_TIMESTAMP (buffer));
1089   }
1090
1091   if (GST_BUFFER_TIMESTAMP_IS_VALID (buffer)
1092       && GST_BUFFER_DURATION_IS_VALID (buffer))
1093     flacenc->next_ts =
1094         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1095   else
1096     flacenc->next_ts = GST_CLOCK_TIME_NONE;
1097
1098   insize = GST_BUFFER_SIZE (buffer);
1099   samples = insize / (width >> 3);
1100
1101   data = g_malloc (samples * sizeof (FLAC__int32));
1102
1103   if (width == 8) {
1104     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
1105
1106     for (i = 0; i < samples; i++)
1107       data[i] = (FLAC__int32) indata[i];
1108   } else if (width == 16) {
1109     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
1110
1111     for (i = 0; i < samples; i++)
1112       data[i] = (FLAC__int32) indata[i];
1113   } else if (width == 32) {
1114     gint32 *indata = (gint32 *) GST_BUFFER_DATA (buffer);
1115
1116     for (i = 0; i < samples; i++)
1117       data[i] = (FLAC__int32) indata[i];
1118   } else {
1119     g_assert_not_reached ();
1120   }
1121
1122   gst_buffer_unref (buffer);
1123
1124   res = FLAC__stream_encoder_process_interleaved (flacenc->encoder,
1125       (const FLAC__int32 *) data, samples / flacenc->channels);
1126
1127   g_free (data);
1128
1129   if (!res) {
1130     if (flacenc->last_flow == GST_FLOW_OK)
1131       return GST_FLOW_ERROR;
1132     else
1133       return flacenc->last_flow;
1134   }
1135
1136   return GST_FLOW_OK;
1137 }
1138
1139 static void
1140 gst_flac_enc_set_property (GObject * object, guint prop_id,
1141     const GValue * value, GParamSpec * pspec)
1142 {
1143   GstFlacEnc *this = GST_FLAC_ENC (object);
1144
1145   GST_OBJECT_LOCK (this);
1146
1147   switch (prop_id) {
1148     case PROP_QUALITY:
1149       gst_flac_enc_update_quality (this, g_value_get_enum (value));
1150       break;
1151     case PROP_STREAMABLE_SUBSET:
1152       FLAC__stream_encoder_set_streamable_subset (this->encoder,
1153           g_value_get_boolean (value));
1154       break;
1155     case PROP_MID_SIDE_STEREO:
1156       FLAC__stream_encoder_set_do_mid_side_stereo (this->encoder,
1157           g_value_get_boolean (value));
1158       break;
1159     case PROP_LOOSE_MID_SIDE_STEREO:
1160       FLAC__stream_encoder_set_loose_mid_side_stereo (this->encoder,
1161           g_value_get_boolean (value));
1162       break;
1163     case PROP_BLOCKSIZE:
1164       FLAC__stream_encoder_set_blocksize (this->encoder,
1165           g_value_get_uint (value));
1166       break;
1167     case PROP_MAX_LPC_ORDER:
1168       FLAC__stream_encoder_set_max_lpc_order (this->encoder,
1169           g_value_get_uint (value));
1170       break;
1171     case PROP_QLP_COEFF_PRECISION:
1172       FLAC__stream_encoder_set_qlp_coeff_precision (this->encoder,
1173           g_value_get_uint (value));
1174       break;
1175     case PROP_QLP_COEFF_PREC_SEARCH:
1176       FLAC__stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
1177           g_value_get_boolean (value));
1178       break;
1179     case PROP_ESCAPE_CODING:
1180       FLAC__stream_encoder_set_do_escape_coding (this->encoder,
1181           g_value_get_boolean (value));
1182       break;
1183     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1184       FLAC__stream_encoder_set_do_exhaustive_model_search (this->encoder,
1185           g_value_get_boolean (value));
1186       break;
1187     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1188       FLAC__stream_encoder_set_min_residual_partition_order (this->encoder,
1189           g_value_get_uint (value));
1190       break;
1191     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1192       FLAC__stream_encoder_set_max_residual_partition_order (this->encoder,
1193           g_value_get_uint (value));
1194       break;
1195     case PROP_RICE_PARAMETER_SEARCH_DIST:
1196       FLAC__stream_encoder_set_rice_parameter_search_dist (this->encoder,
1197           g_value_get_uint (value));
1198       break;
1199     default:
1200       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1201       break;
1202   }
1203
1204   GST_OBJECT_UNLOCK (this);
1205 }
1206
1207 static void
1208 gst_flac_enc_get_property (GObject * object, guint prop_id,
1209     GValue * value, GParamSpec * pspec)
1210 {
1211   GstFlacEnc *this = GST_FLAC_ENC (object);
1212
1213   GST_OBJECT_LOCK (this);
1214
1215   switch (prop_id) {
1216     case PROP_QUALITY:
1217       g_value_set_enum (value, this->quality);
1218       break;
1219     case PROP_STREAMABLE_SUBSET:
1220       g_value_set_boolean (value,
1221           FLAC__stream_encoder_get_streamable_subset (this->encoder));
1222       break;
1223     case PROP_MID_SIDE_STEREO:
1224       g_value_set_boolean (value,
1225           FLAC__stream_encoder_get_do_mid_side_stereo (this->encoder));
1226       break;
1227     case PROP_LOOSE_MID_SIDE_STEREO:
1228       g_value_set_boolean (value,
1229           FLAC__stream_encoder_get_loose_mid_side_stereo (this->encoder));
1230       break;
1231     case PROP_BLOCKSIZE:
1232       g_value_set_uint (value,
1233           FLAC__stream_encoder_get_blocksize (this->encoder));
1234       break;
1235     case PROP_MAX_LPC_ORDER:
1236       g_value_set_uint (value,
1237           FLAC__stream_encoder_get_max_lpc_order (this->encoder));
1238       break;
1239     case PROP_QLP_COEFF_PRECISION:
1240       g_value_set_uint (value,
1241           FLAC__stream_encoder_get_qlp_coeff_precision (this->encoder));
1242       break;
1243     case PROP_QLP_COEFF_PREC_SEARCH:
1244       g_value_set_boolean (value,
1245           FLAC__stream_encoder_get_do_qlp_coeff_prec_search (this->encoder));
1246       break;
1247     case PROP_ESCAPE_CODING:
1248       g_value_set_boolean (value,
1249           FLAC__stream_encoder_get_do_escape_coding (this->encoder));
1250       break;
1251     case PROP_EXHAUSTIVE_MODEL_SEARCH:
1252       g_value_set_boolean (value,
1253           FLAC__stream_encoder_get_do_exhaustive_model_search (this->encoder));
1254       break;
1255     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
1256       g_value_set_uint (value,
1257           FLAC__stream_encoder_get_min_residual_partition_order
1258           (this->encoder));
1259       break;
1260     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
1261       g_value_set_uint (value,
1262           FLAC__stream_encoder_get_max_residual_partition_order
1263           (this->encoder));
1264       break;
1265     case PROP_RICE_PARAMETER_SEARCH_DIST:
1266       g_value_set_uint (value,
1267           FLAC__stream_encoder_get_rice_parameter_search_dist (this->encoder));
1268       break;
1269     default:
1270       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1271       break;
1272   }
1273
1274   GST_OBJECT_UNLOCK (this);
1275 }
1276
1277 static GstStateChangeReturn
1278 gst_flac_enc_change_state (GstElement * element, GstStateChange transition)
1279 {
1280   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1281   GstFlacEnc *flacenc = GST_FLAC_ENC (element);
1282
1283   switch (transition) {
1284     case GST_STATE_CHANGE_NULL_TO_READY:
1285     case GST_STATE_CHANGE_READY_TO_PAUSED:
1286       flacenc->stopped = FALSE;
1287       flacenc->start_ts = GST_CLOCK_TIME_NONE;
1288       flacenc->next_ts = GST_CLOCK_TIME_NONE;
1289       flacenc->granulepos_offset = 0;
1290       break;
1291     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1292     default:
1293       break;
1294   }
1295
1296   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1297
1298   switch (transition) {
1299     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1300       break;
1301     case GST_STATE_CHANGE_PAUSED_TO_READY:
1302       if (FLAC__stream_encoder_get_state (flacenc->encoder) !=
1303           FLAC__STREAM_ENCODER_UNINITIALIZED) {
1304         flacenc->stopped = TRUE;
1305         FLAC__stream_encoder_finish (flacenc->encoder);
1306       }
1307       flacenc->offset = 0;
1308       flacenc->samples_written = 0;
1309       flacenc->channels = 0;
1310       flacenc->depth = 0;
1311       flacenc->sample_rate = 0;
1312       if (flacenc->meta) {
1313         FLAC__metadata_object_delete (flacenc->meta[0]);
1314         g_free (flacenc->meta);
1315         flacenc->meta = NULL;
1316       }
1317       g_list_foreach (flacenc->headers, (GFunc) gst_mini_object_unref, NULL);
1318       g_list_free (flacenc->headers);
1319       flacenc->headers = NULL;
1320       flacenc->got_headers = FALSE;
1321       flacenc->last_flow = GST_FLOW_OK;
1322       break;
1323     case GST_STATE_CHANGE_READY_TO_NULL:
1324     default:
1325       break;
1326   }
1327
1328   return ret;
1329 }