1 /*
2 * Copyright (c) 2006 Christophe Fergeau <teuf@gnome.org>
3 * Copyright (c) 2008 Sebastian Dröge <slomo@circular-chaos.org>
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Library General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
14 *
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
18 * Boston, MA 02110-1301, USA.
19 */
20
21 /* Xing SDK: http://www.mp3-tech.org/programmer/sources/vbrheadersdk.zip */
22
23
24 /**
25 * SECTION:element-xingmux
26 *
27 * xingmux adds a Xing header to MP3 files. This contains information about the duration and size
28 * of the file and a seek table and is very useful for getting an almost correct duration and better
29 * seeking on VBR MP3 files.
30 *
31 * This element will remove any existing Xing, LAME or VBRI headers from the beginning of the file.
32 *
33 * <refsect2>
34 * <title>Example launch line</title>
35 * |[
36 * gst-launch-1.0 audiotestsrc num-buffers=1000 ! audioconvert ! lamemp3enc ! xingmux ! filesink location=test.mp3
37 * gst-launch-1.0 filesrc location=test.mp3 ! xingmux ! filesink location=test2.mp3
38 * gst-launch-1.0 filesrc location=test.mp3 ! mp3parse ! xingmux ! filesink location=test2.mp3
39 * ]|
40 * </refsect2>
41 */
42
43 #ifdef HAVE_CONFIG_H
44 #include <config.h>
45 #endif
46
47 #include <string.h>
48 #include "gstxingmux.h"
49
50 GST_DEBUG_CATEGORY_STATIC (xing_mux_debug);
51 #define GST_CAT_DEFAULT xing_mux_debug
52
53 #define gst_xing_mux_parent_class parent_class
54 G_DEFINE_TYPE (GstXingMux, gst_xing_mux, GST_TYPE_ELEMENT);
55
56 /* Xing Header stuff */
57 #define GST_XING_FRAME_FIELD (1 << 0)
58 #define GST_XING_BYTES_FIELD (1 << 1)
59 #define GST_XING_TOC_FIELD (1 << 2)
60 #define GST_XING_QUALITY_FIELD (1 << 3)
61
62 typedef struct _GstXingSeekEntry
63 {
64 gint64 timestamp;
65 gint byte;
66 } GstXingSeekEntry;
67
68 static inline GstXingSeekEntry *
gst_xing_seek_entry_new(void)69 gst_xing_seek_entry_new (void)
70 {
71 return g_slice_new (GstXingSeekEntry);
72 }
73
74 static inline void
gst_xing_seek_entry_free(GstXingSeekEntry * entry)75 gst_xing_seek_entry_free (GstXingSeekEntry * entry)
76 {
77 g_slice_free (GstXingSeekEntry, entry);
78 }
79
80 static void gst_xing_mux_finalize (GObject * obj);
81 static GstStateChangeReturn
82 gst_xing_mux_change_state (GstElement * element, GstStateChange transition);
83 static GstFlowReturn gst_xing_mux_chain (GstPad * pad, GstObject * parent,
84 GstBuffer * buffer);
85 static gboolean gst_xing_mux_sink_event (GstPad * pad, GstObject * parent,
86 GstEvent * event);
87
88 static GstStaticPadTemplate gst_xing_mux_sink_template =
89 GST_STATIC_PAD_TEMPLATE ("sink",
90 GST_PAD_SINK,
91 GST_PAD_ALWAYS,
92 GST_STATIC_CAPS ("audio/mpeg, "
93 "mpegversion = (int) 1, " "layer = (int) [ 1, 3 ]"));
94
95
96 static GstStaticPadTemplate gst_xing_mux_src_template =
97 GST_STATIC_PAD_TEMPLATE ("src",
98 GST_PAD_SRC,
99 GST_PAD_ALWAYS,
100 GST_STATIC_CAPS ("audio/mpeg, "
101 "mpegversion = (int) 1, " "layer = (int) [ 1, 3 ]"));
102 static const guint mp3types_bitrates[2][3][16] = {
103 {
104 {0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,},
105 {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,},
106 {0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,}
107 },
108 {
109 {0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,},
110 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,},
111 {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160,}
112 },
113 };
114
115 static const guint mp3types_freqs[3][3] = { {44100, 48000, 32000},
116 {22050, 24000, 16000},
117 {11025, 12000, 8000}
118 };
119
120 static gboolean
parse_header(guint32 header,guint * ret_size,guint * ret_spf,gulong * ret_rate)121 parse_header (guint32 header, guint * ret_size, guint * ret_spf,
122 gulong * ret_rate)
123 {
124 guint length, spf;
125 gulong samplerate, bitrate, layer, padding;
126 gint lsf, mpg25;
127
128 if ((header & 0xffe00000) != 0xffe00000) {
129 g_warning ("invalid sync");
130 return FALSE;
131 }
132
133 if (((header >> 19) & 3) == 0x01) {
134 g_warning ("invalid MPEG version");
135 return FALSE;
136 }
137
138 if (((header >> 17) & 3) == 0x00) {
139 g_warning ("invalid MPEG layer");
140 return FALSE;
141 }
142
143 if (((header >> 12) & 0xf) == 0xf || ((header >> 12) & 0xf) == 0x0) {
144 g_warning ("invalid bitrate");
145 return FALSE;
146 }
147
148 if (((header >> 10) & 0x3) == 0x3) {
149 g_warning ("invalid sampling rate");
150 return FALSE;
151 }
152
153 if (header & 0x00000002) {
154 g_warning ("invalid emphasis");
155 return FALSE;
156 }
157
158 if (header & (1 << 20)) {
159 lsf = (header & (1 << 19)) ? 0 : 1;
160 mpg25 = 0;
161 } else {
162 lsf = 1;
163 mpg25 = 1;
164 }
165
166 layer = 4 - ((header >> 17) & 0x3);
167
168 bitrate = (header >> 12) & 0xF;
169 bitrate = mp3types_bitrates[lsf][layer - 1][bitrate] * 1000;
170 if (bitrate == 0)
171 return FALSE;
172
173 samplerate = (header >> 10) & 0x3;
174 samplerate = mp3types_freqs[lsf + mpg25][samplerate];
175
176 padding = (header >> 9) & 0x1;
177
178 switch (layer) {
179 case 1:
180 length = 4 * ((bitrate * 12) / samplerate + padding);
181 break;
182 case 2:
183 length = (bitrate * 144) / samplerate + padding;
184 break;
185 default:
186 case 3:
187 length = (bitrate * 144) / (samplerate << lsf) + padding;
188 break;
189 }
190
191 if (layer == 1)
192 spf = 384;
193 else if (layer == 2 || lsf == 0)
194 spf = 1152;
195 else
196 spf = 576;
197
198 if (ret_size)
199 *ret_size = length;
200 if (ret_spf)
201 *ret_spf = spf;
202 if (ret_rate)
203 *ret_rate = samplerate;
204
205 return TRUE;
206 }
207
208 static guint
get_xing_offset(guint32 header)209 get_xing_offset (guint32 header)
210 {
211 guint mpeg_version = (header >> 19) & 0x3;
212 guint channel_mode = (header >> 6) & 0x3;
213
214 if (mpeg_version == 0x3) {
215 if (channel_mode == 0x3) {
216 return 0x11;
217 } else {
218 return 0x20;
219 }
220 } else {
221 if (channel_mode == 0x3) {
222 return 0x09;
223 } else {
224 return 0x11;
225 }
226 }
227 }
228
229 static gboolean
has_xing_header(guint32 header,GstBuffer * buffer,gsize size)230 has_xing_header (guint32 header, GstBuffer * buffer, gsize size)
231 {
232 gboolean ret;
233 GstMapInfo map;
234 guint8 *data;
235
236 gst_buffer_map (buffer, &map, GST_MAP_READ);
237 data = map.data;
238 data += 4;
239 data += get_xing_offset (header);
240
241 if (memcmp (data, "Xing", 4) == 0 ||
242 memcmp (data, "Info", 4) == 0 || memcmp (data, "VBRI", 4) == 0)
243 ret = TRUE;
244 else
245 ret = FALSE;
246
247 gst_buffer_unmap (buffer, &map);
248 return ret;
249 }
250
251 static GstBuffer *
generate_xing_header(GstXingMux * xing)252 generate_xing_header (GstXingMux * xing)
253 {
254 guint8 *xing_flags;
255 guint32 xing_flags_tmp = 0;
256 GstBuffer *xing_header;
257 GstMapInfo map;
258 guchar *data;
259
260 guint32 header;
261 guint32 header_be;
262 guint size, spf, xing_offset;
263 gulong rate;
264 guint bitrate = 0x00;
265
266 gint64 duration;
267 gint64 byte_count;
268
269 header = xing->first_header;
270
271 /* Set bitrate and choose lowest possible size */
272 do {
273 bitrate++;
274
275 header &= 0xffff0fff;
276 header |= bitrate << 12;
277
278 if (!parse_header (header, &size, &spf, &rate)) {
279 GST_ERROR ("Failed to parse header!");
280 return NULL;
281 }
282 xing_offset = get_xing_offset (header);
283 } while (size < (4 + xing_offset + 4 + 4 + 4 + 4 + 100) && bitrate < 0xe);
284
285 if (bitrate == 0xe) {
286 GST_ERROR ("No usable bitrate found!");
287 return NULL;
288 }
289
290 xing_header = gst_buffer_new_and_alloc (size);
291
292 gst_buffer_map (xing_header, &map, GST_MAP_WRITE);
293 data = map.data;
294 memset (data, 0, size);
295 header_be = GUINT32_TO_BE (header);
296 memcpy (data, &header_be, 4);
297
298 data += 4;
299 data += xing_offset;
300
301 memcpy (data, "Xing", 4);
302 data += 4;
303
304 xing_flags = data;
305 data += 4;
306
307 if (xing->duration != GST_CLOCK_TIME_NONE) {
308 duration = xing->duration;
309 } else {
310 GstFormat fmt = GST_FORMAT_TIME;
311
312 if (!gst_pad_peer_query_duration (xing->sinkpad, fmt, &duration))
313 duration = GST_CLOCK_TIME_NONE;
314 }
315
316 if (duration != GST_CLOCK_TIME_NONE) {
317 guint32 number_of_frames;
318
319 /* The Xing Header contains a NumberOfFrames field, which verifies to:
320 * Duration = NumberOfFrames *SamplesPerFrame/SamplingRate
321 * SamplesPerFrame and SamplingRate are values for the current frame.
322 */
323 number_of_frames = gst_util_uint64_scale (duration, rate, GST_SECOND) / spf;
324 number_of_frames += 1; /* Xing Header Frame */
325 GST_DEBUG ("Setting number of frames to %u", number_of_frames);
326 number_of_frames = GUINT32_TO_BE (number_of_frames);
327 memcpy (data, &number_of_frames, 4);
328 xing_flags_tmp |= GST_XING_FRAME_FIELD;
329 data += 4;
330 }
331
332 if (xing->byte_count != 0) {
333 byte_count = xing->byte_count;
334 } else {
335 GstFormat fmt = GST_FORMAT_BYTES;
336
337 if (!gst_pad_peer_query_duration (xing->sinkpad, fmt, &byte_count))
338 byte_count = 0;
339 if (byte_count == -1)
340 byte_count = 0;
341 }
342
343 if (byte_count != 0) {
344 guint32 nbytes;
345
346 if (byte_count > G_MAXUINT32) {
347 GST_DEBUG ("Too large stream: %" G_GINT64_FORMAT " > %u bytes",
348 byte_count, G_MAXUINT32);
349 } else {
350 nbytes = byte_count;
351 GST_DEBUG ("Setting number of bytes to %u", nbytes);
352 nbytes = GUINT32_TO_BE (nbytes);
353 memcpy (data, &nbytes, 4);
354 xing_flags_tmp |= GST_XING_BYTES_FIELD;
355 data += 4;
356 }
357 }
358
359 if (xing->seek_table != NULL && byte_count != 0
360 && duration != GST_CLOCK_TIME_NONE) {
361 GList *it;
362 gint percent = 0;
363
364 xing_flags_tmp |= GST_XING_TOC_FIELD;
365
366 GST_DEBUG ("Writing seek table");
367 for (it = xing->seek_table; it != NULL && percent < 100; it = it->next) {
368 GstXingSeekEntry *entry = (GstXingSeekEntry *) it->data;
369 gint64 pos;
370 guchar byte;
371
372 while ((entry->timestamp * 100) / duration >= percent) {
373 pos = (entry->byte * 256) / byte_count;
374 GST_DEBUG (" %d %% -- %" G_GINT64_FORMAT " 1/256", percent, pos);
375 byte = (guchar) pos;
376 memcpy (data, &byte, 1);
377 data++;
378 percent++;
379 }
380 }
381
382 if (percent < 100) {
383 guchar b;
384 gint i;
385
386 memcpy (&b, data - 1, 1);
387
388 for (i = percent; i < 100; i++) {
389 GST_DEBUG (" %d %% -- %d 1/256", i, b);
390 memcpy (data, &b, 1);
391 data++;
392 }
393 }
394 }
395
396 GST_DEBUG ("Setting Xing flags to 0x%x\n", xing_flags_tmp);
397 xing_flags_tmp = GUINT32_TO_BE (xing_flags_tmp);
398 memcpy (xing_flags, &xing_flags_tmp, 4);
399 gst_buffer_unmap (xing_header, &map);
400 return xing_header;
401 }
402
403 static void
gst_xing_mux_class_init(GstXingMuxClass * klass)404 gst_xing_mux_class_init (GstXingMuxClass * klass)
405 {
406 GObjectClass *gobject_class;
407 GstElementClass *gstelement_class;
408
409 gobject_class = (GObjectClass *) klass;
410 gstelement_class = (GstElementClass *) klass;
411
412 gobject_class->finalize = GST_DEBUG_FUNCPTR (gst_xing_mux_finalize);
413 gstelement_class->change_state =
414 GST_DEBUG_FUNCPTR (gst_xing_mux_change_state);
415
416 gst_element_class_add_static_pad_template (gstelement_class,
417 &gst_xing_mux_src_template);
418 gst_element_class_add_static_pad_template (gstelement_class,
419 &gst_xing_mux_sink_template);
420
421 GST_DEBUG_CATEGORY_INIT (xing_mux_debug, "xingmux", 0, "Xing Header Muxer");
422
423 gst_element_class_set_static_metadata (gstelement_class, "MP3 Xing muxer",
424 "Formatter/Muxer/Metadata",
425 "Adds a Xing header to the beginning of a VBR MP3 file",
426 "Christophe Fergeau <teuf@gnome.org>");
427 }
428
429 static void
gst_xing_mux_finalize(GObject * obj)430 gst_xing_mux_finalize (GObject * obj)
431 {
432 GstXingMux *xing = GST_XING_MUX (obj);
433
434 if (xing->adapter) {
435 g_object_unref (xing->adapter);
436 xing->adapter = NULL;
437 }
438
439 if (xing->seek_table) {
440 g_list_foreach (xing->seek_table, (GFunc) gst_xing_seek_entry_free, NULL);
441 g_list_free (xing->seek_table);
442 xing->seek_table = NULL;
443 }
444
445 G_OBJECT_CLASS (parent_class)->finalize (obj);
446 }
447
448 static void
xing_reset(GstXingMux * xing)449 xing_reset (GstXingMux * xing)
450 {
451 xing->duration = GST_CLOCK_TIME_NONE;
452 xing->byte_count = 0;
453
454 gst_adapter_clear (xing->adapter);
455
456 if (xing->seek_table) {
457 g_list_foreach (xing->seek_table, (GFunc) gst_xing_seek_entry_free, NULL);
458 g_list_free (xing->seek_table);
459 xing->seek_table = NULL;
460 }
461
462 xing->sent_xing = FALSE;
463 }
464
465
466 static void
gst_xing_mux_init(GstXingMux * xing)467 gst_xing_mux_init (GstXingMux * xing)
468 {
469 /* pad through which data comes in to the element */
470 xing->sinkpad =
471 gst_pad_new_from_static_template (&gst_xing_mux_sink_template, "sink");
472 gst_pad_set_chain_function (xing->sinkpad,
473 GST_DEBUG_FUNCPTR (gst_xing_mux_chain));
474 gst_pad_set_event_function (xing->sinkpad,
475 GST_DEBUG_FUNCPTR (gst_xing_mux_sink_event));
476 GST_PAD_SET_PROXY_CAPS (xing->sinkpad);
477 gst_element_add_pad (GST_ELEMENT (xing), xing->sinkpad);
478
479 /* pad through which data goes out of the element */
480 xing->srcpad =
481 gst_pad_new_from_static_template (&gst_xing_mux_src_template, "src");
482 gst_element_add_pad (GST_ELEMENT (xing), xing->srcpad);
483
484 xing->adapter = gst_adapter_new ();
485
486 xing_reset (xing);
487 }
488
489 static GstFlowReturn
gst_xing_mux_chain(GstPad * pad,GstObject * parent,GstBuffer * buffer)490 gst_xing_mux_chain (GstPad * pad, GstObject * parent, GstBuffer * buffer)
491 {
492 GstXingMux *xing = GST_XING_MUX (parent);
493 GstFlowReturn ret = GST_FLOW_OK;
494
495 gst_adapter_push (xing->adapter, buffer);
496
497 while (gst_adapter_available (xing->adapter) >= 4) {
498 const guchar *data;
499 guint32 header;
500 GstBuffer *outbuf;
501 GstClockTime duration;
502 guint size, spf;
503 gulong rate;
504 GstXingSeekEntry *seek_entry;
505
506 data = gst_adapter_map (xing->adapter, 4);
507 header = GST_READ_UINT32_BE (data);
508 gst_adapter_unmap (xing->adapter);
509
510 if (!parse_header (header, &size, &spf, &rate)) {
511 GST_DEBUG ("Lost sync, resyncing");
512 gst_adapter_flush (xing->adapter, 1);
513 continue;
514 }
515
516 if (gst_adapter_available (xing->adapter) < size)
517 break;
518
519 outbuf = gst_adapter_take_buffer (xing->adapter, size);
520
521 if (!xing->sent_xing) {
522 if (has_xing_header (header, outbuf, size)) {
523 GST_LOG_OBJECT (xing, "Dropping old Xing header");
524 gst_buffer_unref (outbuf);
525 continue;
526 } else {
527 GstBuffer *xing_header;
528 guint64 xing_header_size;
529
530 xing->first_header = header;
531
532 xing_header = generate_xing_header (xing);
533
534 if (xing_header == NULL) {
535 GST_ERROR ("Can't generate Xing header");
536 gst_buffer_unref (outbuf);
537 return GST_FLOW_ERROR;
538 }
539
540 xing_header_size = gst_buffer_get_size (xing_header);
541
542 if ((ret = gst_pad_push (xing->srcpad, xing_header)) != GST_FLOW_OK) {
543 GST_ERROR_OBJECT (xing, "Failed to push Xing header: %s",
544 gst_flow_get_name (ret));
545 gst_buffer_unref (xing_header);
546 gst_buffer_unref (outbuf);
547 return ret;
548 }
549
550 xing->byte_count += xing_header_size;
551 xing->sent_xing = TRUE;
552 }
553 }
554
555 seek_entry = gst_xing_seek_entry_new ();
556 seek_entry->timestamp =
557 (xing->duration == GST_CLOCK_TIME_NONE) ? 0 : xing->duration;
558 /* Workaround for parsers checking that the first seek table entry is 0 */
559 seek_entry->byte = (seek_entry->timestamp == 0) ? 0 : xing->byte_count;
560 xing->seek_table = g_list_append (xing->seek_table, seek_entry);
561
562 duration = gst_util_uint64_scale_ceil (spf, GST_SECOND, rate);
563
564 GST_BUFFER_TIMESTAMP (outbuf) =
565 (xing->duration == GST_CLOCK_TIME_NONE) ? 0 : xing->duration;
566 GST_BUFFER_DURATION (outbuf) = duration;
567 GST_BUFFER_OFFSET (outbuf) = xing->byte_count;
568 xing->byte_count += gst_buffer_get_size (outbuf);
569 GST_BUFFER_OFFSET_END (outbuf) = xing->byte_count;
570
571 if (xing->duration == GST_CLOCK_TIME_NONE)
572 xing->duration = duration;
573 else
574 xing->duration += duration;
575
576 if ((ret = gst_pad_push (xing->srcpad, outbuf)) != GST_FLOW_OK) {
577 GST_ERROR_OBJECT (xing, "Failed to push MP3 frame: %s",
578 gst_flow_get_name (ret));
579 return ret;
580 }
581 }
582
583 return ret;
584 }
585
586 static gboolean
gst_xing_mux_sink_event(GstPad * pad,GstObject * parent,GstEvent * event)587 gst_xing_mux_sink_event (GstPad * pad, GstObject * parent, GstEvent * event)
588 {
589 GstXingMux *xing;
590 gboolean result;
591
592 xing = GST_XING_MUX (parent);
593
594 switch (GST_EVENT_TYPE (event)) {
595 case GST_EVENT_SEGMENT:
596 if (xing->sent_xing) {
597 GST_ERROR ("Already sent Xing header, dropping NEWSEGMENT event!");
598 gst_event_unref (event);
599 result = FALSE;
600 } else {
601 GstSegment segment;
602
603 gst_event_copy_segment (event, &segment);
604
605 if (segment.format == GST_FORMAT_BYTES) {
606 result = gst_pad_push_event (xing->srcpad, event);
607 } else {
608
609 gst_event_unref (event);
610 gst_segment_init (&segment, GST_FORMAT_BYTES);
611 event = gst_event_new_segment (&segment);
612
613 result = gst_pad_push_event (xing->srcpad, event);
614 }
615 }
616 break;
617
618 case GST_EVENT_EOS:{
619 GstEvent *n_event;
620
621 GST_DEBUG_OBJECT (xing, "handling EOS event");
622
623 if (xing->sent_xing) {
624 GstSegment segment;
625
626 gst_segment_init (&segment, GST_FORMAT_BYTES);
627 n_event = gst_event_new_segment (&segment);
628
629 if (G_UNLIKELY (!gst_pad_push_event (xing->srcpad, n_event))) {
630 GST_WARNING
631 ("Failed to seek to position 0 for pushing the Xing header");
632 } else {
633 GstBuffer *header;
634 GstFlowReturn ret;
635
636 header = generate_xing_header (xing);
637
638 if (header == NULL) {
639 GST_ERROR ("Can't generate Xing header");
640 } else {
641
642 GST_INFO ("Writing real Xing header to beginning of stream");
643
644 if ((ret = gst_pad_push (xing->srcpad, header)) != GST_FLOW_OK)
645 GST_WARNING ("Failed to push updated Xing header: %s\n",
646 gst_flow_get_name (ret));
647 }
648 }
649 }
650 result = gst_pad_push_event (xing->srcpad, event);
651 break;
652 }
653 default:
654 result = gst_pad_event_default (pad, parent, event);
655 break;
656 }
657
658 return result;
659 }
660
661
662 static GstStateChangeReturn
gst_xing_mux_change_state(GstElement * element,GstStateChange transition)663 gst_xing_mux_change_state (GstElement * element, GstStateChange transition)
664 {
665 GstXingMux *xing;
666 GstStateChangeReturn result;
667
668 xing = GST_XING_MUX (element);
669
670 result = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
671
672 switch (transition) {
673 case GST_STATE_CHANGE_PAUSED_TO_READY:
674 xing_reset (xing);
675 break;
676 default:
677 break;
678 }
679
680 return result;
681 }
682