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