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