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