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