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