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