ba9d7c4e673899a64f43ca52d776ee5662a371bc
[platform/upstream/gst-plugins-good.git] / gst / audioparsers / gstflacparse.c
1 /* GStreamer
2  *
3  * Copyright (C) 2008 Sebastian Dröge <sebastian.droege@collabora.co.uk>.
4  * Copyright (C) 2009 Mark Nauwelaerts <mark.nauwelaerts@collabora.co.uk>
5  * Copyright (C) 2009 Nokia Corporation. All rights reserved.
6  *   Contact: Stefan Kost <stefan.kost@nokia.com>
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Library General Public
10  * License as published by the Free Software Foundation; either
11  * version 2 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Library General Public License for more details.
17  *
18  * You should have received a copy of the GNU Library General Public
19  * License along with this library; if not, write to the
20  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21  * Boston, MA 02111-1307, USA.
22  */
23
24 /**
25  * SECTION:element-flacparse
26  * @see_also: flacdec, oggdemux, vorbisparse
27  *
28  * The flacparse element will parse the header packets of the FLAC
29  * stream and put them as the streamheader in the caps. This is used in the
30  * multifdsink case where you want to stream live FLAC streams to multiple
31  * clients, each client has to receive the streamheaders first before they can
32  * consume the FLAC packets.
33  *
34  * This element also makes sure that the buffers that it pushes out are properly
35  * timestamped and that their offset and offset_end are set. The buffers that
36  * flacparse outputs have all of the metadata that oggmux expects to receive,
37  * which allows you to (for example) remux an ogg/flac or convert a native FLAC
38  * format file to an ogg bitstream.
39  *
40  * <refsect2>
41  * <title>Example pipelines</title>
42  * |[
43  * gst-launch -v filesrc location=sine.flac ! flacparse ! identity \
44  *            ! oggmux ! filesink location=sine-remuxed.ogg
45  * ]| This pipeline converts a native FLAC format file to an ogg bitstream.
46  * It also illustrates that the streamheader is set in the caps, and that each
47  * buffer has the timestamp, duration, offset, and offset_end set.
48  * </refsect2>
49  *
50  */
51
52 #ifdef HAVE_CONFIG_H
53 #include "config.h"
54 #endif
55
56 #include "gstflacparse.h"
57
58 #include <string.h>
59 #include <gst/tag/tag.h>
60 #include <gst/audio/audio.h>
61
62 #include <gst/base/gstbitreader.h>
63 #include <gst/base/gstbytereader.h>
64
65 GST_DEBUG_CATEGORY_STATIC (flacparse_debug);
66 #define GST_CAT_DEFAULT flacparse_debug
67
68 /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
69 static const guint8 crc8_table[256] = {
70   0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
71   0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
72   0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
73   0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
74   0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
75   0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
76   0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
77   0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
78   0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
79   0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
80   0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
81   0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
82   0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
83   0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
84   0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
85   0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
86   0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
87   0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
88   0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
89   0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
90   0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
91   0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
92   0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
93   0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
94   0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
95   0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
96   0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
97   0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
98   0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
99   0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
100   0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
101   0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
102 };
103
104 static guint8
105 gst_flac_calculate_crc8 (const guint8 * data, guint length)
106 {
107   guint8 crc = 0;
108
109   while (length--) {
110     crc = crc8_table[crc ^ *data];
111     ++data;
112   }
113
114   return crc;
115 }
116
117 static GstStaticPadTemplate src_factory = GST_STATIC_PAD_TEMPLATE ("src",
118     GST_PAD_SRC,
119     GST_PAD_ALWAYS,
120     GST_STATIC_CAPS ("audio/x-flac, framed = (boolean) true, "
121         "channels = (int) [ 1, 8 ], " "rate = (int) [ 1, 655350 ]")
122     );
123
124 static GstStaticPadTemplate sink_factory = GST_STATIC_PAD_TEMPLATE ("sink",
125     GST_PAD_SINK,
126     GST_PAD_ALWAYS,
127     GST_STATIC_CAPS ("audio/x-flac, framed = (boolean) false")
128     );
129
130 static void gst_flac_parse_finalize (GObject * object);
131
132 static gboolean gst_flac_parse_start (GstBaseParse * parse);
133 static gboolean gst_flac_parse_stop (GstBaseParse * parse);
134 static gboolean gst_flac_parse_check_valid_frame (GstBaseParse * parse,
135     GstBuffer * buffer, guint * framesize, gint * skipsize);
136 static GstFlowReturn gst_flac_parse_parse_frame (GstBaseParse * parse,
137     GstBuffer * buffer);
138 static gint gst_flac_parse_get_frame_overhead (GstBaseParse * parse,
139     GstBuffer * buffer);
140
141 GST_BOILERPLATE (GstFlacParse, gst_flac_parse, GstBaseParse,
142     GST_TYPE_BASE_PARSE);
143
144 static void
145 gst_flac_parse_base_init (gpointer g_class)
146 {
147   GstElementClass *element_class = GST_ELEMENT_CLASS (g_class);
148
149   gst_element_class_add_pad_template (element_class,
150       gst_static_pad_template_get (&src_factory));
151   gst_element_class_add_pad_template (element_class,
152       gst_static_pad_template_get (&sink_factory));
153
154   gst_element_class_set_details_simple (element_class, "FLAC audio parser",
155       "Codec/Parser/Audio",
156       "Parses audio with the FLAC lossless audio codec",
157       "Sebastian Dröge <sebastian.droege@collabora.co.uk>");
158
159   GST_DEBUG_CATEGORY_INIT (flacparse_debug, "flacparse", 0,
160       "Flac parser element");
161 }
162
163 static void
164 gst_flac_parse_class_init (GstFlacParseClass * klass)
165 {
166   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
167   GstBaseParseClass *baseparse_class = GST_BASE_PARSE_CLASS (klass);
168
169   gobject_class->finalize = gst_flac_parse_finalize;
170
171   baseparse_class->start = GST_DEBUG_FUNCPTR (gst_flac_parse_start);
172   baseparse_class->stop = GST_DEBUG_FUNCPTR (gst_flac_parse_stop);
173   baseparse_class->check_valid_frame =
174       GST_DEBUG_FUNCPTR (gst_flac_parse_check_valid_frame);
175   baseparse_class->parse_frame = GST_DEBUG_FUNCPTR (gst_flac_parse_parse_frame);
176   baseparse_class->get_frame_overhead =
177       GST_DEBUG_FUNCPTR (gst_flac_parse_get_frame_overhead);
178 }
179
180 static void
181 gst_flac_parse_init (GstFlacParse * flacparse, GstFlacParseClass * klass)
182 {
183 }
184
185 static void
186 gst_flac_parse_finalize (GObject * object)
187 {
188   GstFlacParse *flacparse = GST_FLAC_PARSE (object);
189
190   if (flacparse->tags) {
191     gst_tag_list_free (flacparse->tags);
192     flacparse->tags = NULL;
193   }
194
195
196   g_list_foreach (flacparse->headers, (GFunc) gst_mini_object_unref, NULL);
197   g_list_free (flacparse->headers);
198   flacparse->headers = NULL;
199
200   G_OBJECT_CLASS (parent_class)->finalize (object);
201 }
202
203 static gboolean
204 gst_flac_parse_start (GstBaseParse * parse)
205 {
206   GstFlacParse *flacparse = GST_FLAC_PARSE (parse);
207
208   flacparse->state = GST_FLAC_PARSE_STATE_INIT;
209   flacparse->min_blocksize = 0;
210   flacparse->max_blocksize = 0;
211   flacparse->min_framesize = 0;
212   flacparse->max_framesize = 0;
213
214   flacparse->upstream_length = -1;
215
216   flacparse->samplerate = 0;
217   flacparse->channels = 0;
218   flacparse->bps = 0;
219   flacparse->total_samples = 0;
220
221   flacparse->requested_frame_size = 0;
222   flacparse->offset = GST_CLOCK_TIME_NONE;
223   flacparse->blocking_strategy = 0;
224   flacparse->block_size = 0;
225   flacparse->sample_number = 0;
226
227   /* "fLaC" marker */
228   gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), 4);
229
230   return TRUE;
231 }
232
233 static gboolean
234 gst_flac_parse_stop (GstBaseParse * parse)
235 {
236   GstFlacParse *flacparse = GST_FLAC_PARSE (parse);
237
238   if (flacparse->tags) {
239     gst_tag_list_free (flacparse->tags);
240     flacparse->tags = NULL;
241   }
242
243   g_list_foreach (flacparse->headers, (GFunc) gst_mini_object_unref, NULL);
244   g_list_free (flacparse->headers);
245   flacparse->headers = NULL;
246
247   return TRUE;
248 }
249
250 static gint
251 gst_flac_parse_get_frame_size (GstFlacParse * flacparse, GstBuffer * buffer,
252     guint * framesize_ret)
253 {
254   GstBitReader reader = GST_BIT_READER_INIT_FROM_BUFFER (buffer);
255   guint16 samplerate;
256   guint8 tmp;
257   gint i;
258   guint8 channel_assignment = 0;
259   guint8 actual_crc, expected_crc;
260
261   /* Skip 14 bit sync code */
262   if (!gst_bit_reader_skip (&reader, 14))
263     goto need_more_data;
264
265   /* Must be 0 */
266   if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
267     goto need_more_data;
268   else if (tmp != 0)
269     goto error;
270
271   /* 0 == fixed block size, 1 == variable block size */
272   if (!gst_bit_reader_get_bits_uint8 (&reader, &flacparse->blocking_strategy,
273           1))
274     goto need_more_data;
275
276   /* block size index, calculation of the real blocksize below */
277   if (!gst_bit_reader_get_bits_uint16 (&reader, &flacparse->block_size, 4))
278     goto need_more_data;
279   else if (flacparse->block_size == 0)
280     goto error;
281
282   /* sample rate index, calculation of the real samplerate below */
283   if (!gst_bit_reader_get_bits_uint16 (&reader, &samplerate, 4))
284     goto need_more_data;
285   else if (samplerate == 0x0f)
286     goto error;
287
288   /* channel assignment */
289   if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 4)) {
290     goto need_more_data;
291   } else if (tmp < 8) {
292     if (flacparse->channels && tmp + 1 != flacparse->channels)
293       goto error;
294     else
295       flacparse->channels = tmp + 1;
296   } else if (tmp <= 10) {
297     if (flacparse->channels && 2 != flacparse->channels)
298       goto error;
299     else
300       flacparse->channels = 2;
301     if (tmp == 8)
302       channel_assignment = 1;   /* left-side */
303     else if (tmp == 9)
304       channel_assignment = 2;   /* right-side */
305     else
306       channel_assignment = 3;   /* mid-side */
307   } else if (tmp > 10) {
308     goto error;
309   }
310
311   /* bits per sample */
312   if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 3)) {
313     goto need_more_data;
314   } else if (tmp == 0x03 || tmp == 0x07) {
315     goto error;
316   } else if (tmp == 0 && flacparse->bps == 0) {
317     goto need_streaminfo;
318   } else if (tmp == 0x01 && flacparse->bps != 8) {
319     if (flacparse->bps && flacparse->bps != 8)
320       goto error;
321     else
322       flacparse->bps = 8;
323   } else if (tmp == 0x02 && flacparse->bps != 12) {
324     if (flacparse->bps && flacparse->bps != 12)
325       goto error;
326     else
327       flacparse->bps = 12;
328   } else if (tmp == 0x04 && flacparse->bps != 16) {
329     if (flacparse->bps && flacparse->bps != 16)
330       goto error;
331     else
332       flacparse->bps = 16;
333   } else if (tmp == 0x05 && flacparse->bps != 20) {
334     if (flacparse->bps && flacparse->bps != 20)
335       goto error;
336     else
337       flacparse->bps = 20;
338   } else if (tmp == 0x06 && flacparse->bps != 24) {
339     if (flacparse->bps && flacparse->bps != 24)
340       goto error;
341     else
342       flacparse->bps = 24;
343   }
344
345   /* reserved, must be 0 */
346   if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
347     goto need_more_data;
348   else if (tmp != 0)
349     goto error;
350
351   /* read "utf8" encoded sample/frame number */
352   {
353     guint len = 0;
354
355     tmp = 1;
356     while (tmp != 0) {
357       if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
358         goto need_more_data;
359       else if (tmp == 1)
360         len++;
361     }
362     if (len == 1)
363       goto error;
364
365     flacparse->sample_number = 0;
366     if (len == 0) {
367       if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 7))
368         goto need_more_data;
369       flacparse->sample_number = tmp;
370     } else if ((flacparse->blocking_strategy == 0 && len > 6) ||
371         (flacparse->blocking_strategy == 1 && len > 7)) {
372       goto error;
373     } else {
374       if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 8 - len - 1))
375         goto need_more_data;
376
377       flacparse->sample_number = tmp;
378       len -= 1;
379
380       while (len > 0) {
381         if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 2))
382           goto need_more_data;
383         else if (tmp != 0x02)
384           goto error;
385
386         if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 6))
387           goto need_more_data;
388         flacparse->sample_number <<= 6;
389         flacparse->sample_number |= tmp;
390         len--;
391       }
392     }
393   }
394
395   /* calculate real blocksize from the blocksize index */
396   if (flacparse->block_size == 1)
397     flacparse->block_size = 192;
398   else if (flacparse->block_size <= 5)
399     flacparse->block_size = 576 * (1 << (flacparse->block_size - 2));
400   else if (flacparse->block_size <= 15)
401     flacparse->block_size = 256 * (1 << (flacparse->block_size - 8));
402   else if (flacparse->block_size == 6) {
403     if (!gst_bit_reader_get_bits_uint16 (&reader, &flacparse->block_size, 8))
404       goto need_more_data;
405     flacparse->block_size++;
406   } else if (flacparse->block_size == 7) {
407     if (!gst_bit_reader_get_bits_uint16 (&reader, &flacparse->block_size, 16))
408       goto need_more_data;
409     flacparse->block_size++;
410   }
411
412   /* calculate the real samplerate from the samplerate index */
413   if (samplerate == 0 && flacparse->samplerate == 0) {
414     goto need_streaminfo;
415   } else if (samplerate == 1) {
416     if (flacparse->samplerate == 0)
417       flacparse->samplerate = 88200;
418     else if (flacparse->samplerate != 88200)
419       goto error;
420   } else if (samplerate == 2) {
421     if (flacparse->samplerate == 0)
422       flacparse->samplerate = 176400;
423     else if (flacparse->samplerate != 176400)
424       goto error;
425   } else if (samplerate == 3) {
426     if (flacparse->samplerate == 0)
427       flacparse->samplerate = 192000;
428     else if (flacparse->samplerate != 192000)
429       goto error;
430   } else if (samplerate == 4) {
431     if (flacparse->samplerate == 0)
432       flacparse->samplerate = 8000;
433     else if (flacparse->samplerate != 8000)
434       goto error;
435   } else if (samplerate == 5) {
436     if (flacparse->samplerate == 0)
437       flacparse->samplerate = 16000;
438     else if (flacparse->samplerate != 16000)
439       goto error;
440   } else if (samplerate == 6) {
441     if (flacparse->samplerate == 0)
442       flacparse->samplerate = 22050;
443     else if (flacparse->samplerate != 22050)
444       goto error;
445   } else if (samplerate == 7) {
446     if (flacparse->samplerate == 0)
447       flacparse->samplerate = 24000;
448     else if (flacparse->samplerate != 24000)
449       goto error;
450   } else if (samplerate == 8) {
451     if (flacparse->samplerate == 0)
452       flacparse->samplerate = 32000;
453     else if (flacparse->samplerate != 32000)
454       goto error;
455   } else if (samplerate == 9) {
456     if (flacparse->samplerate == 0)
457       flacparse->samplerate = 44100;
458     else if (flacparse->samplerate != 44100)
459       goto error;
460   } else if (samplerate == 10) {
461     if (flacparse->samplerate == 0)
462       flacparse->samplerate = 48000;
463     else if (flacparse->samplerate != 48000)
464       goto error;
465   } else if (samplerate == 11) {
466     if (flacparse->samplerate == 0)
467       flacparse->samplerate = 96000;
468     else if (flacparse->samplerate != 96000)
469       goto error;
470   } else if (samplerate == 12) {
471     if (!gst_bit_reader_get_bits_uint16 (&reader, &samplerate, 8))
472       goto need_more_data;
473     samplerate *= 1000;
474     if (flacparse->samplerate == 0)
475       flacparse->samplerate = samplerate;
476     else if (flacparse->samplerate != samplerate)
477       goto error;
478   } else if (samplerate == 13) {
479     if (!gst_bit_reader_get_bits_uint16 (&reader, &samplerate, 16))
480       goto need_more_data;
481     if (flacparse->samplerate == 0)
482       flacparse->samplerate = samplerate;
483     else if (flacparse->samplerate != samplerate)
484       goto error;
485   } else if (samplerate == 14) {
486     if (!gst_bit_reader_get_bits_uint16 (&reader, &samplerate, 16))
487       goto need_more_data;
488     samplerate *= 10;
489     if (flacparse->samplerate == 0)
490       flacparse->samplerate = samplerate;
491     else if (flacparse->samplerate != samplerate)
492       goto error;
493   }
494
495   /* check crc-8 for the header */
496   if (!gst_bit_reader_get_bits_uint8 (&reader, &expected_crc, 8))
497     goto need_more_data;
498
499   actual_crc =
500       gst_flac_calculate_crc8 (GST_BUFFER_DATA (buffer),
501       (gst_bit_reader_get_pos (&reader) / 8) - 1);
502   if (actual_crc != expected_crc)
503     goto error;
504
505   /* parse subframes, one subframe per channel */
506   for (i = 0; i < flacparse->channels; i++) {
507     guint8 sf_type;
508     guint8 cur_bps;
509
510     cur_bps = flacparse->bps;
511
512     /* for mid/side, left/side, right/side the "difference" channel
513      * needs and additional bit */
514     if (i == 0 && channel_assignment == 2)
515       cur_bps++;
516     else if (i == 1 && (channel_assignment == 1 || channel_assignment == 3))
517       cur_bps++;
518
519     /* must be 0 */
520     if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
521       goto need_more_data;
522     else if (tmp != 0)
523       goto error;
524
525     /* sub frame type */
526     if (!gst_bit_reader_get_bits_uint8 (&reader, &sf_type, 6))
527       goto need_more_data;
528     else if (((sf_type & 0xfe) == 0x02) ||
529         ((sf_type & 0xfc) == 0x04) ||
530         ((sf_type & 0xf8) == 0x08 && (sf_type & 0x07) > 4) ||
531         ((sf_type & 0xf0) == 0x10))
532       goto error;
533
534     /* wasted bits per sample, if 1 the value follows unary coded */
535     if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1)) {
536       goto need_more_data;
537     } else if (tmp != 0) {
538       guint wasted = 1;
539
540       tmp = 0;
541       while (tmp == 0) {
542         if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
543           goto need_more_data;
544         else
545           wasted++;
546       }
547       cur_bps -= wasted;
548     }
549
550     /* subframe type: constant */
551     if (sf_type == 0x00) {
552       if (!gst_bit_reader_skip (&reader, cur_bps))
553         goto need_more_data;
554       /* subframe type: verbatim */
555     } else if (sf_type == 0x01) {
556       if (!gst_bit_reader_skip (&reader, cur_bps * flacparse->block_size))
557         goto need_more_data;
558       /* subframe type: LPC or fixed */
559     } else {
560       guint8 residual_type;
561       guint order = 0;
562       guint16 partition_order;
563       guint j;
564
565       /* Skip warm-up samples for fixed subframe and calculate order */
566       if ((sf_type & 0xf8) == 0x08) {
567         order = sf_type & 0x07;
568
569         g_assert (order <= 4);
570
571         if (!gst_bit_reader_skip (&reader, cur_bps * order))
572           goto need_more_data;
573         /* Skip warm-up samples for LPC subframe, get parameters and calculate order */
574       } else if ((sf_type & 0xe0) == 0x20) {
575         guint8 prec;
576
577         order = (sf_type & 0x1f) + 1;
578
579         /* warm-up samples */
580         if (!gst_bit_reader_skip (&reader, cur_bps * order))
581           goto need_more_data;
582
583         /* LPC coefficient precision */
584         if (!gst_bit_reader_get_bits_uint8 (&reader, &prec, 4))
585           goto need_more_data;
586         else if (prec == 0x0f)
587           goto error;
588         prec++;
589
590         /* LPC coefficient shift */
591         if (!gst_bit_reader_skip (&reader, 5))
592           goto need_more_data;
593
594         /* LPC coefficients */
595         if (!gst_bit_reader_skip (&reader, order * prec))
596           goto need_more_data;
597       } else {
598         g_assert_not_reached ();
599       }
600
601       /* residual type: 0 == rice, 1 == rice2 */
602       if (!gst_bit_reader_get_bits_uint8 (&reader, &residual_type, 2))
603         goto need_more_data;
604
605       if (residual_type & 0x02)
606         goto error;
607
608       /* partition order */
609       if (!gst_bit_reader_get_bits_uint16 (&reader, &partition_order, 4))
610         goto need_more_data;
611
612       partition_order = 1 << partition_order;
613
614       /* 2^partition_order partitions */
615       for (j = 0; j < partition_order; j++) {
616         guint samples;
617         guint8 rice_parameter;
618
619         /* calculate number of samples for the current partition */
620         if (partition_order == 1) {
621           samples = flacparse->block_size - order;
622         } else if (j != 0) {
623           samples = flacparse->block_size / partition_order;
624         } else {
625           samples = flacparse->block_size / partition_order - order;
626         }
627
628         /* rice parameter */
629         if (!gst_bit_reader_get_bits_uint8 (&reader, &rice_parameter,
630                 (residual_type == 0) ? 4 : 5))
631           goto need_more_data;
632
633         /* if rice parameter has all bits set the samples follow unencoded with the number of bits
634          * per sample in the following 5 bits */
635         if ((residual_type == 0 && rice_parameter == 0x0f)
636             || (residual_type == 1 && rice_parameter == 0x1f)) {
637           if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 5))
638             goto need_more_data;
639           if (!gst_bit_reader_skip (&reader, tmp * samples))
640             goto need_more_data;
641         } else {
642           guint k;
643
644           /* read the rice encoded samples */
645           for (k = 0; k < samples; k++) {
646             tmp = 0;
647             while (tmp == 0)
648               if (!gst_bit_reader_get_bits_uint8 (&reader, &tmp, 1))
649                 goto need_more_data;
650
651             if (!gst_bit_reader_skip (&reader, rice_parameter))
652               goto need_more_data;
653           }
654         }
655       }
656     }
657   }
658
659   /* zero padding to byte alignment */
660   gst_bit_reader_skip_to_byte (&reader);
661
662   /* Skip crc-16 for the complete frame */
663   if (!gst_bit_reader_skip (&reader, 16))
664     goto need_more_data;
665
666   *framesize_ret = gst_bit_reader_get_pos (&reader) / 8;
667
668   GST_DEBUG_OBJECT (flacparse, "Parsed frame at offset %" G_GUINT64_FORMAT ":\n"
669       "Frame size: %u\n"
670       "Block size: %u\n"
671       "Sample/Frame number: %" G_GUINT64_FORMAT,
672       flacparse->offset, *framesize_ret,
673       flacparse->block_size, flacparse->sample_number);
674
675   return 0;
676
677 need_more_data:
678   {
679     gint max;
680
681     /* not enough, if that was all available, give up on frame */
682     if (G_UNLIKELY (gst_base_parse_get_drain (GST_BASE_PARSE_CAST (flacparse))))
683       goto eos;
684     /* otherwise, ask for some more */
685     max = flacparse->max_framesize;
686     if (!max)
687       max = 1 << 24;
688     flacparse->requested_frame_size
689         = MIN (GST_BUFFER_SIZE (buffer) + 4096, max);
690     if (flacparse->requested_frame_size > GST_BUFFER_SIZE (buffer)) {
691       GST_DEBUG_OBJECT (flacparse, "Requesting %u bytes",
692           flacparse->requested_frame_size);
693       return flacparse->requested_frame_size;
694     } else {
695       GST_DEBUG_OBJECT (flacparse, "Giving up on invalid frame (%d bytes)",
696           GST_BUFFER_SIZE (buffer));
697       return -1;
698     }
699   }
700
701 need_streaminfo:
702   {
703     GST_ERROR_OBJECT (flacparse, "Need STREAMINFO");
704     return -2;
705   }
706
707 eos:
708   {
709     GST_WARNING_OBJECT (flacparse, "EOS");
710     return -1;
711   }
712
713 error:
714   {
715     GST_WARNING_OBJECT (flacparse, "Invalid frame");
716     return -1;
717   }
718 }
719
720 static gboolean
721 gst_flac_parse_check_valid_frame (GstBaseParse * parse, GstBuffer * buffer,
722     guint * framesize, gint * skipsize)
723 {
724   GstFlacParse *flacparse = GST_FLAC_PARSE (parse);
725   const guint8 *data = GST_BUFFER_DATA (buffer);
726
727   if (G_UNLIKELY (GST_BUFFER_SIZE (buffer) < 4))
728     return FALSE;
729
730   if (flacparse->state == GST_FLAC_PARSE_STATE_INIT) {
731     if (memcmp (GST_BUFFER_DATA (buffer), "fLaC", 4) == 0) {
732       GST_DEBUG_OBJECT (flacparse, "fLaC marker found");
733       *framesize = 4;
734       return TRUE;
735     } else if (data[0] == 0xff && (data[1] >> 2) == 0x3e) {
736       GST_DEBUG_OBJECT (flacparse, "Found headerless FLAC");
737       /* Minimal size of a frame header */
738       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), 16);
739       flacparse->requested_frame_size = 16;
740       flacparse->state = GST_FLAC_PARSE_STATE_GENERATE_HEADERS;
741       *skipsize = 0;
742       return FALSE;
743     } else {
744       GST_DEBUG_OBJECT (flacparse, "fLaC marker not found");
745       return FALSE;
746     }
747   } else if (flacparse->state == GST_FLAC_PARSE_STATE_HEADERS) {
748     guint size = 4 + ((data[1] << 16) | (data[2] << 8) | (data[3]));
749
750     GST_DEBUG_OBJECT (flacparse, "Found metadata block of size %u", size);
751     *framesize = size;
752     return TRUE;
753   } else {
754     if (data[0] == 0xff && (data[1] >> 2) == 0x3e) {
755       gint ret = 0;
756
757       flacparse->offset = GST_BUFFER_OFFSET (buffer);
758       flacparse->blocking_strategy = 0;
759       flacparse->block_size = 0;
760       flacparse->sample_number = 0;
761
762       GST_DEBUG_OBJECT (flacparse, "Found sync code");
763       ret = gst_flac_parse_get_frame_size (flacparse, buffer, framesize);
764       if (ret == 0) {
765         ret = *framesize;
766         /* if not in sync, also check for next frame header */
767         if (!gst_base_parse_get_sync (parse) &&
768             !gst_base_parse_get_drain (parse)) {
769           GST_DEBUG_OBJECT (flacparse, "Resyncing; checking next sync code");
770           if (GST_BUFFER_SIZE (buffer) >= ret + 2) {
771             if (data[ret] == 0xff && (data[ret + 1] >> 2) == 0x3e) {
772               GST_DEBUG_OBJECT (flacparse, "Found next sync code");
773               return TRUE;
774             } else {
775               GST_DEBUG_OBJECT (flacparse,
776                   "No next sync code, rejecting frame");
777               return FALSE;
778             }
779           } else {
780             /* request more data for next sync */
781             GST_DEBUG_OBJECT (flacparse, "... but not enough data");
782             ret += 2;
783             gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), ret);
784             flacparse->requested_frame_size = ret;
785             return FALSE;
786           }
787         }
788         return TRUE;
789       } else if (ret == -1) {
790         return FALSE;
791       } else if (ret == -2) {
792         GST_ELEMENT_ERROR (flacparse, STREAM, FORMAT, (NULL),
793             ("Need STREAMINFO for parsing"));
794         return FALSE;
795       } else if (ret > 0) {
796         *skipsize = 0;
797         gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), ret);
798         flacparse->requested_frame_size = ret;
799         return FALSE;
800       }
801     } else {
802       GstByteReader reader = GST_BYTE_READER_INIT_FROM_BUFFER (buffer);
803       gint off;
804
805       off = gst_byte_reader_masked_scan_uint32 (&reader, 0xfffc0000, 0xfff80000,
806           0, GST_BUFFER_SIZE (buffer));
807
808       if (off > 0) {
809         GST_DEBUG_OBJECT (parse, "Possible sync at buffer offset %d", off);
810         *skipsize = off;
811         return FALSE;
812       } else {
813         GST_DEBUG_OBJECT (flacparse, "Sync code not found");
814         *skipsize = GST_BUFFER_SIZE (buffer) - 3;
815         return FALSE;
816       }
817     }
818   }
819
820   return FALSE;
821 }
822
823 static gboolean
824 gst_flac_parse_handle_streaminfo (GstFlacParse * flacparse, GstBuffer * buffer)
825 {
826   GstBitReader reader = GST_BIT_READER_INIT_FROM_BUFFER (buffer);
827
828   if (GST_BUFFER_SIZE (buffer) != 4 + 34) {
829     GST_ERROR_OBJECT (flacparse, "Invalid metablock size for STREAMINFO: %u",
830         GST_BUFFER_SIZE (buffer));
831     return FALSE;
832   }
833
834   /* Skip metadata block header */
835   gst_bit_reader_skip (&reader, 32);
836
837   if (!gst_bit_reader_get_bits_uint16 (&reader, &flacparse->min_blocksize, 16))
838     goto error;
839   if (flacparse->min_blocksize < 16) {
840     GST_ERROR_OBJECT (flacparse, "Invalid minimum block size: %u",
841         flacparse->min_blocksize);
842     return FALSE;
843   }
844
845   if (!gst_bit_reader_get_bits_uint16 (&reader, &flacparse->max_blocksize, 16))
846     goto error;
847   if (flacparse->max_blocksize < 16) {
848     GST_ERROR_OBJECT (flacparse, "Invalid maximum block size: %u",
849         flacparse->max_blocksize);
850     return FALSE;
851   }
852
853   if (!gst_bit_reader_get_bits_uint32 (&reader, &flacparse->min_framesize, 24))
854     goto error;
855   if (!gst_bit_reader_get_bits_uint32 (&reader, &flacparse->max_framesize, 24))
856     goto error;
857
858   if (!gst_bit_reader_get_bits_uint32 (&reader, &flacparse->samplerate, 20))
859     goto error;
860   if (flacparse->samplerate == 0) {
861     GST_ERROR_OBJECT (flacparse, "Invalid sample rate 0");
862     return FALSE;
863   }
864
865   if (!gst_bit_reader_get_bits_uint8 (&reader, &flacparse->channels, 3))
866     goto error;
867   flacparse->channels++;
868   if (flacparse->channels > 8) {
869     GST_ERROR_OBJECT (flacparse, "Invalid number of channels %u",
870         flacparse->channels);
871     return FALSE;
872   }
873
874   if (!gst_bit_reader_get_bits_uint8 (&reader, &flacparse->bps, 5))
875     goto error;
876   flacparse->bps++;
877
878   if (!gst_bit_reader_get_bits_uint64 (&reader, &flacparse->total_samples, 36))
879     goto error;
880   if (flacparse->total_samples)
881     gst_base_parse_set_duration (GST_BASE_PARSE (flacparse), GST_FORMAT_TIME,
882         GST_FRAMES_TO_CLOCK_TIME (flacparse->total_samples,
883             flacparse->samplerate));
884
885   GST_DEBUG_OBJECT (flacparse, "STREAMINFO:\n"
886       "\tmin/max blocksize: %u/%u,\n"
887       "\tmin/max framesize: %u/%u,\n"
888       "\tsamplerate: %u,\n"
889       "\tchannels: %u,\n"
890       "\tbits per sample: %u,\n"
891       "\ttotal samples: %" G_GUINT64_FORMAT,
892       flacparse->min_blocksize, flacparse->max_blocksize,
893       flacparse->min_framesize, flacparse->max_framesize,
894       flacparse->samplerate,
895       flacparse->channels, flacparse->bps, flacparse->total_samples);
896
897   return TRUE;
898
899 error:
900   GST_ERROR_OBJECT (flacparse, "Failed to read data");
901   return FALSE;
902 }
903
904 static gboolean
905 gst_flac_parse_handle_vorbiscomment (GstFlacParse * flacparse,
906     GstBuffer * buffer)
907 {
908   flacparse->tags = gst_tag_list_from_vorbiscomment_buffer (buffer,
909       GST_BUFFER_DATA (buffer), 4, NULL);
910
911   if (flacparse->tags == NULL) {
912     GST_ERROR_OBJECT (flacparse, "Invalid vorbiscomment block");
913   } else if (gst_tag_list_is_empty (flacparse->tags)) {
914     gst_tag_list_free (flacparse->tags);
915     flacparse->tags = NULL;
916   }
917
918   return TRUE;
919 }
920
921 static gboolean
922 gst_flac_parse_handle_picture (GstFlacParse * flacparse, GstBuffer * buffer)
923 {
924   GstByteReader reader = GST_BYTE_READER_INIT_FROM_BUFFER (buffer);
925   const guint8 *data = GST_BUFFER_DATA (buffer);
926   guint32 img_len = 0, img_type = 0;
927   guint32 img_mimetype_len = 0, img_description_len = 0;
928
929   if (!gst_byte_reader_get_uint32_be (&reader, &img_type))
930     goto error;
931
932   if (!gst_byte_reader_get_uint32_be (&reader, &img_mimetype_len))
933     goto error;
934   if (!gst_byte_reader_skip (&reader, img_mimetype_len))
935     goto error;
936
937   if (!gst_byte_reader_get_uint32_be (&reader, &img_description_len))
938     goto error;
939   if (!gst_byte_reader_skip (&reader, img_description_len))
940     goto error;
941
942   if (!gst_byte_reader_skip (&reader, 4 * 4))
943     goto error;
944
945   if (!gst_byte_reader_get_uint32_be (&reader, &img_len))
946     goto error;
947
948   if (!flacparse->tags)
949     flacparse->tags = gst_tag_list_new ();
950
951   gst_tag_list_add_id3_image (flacparse->tags,
952       data + gst_byte_reader_get_pos (&reader), img_len, img_type);
953
954   if (gst_tag_list_is_empty (flacparse->tags)) {
955     gst_tag_list_free (flacparse->tags);
956     flacparse->tags = NULL;
957   }
958
959   return TRUE;
960
961 error:
962   GST_ERROR_OBJECT (flacparse, "Error reading data");
963   return FALSE;
964 }
965
966 static void
967 _value_array_append_buffer (GValue * array_val, GstBuffer * buf)
968 {
969   GValue value = { 0, };
970
971   g_value_init (&value, GST_TYPE_BUFFER);
972   /* copy buffer to avoid problems with circular refcounts */
973   buf = gst_buffer_copy (buf);
974   /* again, for good measure */
975   GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_IN_CAPS);
976   gst_value_set_buffer (&value, buf);
977   gst_buffer_unref (buf);
978   gst_value_array_append_value (array_val, &value);
979   g_value_unset (&value);
980 }
981
982 static gboolean
983 gst_flac_parse_handle_headers (GstFlacParse * flacparse)
984 {
985   GstBuffer *vorbiscomment = NULL;
986   GstBuffer *streaminfo = NULL;
987   GstBuffer *marker = NULL;
988   GValue array = { 0, };
989   GstCaps *caps;
990   GList *l;
991
992   caps = gst_caps_new_simple ("audio/x-flac",
993       "channels", G_TYPE_INT, flacparse->channels,
994       "rate", G_TYPE_INT, flacparse->samplerate, NULL);
995
996   if (!flacparse->headers)
997     goto push_headers;
998
999   for (l = flacparse->headers; l; l = l->next) {
1000     GstBuffer *header = l->data;
1001     const guint8 *data = GST_BUFFER_DATA (header);
1002     guint size = GST_BUFFER_SIZE (header);
1003
1004     GST_BUFFER_FLAG_SET (header, GST_BUFFER_FLAG_IN_CAPS);
1005
1006     if (size == 4 && memcmp (data, "fLaC", 4) == 0) {
1007       marker = header;
1008     } else if (size > 1 && (data[0] & 0x7f) == 0) {
1009       streaminfo = header;
1010     } else if (size > 1 && (data[0] & 0x7f) == 4) {
1011       vorbiscomment = header;
1012     }
1013   }
1014
1015   if (marker == NULL || streaminfo == NULL || vorbiscomment == NULL) {
1016     GST_WARNING_OBJECT (flacparse,
1017         "missing header %p %p %p, muxing into container "
1018         "formats may be broken", marker, streaminfo, vorbiscomment);
1019     goto push_headers;
1020   }
1021
1022   g_value_init (&array, GST_TYPE_ARRAY);
1023
1024   /* add marker including STREAMINFO header */
1025   {
1026     GstBuffer *buf;
1027     guint16 num;
1028
1029     /* minus one for the marker that is merged with streaminfo here */
1030     num = g_list_length (flacparse->headers) - 1;
1031
1032     buf = gst_buffer_new_and_alloc (13 + GST_BUFFER_SIZE (streaminfo));
1033     GST_BUFFER_DATA (buf)[0] = 0x7f;
1034     memcpy (GST_BUFFER_DATA (buf) + 1, "FLAC", 4);
1035     GST_BUFFER_DATA (buf)[5] = 0x01;    /* mapping version major */
1036     GST_BUFFER_DATA (buf)[6] = 0x00;    /* mapping version minor */
1037     GST_BUFFER_DATA (buf)[7] = (num & 0xFF00) >> 8;
1038     GST_BUFFER_DATA (buf)[8] = (num & 0x00FF) >> 0;
1039     memcpy (GST_BUFFER_DATA (buf) + 9, "fLaC", 4);
1040     memcpy (GST_BUFFER_DATA (buf) + 13, GST_BUFFER_DATA (streaminfo),
1041         GST_BUFFER_SIZE (streaminfo));
1042     _value_array_append_buffer (&array, buf);
1043     gst_buffer_unref (buf);
1044   }
1045
1046   /* add VORBISCOMMENT header */
1047   _value_array_append_buffer (&array, vorbiscomment);
1048
1049   /* add other headers, if there are any */
1050   for (l = flacparse->headers; l; l = l->next) {
1051     if (GST_BUFFER_CAST (l->data) != marker &&
1052         GST_BUFFER_CAST (l->data) != streaminfo &&
1053         GST_BUFFER_CAST (l->data) != vorbiscomment) {
1054       _value_array_append_buffer (&array, GST_BUFFER_CAST (l->data));
1055     }
1056   }
1057
1058   gst_structure_set_value (gst_caps_get_structure (caps, 0),
1059       "streamheader", &array);
1060   g_value_unset (&array);
1061
1062 push_headers:
1063
1064   gst_pad_set_caps (GST_BASE_PARSE_SRC_PAD (GST_BASE_PARSE (flacparse)), caps);
1065   gst_caps_unref (caps);
1066
1067   /* push header buffers; update caps, so when we push the first buffer the
1068    * negotiated caps will change to caps that include the streamheader field */
1069   for (l = flacparse->headers; l != NULL; l = l->next) {
1070     GstBuffer *buf = GST_BUFFER (l->data);
1071     GstFlowReturn ret;
1072
1073     l->data = NULL;
1074     buf = gst_buffer_make_metadata_writable (buf);
1075     gst_buffer_set_caps (buf,
1076         GST_PAD_CAPS (GST_BASE_PARSE_SRC_PAD (GST_BASE_PARSE (flacparse))));
1077
1078     ret = gst_base_parse_push_buffer (GST_BASE_PARSE (flacparse), buf);
1079     if (ret != GST_FLOW_OK)
1080       return FALSE;
1081   }
1082   g_list_free (flacparse->headers);
1083   flacparse->headers = NULL;
1084
1085   /* Push tags */
1086   if (flacparse->tags)
1087     gst_element_found_tags (GST_ELEMENT (flacparse),
1088         gst_tag_list_copy (flacparse->tags));
1089
1090   return TRUE;
1091 }
1092
1093 static gboolean
1094 gst_flac_parse_generate_headers (GstFlacParse * flacparse)
1095 {
1096   GstBuffer *marker, *streaminfo, *vorbiscomment;
1097   guint8 *data;
1098
1099   marker = gst_buffer_new_and_alloc (4);
1100   memcpy (GST_BUFFER_DATA (marker), "fLaC", 4);
1101   GST_BUFFER_TIMESTAMP (marker) = GST_CLOCK_TIME_NONE;
1102   GST_BUFFER_DURATION (marker) = GST_CLOCK_TIME_NONE;
1103   GST_BUFFER_OFFSET (marker) = 0;
1104   GST_BUFFER_OFFSET_END (marker) = 0;
1105   flacparse->headers = g_list_append (flacparse->headers, marker);
1106
1107   streaminfo = gst_buffer_new_and_alloc (4 + 34);
1108   data = GST_BUFFER_DATA (streaminfo);
1109   memset (data, 0, 4 + 34);
1110
1111   /* metadata block header */
1112   data[0] = 0x00;               /* is_last = 0; type = 0; */
1113   data[1] = 0x00;               /* length = 34; */
1114   data[2] = 0x00;
1115   data[3] = 0x22;
1116
1117   /* streaminfo */
1118
1119   data[4] = (flacparse->block_size >> 8) & 0xff;        /* min blocksize = blocksize; */
1120   data[5] = (flacparse->block_size) & 0xff;
1121   data[6] = (flacparse->block_size >> 8) & 0xff;        /* max blocksize = blocksize; */
1122   data[7] = (flacparse->block_size) & 0xff;
1123
1124   data[8] = 0x00;               /* min framesize = 0; */
1125   data[9] = 0x00;
1126   data[10] = 0x00;
1127   data[11] = 0x00;              /* max framesize = 0; */
1128   data[12] = 0x00;
1129   data[13] = 0x00;
1130
1131   data[14] = (flacparse->samplerate >> 12) & 0xff;
1132   data[15] = (flacparse->samplerate >> 4) & 0xff;
1133   data[16] = (flacparse->samplerate >> 0) & 0xf0;
1134
1135   data[16] |= (flacparse->channels - 1) << 1;
1136
1137   data[16] |= ((flacparse->bps - 1) >> 4) & 0x01;
1138   data[17] = (((flacparse->bps - 1)) & 0x0f) << 4;
1139
1140   {
1141     gint64 duration;
1142     GstFormat fmt = GST_FORMAT_TIME;
1143
1144     if (gst_pad_query_peer_duration (GST_BASE_PARSE_SINK_PAD (GST_BASE_PARSE
1145                 (flacparse)), &fmt, &duration) && fmt == GST_FORMAT_TIME) {
1146       duration = GST_CLOCK_TIME_TO_FRAMES (duration, flacparse->samplerate);
1147
1148       data[17] |= (duration >> 32) & 0xff;
1149       data[18] |= (duration >> 24) & 0xff;
1150       data[19] |= (duration >> 16) & 0xff;
1151       data[20] |= (duration >> 8) & 0xff;
1152       data[21] |= (duration >> 0) & 0xff;
1153     }
1154   }
1155   /* MD5 = 0; */
1156
1157   GST_BUFFER_TIMESTAMP (streaminfo) = GST_CLOCK_TIME_NONE;
1158   GST_BUFFER_DURATION (streaminfo) = GST_CLOCK_TIME_NONE;
1159   GST_BUFFER_OFFSET (streaminfo) = 0;
1160   GST_BUFFER_OFFSET_END (streaminfo) = 0;
1161   flacparse->headers = g_list_append (flacparse->headers, streaminfo);
1162
1163   /* empty vorbiscomment */
1164   {
1165     GstTagList *taglist = gst_tag_list_new ();
1166     guchar header[4];
1167     guint size;
1168
1169     header[0] = 0x84;           /* is_last = 1; type = 4; */
1170
1171     vorbiscomment =
1172         gst_tag_list_to_vorbiscomment_buffer (taglist, header, sizeof (header),
1173         NULL);
1174     gst_tag_list_free (taglist);
1175
1176     /* Get rid of framing bit */
1177     if (GST_BUFFER_DATA (vorbiscomment)[GST_BUFFER_SIZE (vorbiscomment) - 1] ==
1178         1) {
1179       GstBuffer *sub;
1180
1181       sub =
1182           gst_buffer_create_sub (vorbiscomment, 0,
1183           GST_BUFFER_SIZE (vorbiscomment) - 1);
1184       gst_buffer_unref (vorbiscomment);
1185       vorbiscomment = sub;
1186     }
1187
1188     size = GST_BUFFER_SIZE (vorbiscomment) - 4;
1189     GST_BUFFER_DATA (vorbiscomment)[1] = ((size & 0xFF0000) >> 16);
1190     GST_BUFFER_DATA (vorbiscomment)[2] = ((size & 0x00FF00) >> 8);
1191     GST_BUFFER_DATA (vorbiscomment)[3] = (size & 0x0000FF);
1192
1193     GST_BUFFER_TIMESTAMP (vorbiscomment) = GST_CLOCK_TIME_NONE;
1194     GST_BUFFER_DURATION (vorbiscomment) = GST_CLOCK_TIME_NONE;
1195     GST_BUFFER_OFFSET (vorbiscomment) = 0;
1196     GST_BUFFER_OFFSET_END (vorbiscomment) = 0;
1197     flacparse->headers = g_list_append (flacparse->headers, vorbiscomment);
1198   }
1199
1200   return TRUE;
1201 }
1202
1203 static GstFlowReturn
1204 gst_flac_parse_parse_frame (GstBaseParse * parse, GstBuffer * buffer)
1205 {
1206   GstFlacParse *flacparse = GST_FLAC_PARSE (parse);
1207   const guint8 *data = GST_BUFFER_DATA (buffer);
1208
1209   if (flacparse->state == GST_FLAC_PARSE_STATE_INIT) {
1210     GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
1211     GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
1212     GST_BUFFER_OFFSET (buffer) = 0;
1213     GST_BUFFER_OFFSET_END (buffer) = 0;
1214
1215     /* 32 bits metadata block */
1216     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), 4);
1217     flacparse->state = GST_FLAC_PARSE_STATE_HEADERS;
1218
1219     flacparse->headers =
1220         g_list_append (flacparse->headers, gst_buffer_ref (buffer));
1221
1222     return GST_BASE_PARSE_FLOW_DROPPED;
1223   } else if (flacparse->state == GST_FLAC_PARSE_STATE_HEADERS) {
1224     gboolean is_last = ((data[0] & 0x80) == 0x80);
1225     guint type = (data[0] & 0x7F);
1226
1227     if (type == 127) {
1228       GST_WARNING_OBJECT (flacparse, "Invalid metadata block type");
1229       return GST_BASE_PARSE_FLOW_DROPPED;
1230     }
1231
1232     GST_DEBUG_OBJECT (flacparse, "Handling metadata block of type %u", type);
1233
1234     switch (type) {
1235       case 0:                  /* STREAMINFO */
1236         if (!gst_flac_parse_handle_streaminfo (flacparse, buffer))
1237           return GST_FLOW_ERROR;
1238         break;
1239       case 3:                  /* SEEKTABLE */
1240         /* TODO: handle seektables */
1241         break;
1242       case 4:                  /* VORBIS_COMMENT */
1243         if (!gst_flac_parse_handle_vorbiscomment (flacparse, buffer))
1244           return GST_FLOW_ERROR;
1245         break;
1246       case 6:                  /* PICTURE */
1247         if (!gst_flac_parse_handle_picture (flacparse, buffer))
1248           return GST_FLOW_ERROR;
1249         break;
1250       case 1:                  /* PADDING */
1251       case 2:                  /* APPLICATION */
1252       case 5:                  /* CUESHEET */
1253       default:                 /* RESERVED */
1254         break;
1255     }
1256
1257     GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
1258     GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
1259     GST_BUFFER_OFFSET (buffer) = 0;
1260     GST_BUFFER_OFFSET_END (buffer) = 0;
1261
1262     if (is_last) {
1263       flacparse->headers =
1264           g_list_append (flacparse->headers, gst_buffer_ref (buffer));
1265
1266       if (!gst_flac_parse_handle_headers (flacparse))
1267         return GST_FLOW_ERROR;
1268
1269       /* Minimal size of a frame header */
1270       gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), MAX (16,
1271               flacparse->min_framesize));
1272       flacparse->requested_frame_size = MAX (16, flacparse->min_framesize);
1273       flacparse->state = GST_FLAC_PARSE_STATE_DATA;
1274
1275       /* DROPPED because we pushed all headers manually already */
1276       return GST_BASE_PARSE_FLOW_DROPPED;
1277     } else {
1278       flacparse->headers =
1279           g_list_append (flacparse->headers, gst_buffer_ref (buffer));
1280       return GST_BASE_PARSE_FLOW_DROPPED;
1281     }
1282   } else {
1283     if (flacparse->offset != GST_BUFFER_OFFSET (buffer)) {
1284       gint ret;
1285       guint framesize;
1286
1287       flacparse->offset = GST_BUFFER_OFFSET (buffer);
1288       ret = gst_flac_parse_get_frame_size (flacparse, buffer, &framesize);
1289       if (ret != 0) {
1290         GST_ERROR_OBJECT (flacparse,
1291             "Baseclass didn't provide a complete frame");
1292         return GST_FLOW_ERROR;
1293       }
1294     }
1295
1296     if (flacparse->block_size == 0) {
1297       GST_ERROR_OBJECT (flacparse, "Unparsed frame");
1298       return GST_FLOW_ERROR;
1299     }
1300
1301     if (flacparse->state == GST_FLAC_PARSE_STATE_GENERATE_HEADERS) {
1302       if (flacparse->blocking_strategy == 1) {
1303         GST_WARNING_OBJECT (flacparse,
1304             "Generating headers for variable blocksize streams not supported");
1305
1306         if (!gst_flac_parse_handle_headers (flacparse))
1307           return GST_FLOW_ERROR;
1308       } else {
1309         GST_DEBUG_OBJECT (flacparse, "Generating headers");
1310
1311         if (!gst_flac_parse_generate_headers (flacparse))
1312           return GST_FLOW_ERROR;
1313
1314         if (!gst_flac_parse_handle_headers (flacparse))
1315           return GST_FLOW_ERROR;
1316       }
1317       flacparse->state = GST_FLAC_PARSE_STATE_DATA;
1318     }
1319
1320     /* also cater for oggmux metadata */
1321     if (flacparse->blocking_strategy == 0) {
1322       GST_BUFFER_TIMESTAMP (buffer) =
1323           gst_util_uint64_scale (flacparse->sample_number,
1324           flacparse->block_size * GST_SECOND, flacparse->samplerate);
1325       GST_BUFFER_OFFSET_END (buffer) =
1326           flacparse->sample_number * flacparse->block_size +
1327           flacparse->block_size;
1328     } else {
1329       GST_BUFFER_TIMESTAMP (buffer) =
1330           gst_util_uint64_scale (flacparse->sample_number, GST_SECOND,
1331           flacparse->samplerate);
1332       GST_BUFFER_OFFSET_END (buffer) =
1333           flacparse->sample_number + flacparse->block_size;
1334     }
1335     GST_BUFFER_DURATION (buffer) =
1336         GST_FRAMES_TO_CLOCK_TIME (flacparse->block_size, flacparse->samplerate);
1337     GST_BUFFER_OFFSET (buffer) =
1338         GST_BUFFER_TIMESTAMP (buffer) + GST_BUFFER_DURATION (buffer);
1339
1340     /* Minimal size of a frame header */
1341     gst_base_parse_set_min_frame_size (GST_BASE_PARSE (flacparse), MAX (16,
1342             flacparse->min_framesize));
1343     flacparse->requested_frame_size = MAX (16, flacparse->min_framesize);
1344
1345     flacparse->offset = -1;
1346     flacparse->blocking_strategy = 0;
1347     flacparse->block_size = 0;
1348     flacparse->sample_number = 0;
1349     return GST_FLOW_OK;
1350   }
1351 }
1352
1353 static gint
1354 gst_flac_parse_get_frame_overhead (GstBaseParse * parse, GstBuffer * buffer)
1355 {
1356   GstFlacParse *flacparse = GST_FLAC_PARSE (parse);
1357
1358   if (flacparse->state != GST_FLAC_PARSE_STATE_DATA)
1359     return -1;
1360   else
1361     /* To simplify, we just assume that it's a fixed size header and ignore
1362      * subframe headers. The first could lead us to being off by 88 bits and
1363      * the second even less, so the total inaccuracy is negligible. */
1364     return 7;
1365 }