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