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