ext/flac/gstflacenc.c: Don't crash in chain function if setcaps hasn't been called.
[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
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 #include <stdlib.h>
25 #include <string.h>
26
27 #include <gstflacenc.h>
28 #include <gst/audio/audio.h>
29 #include <gst/tag/tag.h>
30 #include <gst/gsttagsetter.h>
31
32
33 static const GstElementDetails flacenc_details =
34 GST_ELEMENT_DETAILS ("FLAC audio encoder",
35     "Codec/Encoder/Audio",
36     "Encodes audio with the FLAC lossless audio encoder",
37     "Wim Taymans <wim.taymans@chello.be>");
38
39 #define FLAC_SINK_CAPS \
40   "audio/x-raw-int, "               \
41   "endianness = (int) BYTE_ORDER, " \
42   "signed = (boolean) TRUE, "       \
43   "width = (int) 16, "              \
44   "depth = (int) 16, "              \
45   "rate = (int) [ 8000, 48000 ], " \
46   "channels = (int) [ 1, 2 ]"
47
48 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
49     GST_PAD_SRC,
50     GST_PAD_ALWAYS,
51     GST_STATIC_CAPS ("audio/x-flac")
52     );
53
54 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
55     GST_PAD_SINK,
56     GST_PAD_ALWAYS,
57     GST_STATIC_CAPS (FLAC_SINK_CAPS)
58     );
59
60 enum
61 {
62   PROP_0,
63   PROP_QUALITY,
64   PROP_STREAMABLE_SUBSET,
65   PROP_MID_SIDE_STEREO,
66   PROP_LOOSE_MID_SIDE_STEREO,
67   PROP_BLOCKSIZE,
68   PROP_MAX_LPC_ORDER,
69   PROP_QLP_COEFF_PRECISION,
70   PROP_QLP_COEFF_PREC_SEARCH,
71   PROP_ESCAPE_CODING,
72   PROP_EXHAUSTIVE_MODEL_SEARCH,
73   PROP_MIN_RESIDUAL_PARTITION_ORDER,
74   PROP_MAX_RESIDUAL_PARTITION_ORDER,
75   PROP_RICE_PARAMETER_SEARCH_DIST
76 };
77
78 GST_DEBUG_CATEGORY_STATIC (flacenc_debug);
79 #define GST_CAT_DEFAULT flacenc_debug
80
81
82 #define _do_init(type)                                                          \
83   G_STMT_START{                                                                 \
84     static const GInterfaceInfo tag_setter_info = {                             \
85       NULL,                                                                     \
86       NULL,                                                                     \
87       NULL                                                                      \
88     };                                                                          \
89     g_type_add_interface_static (type, GST_TYPE_TAG_SETTER,                     \
90                                  &tag_setter_info);                             \
91   }G_STMT_END
92
93 GST_BOILERPLATE_FULL (GstFlacEnc, gst_flac_enc, GstElement, GST_TYPE_ELEMENT,
94     _do_init);
95
96 static void gst_flac_enc_finalize (GObject * object);
97
98 static gboolean gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps);
99 static gboolean gst_flac_enc_sink_event (GstPad * pad, GstEvent * event);
100 static GstFlowReturn gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer);
101
102 static gboolean gst_flac_enc_update_quality (GstFlacEnc * flacenc,
103     gint quality);
104 static void gst_flac_enc_set_property (GObject * object, guint prop_id,
105     const GValue * value, GParamSpec * pspec);
106 static void gst_flac_enc_get_property (GObject * object, guint prop_id,
107     GValue * value, GParamSpec * pspec);
108 static GstStateChangeReturn gst_flac_enc_change_state (GstElement * element,
109     GstStateChange transition);
110
111 static FLAC__StreamEncoderWriteStatus
112 gst_flac_enc_write_callback (const FLAC__SeekableStreamEncoder * encoder,
113     const FLAC__byte buffer[], unsigned bytes,
114     unsigned samples, unsigned current_frame, void *client_data);
115 static FLAC__SeekableStreamEncoderSeekStatus
116 gst_flac_enc_seek_callback (const FLAC__SeekableStreamEncoder * encoder,
117     FLAC__uint64 absolute_byte_offset, void *client_data);
118 static FLAC__SeekableStreamEncoderTellStatus
119 gst_flac_enc_tell_callback (const FLAC__SeekableStreamEncoder * encoder,
120     FLAC__uint64 * absolute_byte_offset, void *client_data);
121
122 typedef struct
123 {
124   gboolean exhaustive_model_search;
125   gboolean escape_coding;
126   gboolean mid_side;
127   gboolean loose_mid_side;
128   guint qlp_coeff_precision;
129   gboolean qlp_coeff_prec_search;
130   guint min_residual_partition_order;
131   guint max_residual_partition_order;
132   guint rice_parameter_search_dist;
133   guint max_lpc_order;
134   guint blocksize;
135 }
136 GstFlacEncParams;
137
138 static const GstFlacEncParams flacenc_params[] = {
139   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 2, 2, 0, 0, 1152},
140   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 2, 2, 0, 0, 1152},
141   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 3, 0, 0, 1152},
142   {FALSE, FALSE, FALSE, FALSE, 0, FALSE, 3, 3, 0, 6, 4608},
143   {FALSE, FALSE, TRUE, TRUE, 0, FALSE, 3, 3, 0, 8, 4608},
144   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 3, 3, 0, 8, 4608},
145   {FALSE, FALSE, TRUE, FALSE, 0, FALSE, 0, 4, 0, 8, 4608},
146   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 8, 4608},
147   {TRUE, FALSE, TRUE, FALSE, 0, FALSE, 0, 6, 0, 12, 4608},
148   {TRUE, TRUE, TRUE, FALSE, 0, FALSE, 0, 16, 0, 32, 4608},
149 };
150
151 #define DEFAULT_QUALITY 5
152
153 #define GST_TYPE_FLAC_ENC_QUALITY (gst_flac_enc_quality_get_type ())
154 GType
155 gst_flac_enc_quality_get_type (void)
156 {
157   static GType qtype = 0;
158
159   if (qtype == 0) {
160     static const GEnumValue values[] = {
161       {0, "0 - Fastest compression", "0"},
162       {1, "1", "1"},
163       {2, "2", "2"},
164       {3, "3", "3"},
165       {4, "4", "4"},
166       {5, "5 - Default", "5"},
167       {6, "6", "6"},
168       {7, "7", "7"},
169       {8, "8 - Highest compression", "8"},
170       {9, "9 - Insane", "9"},
171       {0, NULL, NULL}
172     };
173
174     qtype = g_enum_register_static ("GstFlacEncQuality", values);
175   }
176   return qtype;
177 }
178
179 static void
180 gst_flac_enc_base_init (gpointer g_class)
181 {
182   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
183
184   gst_element_class_add_pad_template (element_class,
185       gst_static_pad_template_get (&src_factory));
186   gst_element_class_add_pad_template (element_class,
187       gst_static_pad_template_get (&sink_factory));
188
189   gst_element_class_set_details (element_class, &flacenc_details);
190
191   GST_DEBUG_CATEGORY_INIT (flacenc_debug, "flacenc", 0,
192       "Flac encoding element");
193 }
194
195 static void
196 gst_flac_enc_class_init (GstFlacEncClass * klass)
197 {
198   GObjectClass *gobject_class;
199   GstElementClass *gstelement_class;
200
201   gobject_class = (GObjectClass *) klass;
202   gstelement_class = (GstElementClass *) klass;
203
204   gobject_class->set_property = gst_flac_enc_set_property;
205   gobject_class->get_property = gst_flac_enc_get_property;
206   gobject_class->finalize = gst_flac_enc_finalize;
207
208   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_QUALITY,
209       g_param_spec_enum ("quality",
210           "Quality",
211           "Speed versus compression tradeoff",
212           GST_TYPE_FLAC_ENC_QUALITY, DEFAULT_QUALITY, G_PARAM_READWRITE));
213   g_object_class_install_property (G_OBJECT_CLASS (klass),
214       PROP_STREAMABLE_SUBSET, g_param_spec_boolean ("streamable_subset",
215           "Streamable subset",
216           "true to limit encoder to generating a Subset stream, else false",
217           TRUE, G_PARAM_READWRITE));
218   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MID_SIDE_STEREO,
219       g_param_spec_boolean ("mid_side_stereo", "Do mid side stereo",
220           "Do mid side stereo (only for stereo input)",
221           flacenc_params[DEFAULT_QUALITY].mid_side, G_PARAM_READWRITE));
222   g_object_class_install_property (G_OBJECT_CLASS (klass),
223       PROP_LOOSE_MID_SIDE_STEREO, g_param_spec_boolean ("loose_mid_side_stereo",
224           "Loose mid side stereo", "Loose mid side stereo",
225           flacenc_params[DEFAULT_QUALITY].loose_mid_side, G_PARAM_READWRITE));
226   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_BLOCKSIZE,
227       g_param_spec_uint ("blocksize", "Blocksize", "Blocksize in samples",
228           FLAC__MIN_BLOCK_SIZE, FLAC__MAX_BLOCK_SIZE,
229           flacenc_params[DEFAULT_QUALITY].blocksize, G_PARAM_READWRITE));
230   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_MAX_LPC_ORDER,
231       g_param_spec_uint ("max_lpc_order", "Max LPC order",
232           "Max LPC order; 0 => use only fixed predictors", 0,
233           FLAC__MAX_LPC_ORDER, flacenc_params[DEFAULT_QUALITY].max_lpc_order,
234           G_PARAM_READWRITE));
235   g_object_class_install_property (G_OBJECT_CLASS (klass),
236       PROP_QLP_COEFF_PRECISION, g_param_spec_uint ("qlp_coeff_precision",
237           "QLP coefficients precision",
238           "Precision in bits of quantized linear-predictor coefficients; 0 = automatic",
239           0, 32, flacenc_params[DEFAULT_QUALITY].qlp_coeff_precision,
240           G_PARAM_READWRITE));
241   g_object_class_install_property (G_OBJECT_CLASS (klass),
242       PROP_QLP_COEFF_PREC_SEARCH, g_param_spec_boolean ("qlp_coeff_prec_search",
243           "Do QLP coefficients precision search",
244           "false = use qlp_coeff_precision, "
245           "true = search around qlp_coeff_precision, take best",
246           flacenc_params[DEFAULT_QUALITY].qlp_coeff_prec_search,
247           G_PARAM_READWRITE));
248   g_object_class_install_property (G_OBJECT_CLASS (klass), PROP_ESCAPE_CODING,
249       g_param_spec_boolean ("escape_coding", "Do Escape coding",
250           "search for escape codes in the entropy coding stage "
251           "for slightly better compression",
252           flacenc_params[DEFAULT_QUALITY].escape_coding, G_PARAM_READWRITE));
253   g_object_class_install_property (G_OBJECT_CLASS (klass),
254       PROP_EXHAUSTIVE_MODEL_SEARCH,
255       g_param_spec_boolean ("exhaustive_model_search",
256           "Do exhaustive model search",
257           "do exhaustive search of LP coefficient quantization (expensive!)",
258           flacenc_params[DEFAULT_QUALITY].exhaustive_model_search,
259           G_PARAM_READWRITE));
260   g_object_class_install_property (G_OBJECT_CLASS (klass),
261       PROP_MIN_RESIDUAL_PARTITION_ORDER,
262       g_param_spec_uint ("min_residual_partition_order",
263           "Min residual partition order",
264           "Min residual partition order (above 4 doesn't usually help much)", 0,
265           16, flacenc_params[DEFAULT_QUALITY].min_residual_partition_order,
266           G_PARAM_READWRITE));
267   g_object_class_install_property (G_OBJECT_CLASS (klass),
268       PROP_MAX_RESIDUAL_PARTITION_ORDER,
269       g_param_spec_uint ("max_residual_partition_order",
270           "Max residual partition order",
271           "Max residual partition order (above 4 doesn't usually help much)", 0,
272           16, flacenc_params[DEFAULT_QUALITY].max_residual_partition_order,
273           G_PARAM_READWRITE));
274   g_object_class_install_property (G_OBJECT_CLASS (klass),
275       PROP_RICE_PARAMETER_SEARCH_DIST,
276       g_param_spec_uint ("rice_parameter_search_dist",
277           "rice_parameter_search_dist",
278           "0 = try only calc'd parameter k; else try all [k-dist..k+dist] "
279           "parameters, use best", 0, FLAC__MAX_RICE_PARTITION_ORDER,
280           flacenc_params[DEFAULT_QUALITY].rice_parameter_search_dist,
281           G_PARAM_READWRITE));
282
283   gstelement_class->change_state = gst_flac_enc_change_state;
284 }
285
286 static void
287 gst_flac_enc_init (GstFlacEnc * flacenc, GstFlacEncClass * klass)
288 {
289   GstElementClass *eclass = GST_ELEMENT_CLASS (klass);
290
291   flacenc->sinkpad =
292       gst_pad_new_from_template (gst_element_class_get_pad_template (eclass,
293           "sink"), "sink");
294   gst_element_add_pad (GST_ELEMENT (flacenc), flacenc->sinkpad);
295   gst_pad_set_chain_function (flacenc->sinkpad, gst_flac_enc_chain);
296   gst_pad_set_event_function (flacenc->sinkpad, gst_flac_enc_sink_event);
297   gst_pad_set_setcaps_function (flacenc->sinkpad, gst_flac_enc_sink_setcaps);
298
299   flacenc->srcpad =
300       gst_pad_new_from_template (gst_element_class_get_pad_template (eclass,
301           "src"), "src");
302   gst_pad_use_fixed_caps (flacenc->srcpad);
303   gst_element_add_pad (GST_ELEMENT (flacenc), flacenc->srcpad);
304
305   flacenc->encoder = FLAC__seekable_stream_encoder_new ();
306
307   flacenc->offset = 0;
308   flacenc->samples_written = 0;
309   gst_flac_enc_update_quality (flacenc, DEFAULT_QUALITY);
310   flacenc->tags = gst_tag_list_new ();
311 }
312
313 static void
314 gst_flac_enc_finalize (GObject * object)
315 {
316   GstFlacEnc *flacenc = GST_FLAC_ENC (object);
317
318   gst_tag_list_free (flacenc->tags);
319   FLAC__seekable_stream_encoder_delete (flacenc->encoder);
320
321   G_OBJECT_CLASS (parent_class)->finalize (object);
322 }
323
324 static void
325 add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
326 {
327   GList *comments;
328   GList *it;
329   GstFlacEnc *flacenc = GST_FLAC_ENC (user_data);
330
331   comments = gst_tag_to_vorbis_comments (list, tag);
332   for (it = comments; it != NULL; it = it->next) {
333     FLAC__StreamMetadata_VorbisComment_Entry commment_entry;
334
335     commment_entry.length = strlen (it->data);
336     commment_entry.entry = it->data;
337     FLAC__metadata_object_vorbiscomment_insert_comment (flacenc->meta[0],
338         flacenc->meta[0]->data.vorbis_comment.num_comments,
339         commment_entry, TRUE);
340     g_free (it->data);
341   }
342   g_list_free (comments);
343 }
344
345 static void
346 gst_flac_enc_set_metadata (GstFlacEnc * flacenc)
347 {
348   const GstTagList *user_tags;
349   GstTagList *copy;
350
351   g_return_if_fail (flacenc != NULL);
352   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (flacenc));
353   if ((flacenc->tags == NULL) && (user_tags == NULL)) {
354     return;
355   }
356   copy = gst_tag_list_merge (user_tags, flacenc->tags,
357       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
358   flacenc->meta = g_malloc (sizeof (FLAC__StreamMetadata **));
359
360   flacenc->meta[0] =
361       FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT);
362   gst_tag_list_foreach (copy, add_one_tag, flacenc);
363
364   if (FLAC__seekable_stream_encoder_set_metadata (flacenc->encoder,
365           flacenc->meta, 1) != true)
366     g_warning ("Dude, i'm already initialized!");
367   gst_tag_list_free (copy);
368 }
369
370 static gboolean
371 gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps)
372 {
373   GstFlacEnc *flacenc;
374   GstStructure *structure;
375   FLAC__SeekableStreamEncoderState state;
376   gint depth, chans, rate, width;
377
378   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
379
380   if (FLAC__seekable_stream_encoder_get_state (flacenc->encoder) !=
381       FLAC__SEEKABLE_STREAM_ENCODER_UNINITIALIZED)
382     goto encoder_already_initialized;
383
384   structure = gst_caps_get_structure (caps, 0);
385
386   if (!gst_structure_get_int (structure, "channels", &chans) ||
387       !gst_structure_get_int (structure, "width", &width) ||
388       !gst_structure_get_int (structure, "depth", &depth) ||
389       !gst_structure_get_int (structure, "rate", &rate)) {
390     GST_DEBUG_OBJECT (flacenc, "incomplete caps: %" GST_PTR_FORMAT, caps);
391     return FALSE;
392   }
393
394   flacenc->channels = chans;
395   flacenc->depth = depth;
396   flacenc->sample_rate = rate;
397
398   caps = gst_caps_new_simple ("audio/x-flac",
399       "channels", G_TYPE_INT, flacenc->channels,
400       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
401
402   if (!gst_pad_set_caps (flacenc->srcpad, caps))
403     goto setting_src_caps_failed;
404
405   gst_caps_unref (caps);
406
407   FLAC__seekable_stream_encoder_set_bits_per_sample (flacenc->encoder,
408       flacenc->depth);
409   FLAC__seekable_stream_encoder_set_sample_rate (flacenc->encoder,
410       flacenc->sample_rate);
411   FLAC__seekable_stream_encoder_set_channels (flacenc->encoder,
412       flacenc->channels);
413
414   FLAC__seekable_stream_encoder_set_write_callback (flacenc->encoder,
415       gst_flac_enc_write_callback);
416   FLAC__seekable_stream_encoder_set_seek_callback (flacenc->encoder,
417       gst_flac_enc_seek_callback);
418   FLAC__seekable_stream_encoder_set_tell_callback (flacenc->encoder,
419       gst_flac_enc_tell_callback);
420
421   FLAC__seekable_stream_encoder_set_client_data (flacenc->encoder, flacenc);
422
423   gst_flac_enc_set_metadata (flacenc);
424
425   state = FLAC__seekable_stream_encoder_init (flacenc->encoder);
426   if (state != FLAC__STREAM_ENCODER_OK)
427     goto failed_to_initialize;
428
429   gst_object_unref (flacenc);
430
431   return TRUE;
432
433 encoder_already_initialized:
434   {
435     g_warning ("flac already initialized -- fixme allow this");
436     gst_object_unref (flacenc);
437     return FALSE;
438   }
439 setting_src_caps_failed:
440   {
441     GST_DEBUG_OBJECT (flacenc,
442         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
443     gst_caps_unref (caps);
444     gst_object_unref (flacenc);
445     return FALSE;
446   }
447 failed_to_initialize:
448   {
449     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
450         ("could not initialize encoder (wrong parameters?)"));
451     gst_object_unref (flacenc);
452     return FALSE;
453   }
454 }
455
456 static gboolean
457 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
458 {
459   flacenc->quality = quality;
460
461 #define DO_UPDATE(name, val, str)                                               \
462   G_STMT_START {                                                                \
463     if (FLAC__seekable_stream_encoder_get_##name (flacenc->encoder) !=          \
464         flacenc_params[quality].val) {                                          \
465       FLAC__seekable_stream_encoder_set_##name (flacenc->encoder,               \
466           flacenc_params[quality].val);                                         \
467       g_object_notify (G_OBJECT (flacenc), str);                                \
468     }                                                                           \
469   } G_STMT_END
470
471   g_object_freeze_notify (G_OBJECT (flacenc));
472
473   if (flacenc->channels == 2) {
474     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
475     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
476   }
477
478   DO_UPDATE (blocksize, blocksize, "blocksize");
479   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
480   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
481   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
482       "qlp_coeff_prec_search");
483   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
484   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
485       "exhaustive_model_search");
486   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
487       "min_residual_partition_order");
488   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
489       "max_residual_partition_order");
490   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
491       "rice_parameter_search_dist");
492
493 #undef DO_UPDATE
494
495   g_object_thaw_notify (G_OBJECT (flacenc));
496
497   return TRUE;
498 }
499
500 static FLAC__SeekableStreamEncoderSeekStatus
501 gst_flac_enc_seek_callback (const FLAC__SeekableStreamEncoder * encoder,
502     FLAC__uint64 absolute_byte_offset, void *client_data)
503 {
504   GstFlacEnc *flacenc;
505   GstEvent *event;
506   GstPad *peerpad;
507
508   flacenc = GST_FLAC_ENC (client_data);
509
510   if (flacenc->stopped)
511     return FLAC__SEEKABLE_STREAM_ENCODER_SEEK_STATUS_OK;
512
513   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
514       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
515
516   if ((peerpad = gst_pad_get_peer (flacenc->srcpad))) {
517     gboolean ret = gst_pad_send_event (peerpad, event);
518
519     gst_object_unref (peerpad);
520
521     if (ret) {
522       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
523           "succeeded");
524     } else {
525       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
526           "failed");
527     }
528   } else {
529     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
530         absolute_byte_offset);
531   }
532
533   flacenc->offset = absolute_byte_offset;
534
535   return FLAC__SEEKABLE_STREAM_ENCODER_SEEK_STATUS_OK;
536 }
537
538 static FLAC__StreamEncoderWriteStatus
539 gst_flac_enc_write_callback (const FLAC__SeekableStreamEncoder * encoder,
540     const FLAC__byte buffer[], unsigned bytes,
541     unsigned samples, unsigned current_frame, void *client_data)
542 {
543   GstFlowReturn ret;
544   GstFlacEnc *flacenc;
545   GstBuffer *outbuf;
546
547   flacenc = GST_FLAC_ENC (client_data);
548
549   if (flacenc->stopped)
550     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
551
552   if (gst_pad_alloc_buffer_and_set_caps (flacenc->srcpad, flacenc->offset,
553           bytes, GST_PAD_CAPS (flacenc->srcpad), &outbuf) != GST_FLOW_OK) {
554     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
555   }
556
557   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
558
559   if (samples > 0 && flacenc->samples_written != (guint64) - 1) {
560     GST_BUFFER_TIMESTAMP (outbuf) =
561         GST_FRAMES_TO_CLOCK_TIME (flacenc->samples_written,
562         flacenc->sample_rate);
563     GST_BUFFER_DURATION (outbuf) =
564         GST_FRAMES_TO_CLOCK_TIME (samples, flacenc->sample_rate);
565     /* offset_end = granulepos for ogg muxer */
566     GST_BUFFER_OFFSET_END (outbuf) = flacenc->samples_written + samples;
567   } else {
568     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
569     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
570   }
571
572   GST_DEBUG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
573       "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
574       samples, bytes, flacenc->offset);
575
576   ret = gst_pad_push (flacenc->srcpad, outbuf);
577
578   flacenc->offset += bytes;
579   flacenc->samples_written += samples;
580
581   if (ret != GST_FLOW_OK && GST_FLOW_IS_FATAL (ret))
582     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
583
584   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
585 }
586
587 static FLAC__SeekableStreamEncoderTellStatus
588 gst_flac_enc_tell_callback (const FLAC__SeekableStreamEncoder * encoder,
589     FLAC__uint64 * absolute_byte_offset, void *client_data)
590 {
591   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
592
593   *absolute_byte_offset = flacenc->offset;
594
595   return FLAC__SEEKABLE_STREAM_ENCODER_TELL_STATUS_OK;
596 }
597
598 static gboolean
599 gst_flac_enc_sink_event (GstPad * pad, GstEvent * event)
600 {
601   GstFlacEnc *flacenc;
602   GstTagList *taglist;
603   gboolean ret = TRUE;
604
605   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
606
607   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
608
609   switch (GST_EVENT_TYPE (event)) {
610     case GST_EVENT_NEWSEGMENT:{
611       GstFormat format;
612       gint64 start, stream_time;
613
614       if (flacenc->offset == 0) {
615         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
616             &stream_time);
617       } else {
618         start = -1;
619       }
620       if (start != 0) {
621         if (flacenc->offset > 0)
622           GST_DEBUG ("Not handling mid-stream newsegment event");
623         else
624           GST_DEBUG ("Not handling newsegment event with non-zero start");
625       } else {
626         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
627             0, -1, 0);
628
629         ret = gst_pad_push_event (flacenc->srcpad, e);
630       }
631       if (stream_time != 0) {
632         GST_DEBUG ("Not handling non-zero stream time");
633       }
634       gst_event_unref (event);
635       /* don't push it downstream, we'll generate our own via seek to 0 */
636       break;
637     }
638     case GST_EVENT_EOS:
639       FLAC__seekable_stream_encoder_finish (flacenc->encoder);
640       ret = gst_pad_event_default (pad, event);
641       break;
642     case GST_EVENT_TAG:
643       if (flacenc->tags) {
644         gst_event_parse_tag (event, &taglist);
645         gst_tag_list_insert (flacenc->tags, taglist, GST_TAG_MERGE_REPLACE);
646       } else {
647         g_assert_not_reached ();
648       }
649       ret = gst_pad_event_default (pad, event);
650       break;
651     default:
652       ret = gst_pad_event_default (pad, event);
653       break;
654   }
655
656   gst_object_unref (flacenc);
657
658   return ret;
659 }
660
661 static GstFlowReturn
662 gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer)
663 {
664   GstFlacEnc *flacenc;
665   FLAC__int32 *data;
666   gulong insize;
667   gint samples, depth;
668   gulong i;
669   FLAC__bool res;
670
671   flacenc = GST_FLAC_ENC (GST_PAD_PARENT (pad));
672
673   /* make sure setcaps has been called and the encoder is setup */
674   if (G_UNLIKELY (flacenc->depth == 0))
675     return GST_FLOW_NOT_NEGOTIATED;
676
677   depth = flacenc->depth;
678
679   insize = GST_BUFFER_SIZE (buffer);
680   samples = insize / ((depth + 7) >> 3);
681
682   data = g_malloc (samples * sizeof (FLAC__int32));
683
684   if (depth == 8) {
685     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
686
687     for (i = 0; i < samples; i++)
688       data[i] = (FLAC__int32) indata[i];
689   } else if (depth == 16) {
690     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
691
692     for (i = 0; i < samples; i++)
693       data[i] = (FLAC__int32) indata[i];
694   } else {
695     g_assert_not_reached ();
696   }
697
698   gst_buffer_unref (buffer);
699
700   res = FLAC__seekable_stream_encoder_process_interleaved (flacenc->encoder,
701       (const FLAC__int32 *) data, samples / flacenc->channels);
702
703   g_free (data);
704
705   if (res)
706     return GST_FLOW_OK;
707   else
708     return GST_FLOW_ERROR;
709 }
710
711 static void
712 gst_flac_enc_set_property (GObject * object, guint prop_id,
713     const GValue * value, GParamSpec * pspec)
714 {
715   GstFlacEnc *this = GST_FLAC_ENC (object);
716
717   GST_OBJECT_LOCK (this);
718
719   switch (prop_id) {
720     case PROP_QUALITY:
721       gst_flac_enc_update_quality (this, g_value_get_enum (value));
722       break;
723     case PROP_STREAMABLE_SUBSET:
724       FLAC__seekable_stream_encoder_set_streamable_subset (this->encoder,
725           g_value_get_boolean (value));
726       break;
727     case PROP_MID_SIDE_STEREO:
728       FLAC__seekable_stream_encoder_set_do_mid_side_stereo (this->encoder,
729           g_value_get_boolean (value));
730       break;
731     case PROP_LOOSE_MID_SIDE_STEREO:
732       FLAC__seekable_stream_encoder_set_loose_mid_side_stereo (this->encoder,
733           g_value_get_boolean (value));
734       break;
735     case PROP_BLOCKSIZE:
736       FLAC__seekable_stream_encoder_set_blocksize (this->encoder,
737           g_value_get_uint (value));
738       break;
739     case PROP_MAX_LPC_ORDER:
740       FLAC__seekable_stream_encoder_set_max_lpc_order (this->encoder,
741           g_value_get_uint (value));
742       break;
743     case PROP_QLP_COEFF_PRECISION:
744       FLAC__seekable_stream_encoder_set_qlp_coeff_precision (this->encoder,
745           g_value_get_uint (value));
746       break;
747     case PROP_QLP_COEFF_PREC_SEARCH:
748       FLAC__seekable_stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
749           g_value_get_boolean (value));
750       break;
751     case PROP_ESCAPE_CODING:
752       FLAC__seekable_stream_encoder_set_do_escape_coding (this->encoder,
753           g_value_get_boolean (value));
754       break;
755     case PROP_EXHAUSTIVE_MODEL_SEARCH:
756       FLAC__seekable_stream_encoder_set_do_exhaustive_model_search (this->
757           encoder, g_value_get_boolean (value));
758       break;
759     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
760       FLAC__seekable_stream_encoder_set_min_residual_partition_order (this->
761           encoder, g_value_get_uint (value));
762       break;
763     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
764       FLAC__seekable_stream_encoder_set_max_residual_partition_order (this->
765           encoder, g_value_get_uint (value));
766       break;
767     case PROP_RICE_PARAMETER_SEARCH_DIST:
768       FLAC__seekable_stream_encoder_set_rice_parameter_search_dist (this->
769           encoder, g_value_get_uint (value));
770       break;
771     default:
772       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
773       break;
774   }
775
776   GST_OBJECT_UNLOCK (this);
777 }
778
779 static void
780 gst_flac_enc_get_property (GObject * object, guint prop_id,
781     GValue * value, GParamSpec * pspec)
782 {
783   GstFlacEnc *this = GST_FLAC_ENC (object);
784
785   GST_OBJECT_LOCK (this);
786
787   switch (prop_id) {
788     case PROP_QUALITY:
789       g_value_set_enum (value, this->quality);
790       break;
791     case PROP_STREAMABLE_SUBSET:
792       g_value_set_boolean (value,
793           FLAC__seekable_stream_encoder_get_streamable_subset (this->encoder));
794       break;
795     case PROP_MID_SIDE_STEREO:
796       g_value_set_boolean (value,
797           FLAC__seekable_stream_encoder_get_do_mid_side_stereo (this->encoder));
798       break;
799     case PROP_LOOSE_MID_SIDE_STEREO:
800       g_value_set_boolean (value,
801           FLAC__seekable_stream_encoder_get_loose_mid_side_stereo (this->
802               encoder));
803       break;
804     case PROP_BLOCKSIZE:
805       g_value_set_uint (value,
806           FLAC__seekable_stream_encoder_get_blocksize (this->encoder));
807       break;
808     case PROP_MAX_LPC_ORDER:
809       g_value_set_uint (value,
810           FLAC__seekable_stream_encoder_get_max_lpc_order (this->encoder));
811       break;
812     case PROP_QLP_COEFF_PRECISION:
813       g_value_set_uint (value,
814           FLAC__seekable_stream_encoder_get_qlp_coeff_precision (this->
815               encoder));
816       break;
817     case PROP_QLP_COEFF_PREC_SEARCH:
818       g_value_set_boolean (value,
819           FLAC__seekable_stream_encoder_get_do_qlp_coeff_prec_search (this->
820               encoder));
821       break;
822     case PROP_ESCAPE_CODING:
823       g_value_set_boolean (value,
824           FLAC__seekable_stream_encoder_get_do_escape_coding (this->encoder));
825       break;
826     case PROP_EXHAUSTIVE_MODEL_SEARCH:
827       g_value_set_boolean (value,
828           FLAC__seekable_stream_encoder_get_do_exhaustive_model_search (this->
829               encoder));
830       break;
831     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
832       g_value_set_uint (value,
833           FLAC__seekable_stream_encoder_get_min_residual_partition_order (this->
834               encoder));
835       break;
836     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
837       g_value_set_uint (value,
838           FLAC__seekable_stream_encoder_get_max_residual_partition_order (this->
839               encoder));
840       break;
841     case PROP_RICE_PARAMETER_SEARCH_DIST:
842       g_value_set_uint (value,
843           FLAC__seekable_stream_encoder_get_rice_parameter_search_dist (this->
844               encoder));
845       break;
846     default:
847       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
848       break;
849   }
850
851   GST_OBJECT_UNLOCK (this);
852 }
853
854 static GstStateChangeReturn
855 gst_flac_enc_change_state (GstElement * element, GstStateChange transition)
856 {
857   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
858   GstFlacEnc *flacenc = GST_FLAC_ENC (element);
859
860   switch (transition) {
861     case GST_STATE_CHANGE_NULL_TO_READY:
862     case GST_STATE_CHANGE_READY_TO_PAUSED:
863       flacenc->stopped = FALSE;
864       break;
865     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
866     default:
867       break;
868   }
869
870   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
871
872   switch (transition) {
873     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
874       break;
875     case GST_STATE_CHANGE_PAUSED_TO_READY:
876       if (FLAC__seekable_stream_encoder_get_state (flacenc->encoder) !=
877           FLAC__STREAM_ENCODER_UNINITIALIZED) {
878         flacenc->stopped = TRUE;
879         FLAC__seekable_stream_encoder_finish (flacenc->encoder);
880       }
881       flacenc->offset = 0;
882       flacenc->samples_written = 0;
883       if (flacenc->meta) {
884         FLAC__metadata_object_delete (flacenc->meta[0]);
885         g_free (flacenc->meta);
886         flacenc->meta = NULL;
887       }
888       break;
889     case GST_STATE_CHANGE_READY_TO_NULL:
890     default:
891       break;
892   }
893
894   return ret;
895 }