better/unified long descriptions
[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 #include "flac_compat.h"
32
33
34 GstElementDetails flacenc_details = 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   FLAC__seekable_stream_encoder_delete (flacenc->encoder);
319
320   G_OBJECT_CLASS (parent_class)->finalize (object);
321 }
322
323 static void
324 add_one_tag (const GstTagList * list, const gchar * tag, gpointer user_data)
325 {
326   GList *comments;
327   GList *it;
328   GstFlacEnc *flacenc = GST_FLAC_ENC (user_data);
329
330   comments = gst_tag_to_vorbis_comments (list, tag);
331   for (it = comments; it != NULL; it = it->next) {
332     FLAC__StreamMetadata_VorbisComment_Entry commment_entry;
333
334     commment_entry.length = strlen (it->data);
335     commment_entry.entry = it->data;
336     FLAC__metadata_object_vorbiscomment_insert_comment (flacenc->meta[0],
337         flacenc->meta[0]->data.vorbis_comment.num_comments,
338         commment_entry, TRUE);
339     g_free (it->data);
340   }
341   g_list_free (comments);
342 }
343
344 static void
345 gst_flac_enc_set_metadata (GstFlacEnc * flacenc)
346 {
347   const GstTagList *user_tags;
348   GstTagList *copy;
349
350   g_return_if_fail (flacenc != NULL);
351   user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (flacenc));
352   if ((flacenc->tags == NULL) && (user_tags == NULL)) {
353     return;
354   }
355   copy = gst_tag_list_merge (user_tags, flacenc->tags,
356       gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (flacenc)));
357   flacenc->meta = g_malloc (sizeof (FLAC__StreamMetadata **));
358
359   flacenc->meta[0] =
360       FLAC__metadata_object_new (FLAC__METADATA_TYPE_VORBIS_COMMENT);
361   gst_tag_list_foreach (copy, add_one_tag, flacenc);
362
363   if (FLAC__seekable_stream_encoder_set_metadata (flacenc->encoder,
364           flacenc->meta, 1) != true)
365     g_warning ("Dude, i'm already initialized!");
366   gst_tag_list_free (copy);
367 }
368
369 static gboolean
370 gst_flac_enc_sink_setcaps (GstPad * pad, GstCaps * caps)
371 {
372   GstFlacEnc *flacenc;
373   GstStructure *structure;
374   FLAC__SeekableStreamEncoderState state;
375
376   /* takes a ref on flacenc */
377   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
378
379   if (FLAC__seekable_stream_encoder_get_state (flacenc->encoder) !=
380       FLAC__SEEKABLE_STREAM_ENCODER_UNINITIALIZED)
381     goto encoder_already_initialized;
382
383   structure = gst_caps_get_structure (caps, 0);
384
385   if (!gst_structure_get_int (structure, "channels", &flacenc->channels)
386       || !gst_structure_get_int (structure, "depth", &flacenc->depth)
387       || !gst_structure_get_int (structure, "rate", &flacenc->sample_rate))
388     /* we got caps incompatible with the template? */
389     g_return_val_if_reached (FALSE);
390
391   caps = gst_caps_new_simple ("audio/x-flac",
392       "channels", G_TYPE_INT, flacenc->channels,
393       "rate", G_TYPE_INT, flacenc->sample_rate, NULL);
394
395   if (!gst_pad_set_caps (flacenc->srcpad, caps))
396     goto setting_src_caps_failed;
397
398   gst_caps_unref (caps);
399
400   FLAC__seekable_stream_encoder_set_bits_per_sample (flacenc->encoder,
401       flacenc->depth);
402   FLAC__seekable_stream_encoder_set_sample_rate (flacenc->encoder,
403       flacenc->sample_rate);
404   FLAC__seekable_stream_encoder_set_channels (flacenc->encoder,
405       flacenc->channels);
406
407   FLAC__seekable_stream_encoder_set_write_callback (flacenc->encoder,
408       gst_flac_enc_write_callback);
409   FLAC__seekable_stream_encoder_set_seek_callback (flacenc->encoder,
410       gst_flac_enc_seek_callback);
411   FLAC__seekable_stream_encoder_set_tell_callback (flacenc->encoder,
412       gst_flac_enc_tell_callback);
413
414   FLAC__seekable_stream_encoder_set_client_data (flacenc->encoder, flacenc);
415
416   gst_flac_enc_set_metadata (flacenc);
417
418   state = FLAC__seekable_stream_encoder_init (flacenc->encoder);
419   if (state != FLAC__STREAM_ENCODER_OK)
420     goto failed_to_initialize;
421
422   gst_object_unref (flacenc);
423
424   return TRUE;
425
426 encoder_already_initialized:
427   {
428     g_warning ("flac already initialized -- fixme allow this");
429     gst_object_unref (flacenc);
430     return FALSE;
431   }
432 setting_src_caps_failed:
433   {
434     GST_DEBUG_OBJECT (flacenc,
435         "Couldn't set caps on source pad: %" GST_PTR_FORMAT, caps);
436     gst_caps_unref (caps);
437     gst_object_unref (flacenc);
438     return FALSE;
439   }
440 failed_to_initialize:
441   {
442     GST_ELEMENT_ERROR (flacenc, LIBRARY, INIT, (NULL),
443         ("could not initialize encoder (wrong parameters?)"));
444     gst_object_unref (flacenc);
445     return FALSE;
446   }
447 }
448
449 static gboolean
450 gst_flac_enc_update_quality (GstFlacEnc * flacenc, gint quality)
451 {
452   flacenc->quality = quality;
453
454 #define DO_UPDATE(name, val, str)                                               \
455   G_STMT_START {                                                                \
456     if (FLAC__seekable_stream_encoder_get_##name (flacenc->encoder) !=          \
457         flacenc_params[quality].val) {                                          \
458       FLAC__seekable_stream_encoder_set_##name (flacenc->encoder,               \
459           flacenc_params[quality].val);                                         \
460       g_object_notify (G_OBJECT (flacenc), str);                                \
461     }                                                                           \
462   } G_STMT_END
463
464   g_object_freeze_notify (G_OBJECT (flacenc));
465
466   if (flacenc->channels == 2) {
467     DO_UPDATE (do_mid_side_stereo, mid_side, "mid_side_stereo");
468     DO_UPDATE (loose_mid_side_stereo, loose_mid_side, "loose_mid_side");
469   }
470
471   DO_UPDATE (blocksize, blocksize, "blocksize");
472   DO_UPDATE (max_lpc_order, max_lpc_order, "max_lpc_order");
473   DO_UPDATE (qlp_coeff_precision, qlp_coeff_precision, "qlp_coeff_precision");
474   DO_UPDATE (do_qlp_coeff_prec_search, qlp_coeff_prec_search,
475       "qlp_coeff_prec_search");
476   DO_UPDATE (do_escape_coding, escape_coding, "escape_coding");
477   DO_UPDATE (do_exhaustive_model_search, exhaustive_model_search,
478       "exhaustive_model_search");
479   DO_UPDATE (min_residual_partition_order, min_residual_partition_order,
480       "min_residual_partition_order");
481   DO_UPDATE (max_residual_partition_order, max_residual_partition_order,
482       "max_residual_partition_order");
483   DO_UPDATE (rice_parameter_search_dist, rice_parameter_search_dist,
484       "rice_parameter_search_dist");
485
486 #undef DO_UPDATE
487
488   g_object_thaw_notify (G_OBJECT (flacenc));
489
490   return TRUE;
491 }
492
493 static FLAC__SeekableStreamEncoderSeekStatus
494 gst_flac_enc_seek_callback (const FLAC__SeekableStreamEncoder * encoder,
495     FLAC__uint64 absolute_byte_offset, void *client_data)
496 {
497   GstFlacEnc *flacenc;
498   GstEvent *event;
499   GstPad *peerpad;
500
501   flacenc = GST_FLAC_ENC (client_data);
502
503   if (flacenc->stopped)
504     return FLAC__STREAM_ENCODER_OK;
505
506   event = gst_event_new_new_segment (TRUE, 1.0, GST_FORMAT_BYTES,
507       absolute_byte_offset, GST_BUFFER_OFFSET_NONE, 0);
508
509   if ((peerpad = gst_pad_get_peer (flacenc->srcpad))) {
510     gboolean ret = gst_pad_send_event (peerpad, event);
511
512     gst_object_unref (peerpad);
513
514     if (ret) {
515       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
516           "succeeded");
517     } else {
518       GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " %s", absolute_byte_offset,
519           "failed");
520     }
521   } else {
522     GST_DEBUG ("Seek to %" G_GUINT64_FORMAT " failed (no peer pad)",
523         absolute_byte_offset);
524   }
525
526   flacenc->offset = absolute_byte_offset;
527
528   return FLAC__STREAM_ENCODER_OK;
529 }
530
531 static FLAC__StreamEncoderWriteStatus
532 gst_flac_enc_write_callback (const FLAC__SeekableStreamEncoder * encoder,
533     const FLAC__byte buffer[], unsigned bytes,
534     unsigned samples, unsigned current_frame, void *client_data)
535 {
536   GstFlowReturn ret;
537   GstFlacEnc *flacenc;
538   GstBuffer *outbuf;
539
540   flacenc = GST_FLAC_ENC (client_data);
541
542   if (flacenc->stopped)
543     return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
544
545   if (gst_pad_alloc_buffer_and_set_caps (flacenc->srcpad, flacenc->offset,
546           bytes, GST_PAD_CAPS (flacenc->srcpad), &outbuf) != GST_FLOW_OK) {
547     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
548   }
549
550   memcpy (GST_BUFFER_DATA (outbuf), buffer, bytes);
551
552   if (samples > 0 && flacenc->samples_written != (guint64) - 1) {
553     GST_BUFFER_TIMESTAMP (outbuf) =
554         GST_FRAMES_TO_CLOCK_TIME (flacenc->samples_written,
555         flacenc->sample_rate);
556     GST_BUFFER_DURATION (outbuf) =
557         GST_FRAMES_TO_CLOCK_TIME (samples, flacenc->sample_rate);
558     /* offset_end = granulepos for ogg muxer */
559     GST_BUFFER_OFFSET_END (outbuf) = flacenc->samples_written + samples;
560   } else {
561     GST_BUFFER_TIMESTAMP (outbuf) = GST_CLOCK_TIME_NONE;
562     GST_BUFFER_DURATION (outbuf) = GST_CLOCK_TIME_NONE;
563   }
564
565   GST_DEBUG ("Pushing buffer: ts=%" GST_TIME_FORMAT ", samples=%u, size=%u, "
566       "pos=%" G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (outbuf)),
567       samples, bytes, flacenc->offset);
568
569   ret = gst_pad_push (flacenc->srcpad, outbuf);
570
571   flacenc->offset += bytes;
572   flacenc->samples_written += samples;
573
574   if (ret != GST_FLOW_OK && GST_FLOW_IS_FATAL (ret))
575     return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
576
577   return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
578 }
579
580 static FLAC__SeekableStreamEncoderTellStatus
581 gst_flac_enc_tell_callback (const FLAC__SeekableStreamEncoder * encoder,
582     FLAC__uint64 * absolute_byte_offset, void *client_data)
583 {
584   GstFlacEnc *flacenc = GST_FLAC_ENC (client_data);
585
586   *absolute_byte_offset = flacenc->offset;
587
588   return FLAC__STREAM_ENCODER_OK;
589 }
590
591 static gboolean
592 gst_flac_enc_sink_event (GstPad * pad, GstEvent * event)
593 {
594   GstFlacEnc *flacenc;
595   GstTagList *taglist;
596   gboolean ret = TRUE;
597
598   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
599
600   GST_DEBUG ("Received %s event on sinkpad", GST_EVENT_TYPE_NAME (event));
601
602   switch (GST_EVENT_TYPE (event)) {
603     case GST_EVENT_NEWSEGMENT:{
604       GstFormat format;
605       gint64 start, stream_time;
606
607       if (flacenc->offset == 0) {
608         gst_event_parse_new_segment (event, NULL, NULL, &format, &start, NULL,
609             &stream_time);
610       } else {
611         start = -1;
612       }
613       if (start != 0) {
614         if (flacenc->offset > 0)
615           GST_DEBUG ("Not handling mid-stream newsegment event");
616         else
617           GST_DEBUG ("Not handling newsegment event with non-zero start");
618       } else {
619         GstEvent *e = gst_event_new_new_segment (FALSE, 1.0, GST_FORMAT_BYTES,
620             0, -1, 0);
621
622         ret = gst_pad_push_event (flacenc->srcpad, e);
623       }
624       if (stream_time != 0) {
625         GST_DEBUG ("Not handling non-zero stream time");
626       }
627       gst_event_unref (event);
628       /* don't push it downstream, we'll generate our own via seek to 0 */
629       break;
630     }
631     case GST_EVENT_EOS:
632       FLAC__seekable_stream_encoder_finish (flacenc->encoder);
633       ret = gst_pad_event_default (pad, event);
634       break;
635     case GST_EVENT_TAG:
636       if (flacenc->tags) {
637         gst_event_parse_tag (event, &taglist);
638         gst_tag_list_insert (flacenc->tags, taglist, GST_TAG_MERGE_REPLACE);
639       } else {
640         g_assert_not_reached ();
641       }
642       ret = gst_pad_event_default (pad, event);
643       break;
644     default:
645       ret = gst_pad_event_default (pad, event);
646       break;
647   }
648
649   gst_object_unref (flacenc);
650
651   return ret;
652 }
653
654 static GstFlowReturn
655 gst_flac_enc_chain (GstPad * pad, GstBuffer * buffer)
656 {
657   GstFlacEnc *flacenc;
658   FLAC__int32 *data;
659   gulong insize;
660   gint samples, depth;
661   gulong i;
662   FLAC__bool res;
663
664   flacenc = GST_FLAC_ENC (gst_pad_get_parent (pad));
665
666   depth = flacenc->depth;
667
668   insize = GST_BUFFER_SIZE (buffer);
669   samples = insize / ((depth + 7) >> 3);
670
671   data = g_malloc (samples * sizeof (FLAC__int32));
672
673   if (depth == 8) {
674     gint8 *indata = (gint8 *) GST_BUFFER_DATA (buffer);
675
676     for (i = 0; i < samples; i++)
677       data[i] = (FLAC__int32) indata[i];
678   } else if (depth == 16) {
679     gint16 *indata = (gint16 *) GST_BUFFER_DATA (buffer);
680
681     for (i = 0; i < samples; i++)
682       data[i] = (FLAC__int32) indata[i];
683   } else {
684     g_assert_not_reached ();
685   }
686
687   gst_buffer_unref (buffer);
688
689   res = FLAC__seekable_stream_encoder_process_interleaved (flacenc->encoder,
690       (const FLAC__int32 *) data, samples / flacenc->channels);
691
692   g_free (data);
693
694   gst_object_unref (flacenc);
695
696   if (res)
697     return GST_FLOW_OK;
698   else
699     return GST_FLOW_ERROR;
700 }
701
702 static void
703 gst_flac_enc_set_property (GObject * object, guint prop_id,
704     const GValue * value, GParamSpec * pspec)
705 {
706   GstFlacEnc *this = GST_FLAC_ENC (object);
707
708   GST_OBJECT_LOCK (this);
709
710   switch (prop_id) {
711     case PROP_QUALITY:
712       gst_flac_enc_update_quality (this, g_value_get_enum (value));
713       break;
714     case PROP_STREAMABLE_SUBSET:
715       FLAC__seekable_stream_encoder_set_streamable_subset (this->encoder,
716           g_value_get_boolean (value));
717       break;
718     case PROP_MID_SIDE_STEREO:
719       FLAC__seekable_stream_encoder_set_do_mid_side_stereo (this->encoder,
720           g_value_get_boolean (value));
721       break;
722     case PROP_LOOSE_MID_SIDE_STEREO:
723       FLAC__seekable_stream_encoder_set_loose_mid_side_stereo (this->encoder,
724           g_value_get_boolean (value));
725       break;
726     case PROP_BLOCKSIZE:
727       FLAC__seekable_stream_encoder_set_blocksize (this->encoder,
728           g_value_get_uint (value));
729       break;
730     case PROP_MAX_LPC_ORDER:
731       FLAC__seekable_stream_encoder_set_max_lpc_order (this->encoder,
732           g_value_get_uint (value));
733       break;
734     case PROP_QLP_COEFF_PRECISION:
735       FLAC__seekable_stream_encoder_set_qlp_coeff_precision (this->encoder,
736           g_value_get_uint (value));
737       break;
738     case PROP_QLP_COEFF_PREC_SEARCH:
739       FLAC__seekable_stream_encoder_set_do_qlp_coeff_prec_search (this->encoder,
740           g_value_get_boolean (value));
741       break;
742     case PROP_ESCAPE_CODING:
743       FLAC__seekable_stream_encoder_set_do_escape_coding (this->encoder,
744           g_value_get_boolean (value));
745       break;
746     case PROP_EXHAUSTIVE_MODEL_SEARCH:
747       FLAC__seekable_stream_encoder_set_do_exhaustive_model_search (this->
748           encoder, g_value_get_boolean (value));
749       break;
750     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
751       FLAC__seekable_stream_encoder_set_min_residual_partition_order (this->
752           encoder, g_value_get_uint (value));
753       break;
754     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
755       FLAC__seekable_stream_encoder_set_max_residual_partition_order (this->
756           encoder, g_value_get_uint (value));
757       break;
758     case PROP_RICE_PARAMETER_SEARCH_DIST:
759       FLAC__seekable_stream_encoder_set_rice_parameter_search_dist (this->
760           encoder, g_value_get_uint (value));
761       break;
762     default:
763       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
764       break;
765   }
766
767   GST_OBJECT_UNLOCK (this);
768 }
769
770 static void
771 gst_flac_enc_get_property (GObject * object, guint prop_id,
772     GValue * value, GParamSpec * pspec)
773 {
774   GstFlacEnc *this = GST_FLAC_ENC (object);
775
776   GST_OBJECT_LOCK (this);
777
778   switch (prop_id) {
779     case PROP_QUALITY:
780       g_value_set_enum (value, this->quality);
781       break;
782     case PROP_STREAMABLE_SUBSET:
783       g_value_set_boolean (value,
784           FLAC__seekable_stream_encoder_get_streamable_subset (this->encoder));
785       break;
786     case PROP_MID_SIDE_STEREO:
787       g_value_set_boolean (value,
788           FLAC__seekable_stream_encoder_get_do_mid_side_stereo (this->encoder));
789       break;
790     case PROP_LOOSE_MID_SIDE_STEREO:
791       g_value_set_boolean (value,
792           FLAC__seekable_stream_encoder_get_loose_mid_side_stereo (this->
793               encoder));
794       break;
795     case PROP_BLOCKSIZE:
796       g_value_set_uint (value,
797           FLAC__seekable_stream_encoder_get_blocksize (this->encoder));
798       break;
799     case PROP_MAX_LPC_ORDER:
800       g_value_set_uint (value,
801           FLAC__seekable_stream_encoder_get_max_lpc_order (this->encoder));
802       break;
803     case PROP_QLP_COEFF_PRECISION:
804       g_value_set_uint (value,
805           FLAC__seekable_stream_encoder_get_qlp_coeff_precision (this->
806               encoder));
807       break;
808     case PROP_QLP_COEFF_PREC_SEARCH:
809       g_value_set_boolean (value,
810           FLAC__seekable_stream_encoder_get_do_qlp_coeff_prec_search (this->
811               encoder));
812       break;
813     case PROP_ESCAPE_CODING:
814       g_value_set_boolean (value,
815           FLAC__seekable_stream_encoder_get_do_escape_coding (this->encoder));
816       break;
817     case PROP_EXHAUSTIVE_MODEL_SEARCH:
818       g_value_set_boolean (value,
819           FLAC__seekable_stream_encoder_get_do_exhaustive_model_search (this->
820               encoder));
821       break;
822     case PROP_MIN_RESIDUAL_PARTITION_ORDER:
823       g_value_set_uint (value,
824           FLAC__seekable_stream_encoder_get_min_residual_partition_order (this->
825               encoder));
826       break;
827     case PROP_MAX_RESIDUAL_PARTITION_ORDER:
828       g_value_set_uint (value,
829           FLAC__seekable_stream_encoder_get_max_residual_partition_order (this->
830               encoder));
831       break;
832     case PROP_RICE_PARAMETER_SEARCH_DIST:
833       g_value_set_uint (value,
834           FLAC__seekable_stream_encoder_get_rice_parameter_search_dist (this->
835               encoder));
836       break;
837     default:
838       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
839       break;
840   }
841
842   GST_OBJECT_UNLOCK (this);
843 }
844
845 static GstStateChangeReturn
846 gst_flac_enc_change_state (GstElement * element, GstStateChange transition)
847 {
848   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
849   GstFlacEnc *flacenc = GST_FLAC_ENC (element);
850
851   switch (transition) {
852     case GST_STATE_CHANGE_NULL_TO_READY:
853     case GST_STATE_CHANGE_READY_TO_PAUSED:
854       flacenc->stopped = FALSE;
855       break;
856     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
857     default:
858       break;
859   }
860
861   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
862
863   switch (transition) {
864     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
865       break;
866     case GST_STATE_CHANGE_PAUSED_TO_READY:
867       if (FLAC__seekable_stream_encoder_get_state (flacenc->encoder) !=
868           FLAC__STREAM_ENCODER_UNINITIALIZED) {
869         flacenc->stopped = TRUE;
870         FLAC__seekable_stream_encoder_finish (flacenc->encoder);
871       }
872       flacenc->offset = 0;
873       flacenc->samples_written = 0;
874       if (flacenc->meta) {
875         FLAC__metadata_object_delete (flacenc->meta[0]);
876         g_free (flacenc->meta);
877         flacenc->meta = NULL;
878       }
879       break;
880     case GST_STATE_CHANGE_READY_TO_NULL:
881     default:
882       break;
883   }
884
885   return ret;
886 }