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