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