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