]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavformat/mp3.c
Use AV_RB* macros where appropriate.
[frescor/ffmpeg.git] / libavformat / mp3.c
1 /*
2  * MP3 muxer and demuxer
3  * Copyright (c) 2003 Fabrice Bellard.
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 #include "avformat.h"
22 #include "mpegaudio.h"
23 #include "avstring.h"
24
25 #define ID3v2_HEADER_SIZE 10
26 #define ID3v1_TAG_SIZE 128
27
28 #define ID3v1_GENRE_MAX 125
29
30 static const char *id3v1_genre_str[ID3v1_GENRE_MAX + 1] = {
31     [0] = "Blues",
32     [1] = "Classic Rock",
33     [2] = "Country",
34     [3] = "Dance",
35     [4] = "Disco",
36     [5] = "Funk",
37     [6] = "Grunge",
38     [7] = "Hip-Hop",
39     [8] = "Jazz",
40     [9] = "Metal",
41     [10] = "New Age",
42     [11] = "Oldies",
43     [12] = "Other",
44     [13] = "Pop",
45     [14] = "R&B",
46     [15] = "Rap",
47     [16] = "Reggae",
48     [17] = "Rock",
49     [18] = "Techno",
50     [19] = "Industrial",
51     [20] = "Alternative",
52     [21] = "Ska",
53     [22] = "Death Metal",
54     [23] = "Pranks",
55     [24] = "Soundtrack",
56     [25] = "Euro-Techno",
57     [26] = "Ambient",
58     [27] = "Trip-Hop",
59     [28] = "Vocal",
60     [29] = "Jazz+Funk",
61     [30] = "Fusion",
62     [31] = "Trance",
63     [32] = "Classical",
64     [33] = "Instrumental",
65     [34] = "Acid",
66     [35] = "House",
67     [36] = "Game",
68     [37] = "Sound Clip",
69     [38] = "Gospel",
70     [39] = "Noise",
71     [40] = "AlternRock",
72     [41] = "Bass",
73     [42] = "Soul",
74     [43] = "Punk",
75     [44] = "Space",
76     [45] = "Meditative",
77     [46] = "Instrumental Pop",
78     [47] = "Instrumental Rock",
79     [48] = "Ethnic",
80     [49] = "Gothic",
81     [50] = "Darkwave",
82     [51] = "Techno-Industrial",
83     [52] = "Electronic",
84     [53] = "Pop-Folk",
85     [54] = "Eurodance",
86     [55] = "Dream",
87     [56] = "Southern Rock",
88     [57] = "Comedy",
89     [58] = "Cult",
90     [59] = "Gangsta",
91     [60] = "Top 40",
92     [61] = "Christian Rap",
93     [62] = "Pop/Funk",
94     [63] = "Jungle",
95     [64] = "Native American",
96     [65] = "Cabaret",
97     [66] = "New Wave",
98     [67] = "Psychadelic",
99     [68] = "Rave",
100     [69] = "Showtunes",
101     [70] = "Trailer",
102     [71] = "Lo-Fi",
103     [72] = "Tribal",
104     [73] = "Acid Punk",
105     [74] = "Acid Jazz",
106     [75] = "Polka",
107     [76] = "Retro",
108     [77] = "Musical",
109     [78] = "Rock & Roll",
110     [79] = "Hard Rock",
111     [80] = "Folk",
112     [81] = "Folk-Rock",
113     [82] = "National Folk",
114     [83] = "Swing",
115     [84] = "Fast Fusion",
116     [85] = "Bebob",
117     [86] = "Latin",
118     [87] = "Revival",
119     [88] = "Celtic",
120     [89] = "Bluegrass",
121     [90] = "Avantgarde",
122     [91] = "Gothic Rock",
123     [92] = "Progressive Rock",
124     [93] = "Psychedelic Rock",
125     [94] = "Symphonic Rock",
126     [95] = "Slow Rock",
127     [96] = "Big Band",
128     [97] = "Chorus",
129     [98] = "Easy Listening",
130     [99] = "Acoustic",
131     [100] = "Humour",
132     [101] = "Speech",
133     [102] = "Chanson",
134     [103] = "Opera",
135     [104] = "Chamber Music",
136     [105] = "Sonata",
137     [106] = "Symphony",
138     [107] = "Booty Bass",
139     [108] = "Primus",
140     [109] = "Porn Groove",
141     [110] = "Satire",
142     [111] = "Slow Jam",
143     [112] = "Club",
144     [113] = "Tango",
145     [114] = "Samba",
146     [115] = "Folklore",
147     [116] = "Ballad",
148     [117] = "Power Ballad",
149     [118] = "Rhythmic Soul",
150     [119] = "Freestyle",
151     [120] = "Duet",
152     [121] = "Punk Rock",
153     [122] = "Drum Solo",
154     [123] = "A capella",
155     [124] = "Euro-House",
156     [125] = "Dance Hall",
157 };
158
159 /* buf must be ID3v2_HEADER_SIZE byte long */
160 static int id3v2_match(const uint8_t *buf)
161 {
162     return (buf[0] == 'I' &&
163             buf[1] == 'D' &&
164             buf[2] == '3' &&
165             buf[3] != 0xff &&
166             buf[4] != 0xff &&
167             (buf[6] & 0x80) == 0 &&
168             (buf[7] & 0x80) == 0 &&
169             (buf[8] & 0x80) == 0 &&
170             (buf[9] & 0x80) == 0);
171 }
172
173 static unsigned int id3v2_get_size(ByteIOContext *s, int len)
174 {
175     int v=0;
176     while(len--)
177         v= (v<<7) + (get_byte(s)&0x7F);
178     return v;
179 }
180
181 static void id3v2_read_ttag(AVFormatContext *s, int taglen, char *dst, int dstlen)
182 {
183     char *q;
184     int len;
185
186     if(taglen < 1)
187         return;
188
189     taglen--; /* account for encoding type byte */
190     dstlen--; /* Leave space for zero terminator */
191
192     switch(get_byte(&s->pb)) { /* encoding type */
193
194     case 0:  /* ISO-8859-1 (0 - 255 maps directly into unicode) */
195         q = dst;
196         while(taglen--) {
197             uint8_t tmp;
198             PUT_UTF8(get_byte(&s->pb), tmp, if (q - dst < dstlen - 1) *q++ = tmp;)
199         }
200         *q = '\0';
201         break;
202
203     case 3:  /* UTF-8 */
204         len = FFMIN(taglen, dstlen);
205         get_buffer(&s->pb, dst, len);
206         dst[len] = 0;
207         break;
208     }
209 }
210
211 /**
212  * ID3v2 parser
213  *
214  * Handles ID3v2.2, 2.3 and 2.4.
215  *
216  */
217
218 static void id3v2_parse(AVFormatContext *s, int len, uint8_t version, uint8_t flags)
219 {
220     int isv34, tlen;
221     uint32_t tag;
222     offset_t next;
223     char tmp[16];
224     int taghdrlen;
225     const char *reason;
226
227     switch(version) {
228     case 2:
229         if(flags & 0x40) {
230             reason = "compression";
231             goto error;
232         }
233         isv34 = 0;
234         taghdrlen = 6;
235         break;
236
237     case 3 ... 4:
238         isv34 = 1;
239         taghdrlen = 10;
240         break;
241
242     default:
243         reason = "version";
244         goto error;
245     }
246
247     if(flags & 0x80) {
248         reason = "unsynchronization";
249         goto error;
250     }
251
252     if(isv34 && flags & 0x40) /* Extended header present, just skip over it */
253         url_fskip(&s->pb, id3v2_get_size(&s->pb, 4));
254
255     while(len >= taghdrlen) {
256         if(isv34) {
257             tag  = get_be32(&s->pb);
258             tlen = id3v2_get_size(&s->pb, 4);
259             get_be16(&s->pb); /* flags */
260         } else {
261             tag  = get_be24(&s->pb);
262             tlen = id3v2_get_size(&s->pb, 3);
263         }
264         len -= taghdrlen + tlen;
265
266         if(len < 0)
267             break;
268
269         next = url_ftell(&s->pb) + tlen;
270
271         switch(tag) {
272         case MKBETAG('T', 'I', 'T', '2'):
273         case MKBETAG(0,   'T', 'T', '2'):
274             id3v2_read_ttag(s, tlen, s->title, sizeof(s->title));
275             break;
276         case MKBETAG('T', 'P', 'E', '1'):
277         case MKBETAG(0,   'T', 'P', '1'):
278             id3v2_read_ttag(s, tlen, s->author, sizeof(s->author));
279             break;
280         case MKBETAG('T', 'A', 'L', 'B'):
281         case MKBETAG(0,   'T', 'A', 'L'):
282             id3v2_read_ttag(s, tlen, s->album, sizeof(s->album));
283             break;
284         case MKBETAG('T', 'C', 'O', 'N'):
285         case MKBETAG(0,   'T', 'C', 'O'):
286             id3v2_read_ttag(s, tlen, s->genre, sizeof(s->genre));
287             break;
288         case MKBETAG('T', 'C', 'O', 'P'):
289         case MKBETAG(0,   'T', 'C', 'R'):
290             id3v2_read_ttag(s, tlen, s->copyright, sizeof(s->copyright));
291             break;
292         case MKBETAG('T', 'R', 'C', 'K'):
293         case MKBETAG(0,   'T', 'R', 'K'):
294             id3v2_read_ttag(s, tlen, tmp, sizeof(tmp));
295             s->track = atoi(tmp);
296             break;
297         case 0:
298             /* padding, skip to end */
299             url_fskip(&s->pb, len);
300             len = 0;
301             continue;
302         }
303         /* Skip to end of tag */
304         url_fseek(&s->pb, next, SEEK_SET);
305     }
306
307     if(version == 4 && flags & 0x10) /* Footer preset, always 10 bytes, skip over it */
308         url_fskip(&s->pb, 10);
309     return;
310
311   error:
312     av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n", version, reason);
313     url_fskip(&s->pb, len);
314 }
315
316 static void id3v1_get_string(char *str, int str_size,
317                              const uint8_t *buf, int buf_size)
318 {
319     int i, c;
320     char *q;
321
322     q = str;
323     for(i = 0; i < buf_size; i++) {
324         c = buf[i];
325         if (c == '\0')
326             break;
327         if ((q - str) >= str_size - 1)
328             break;
329         *q++ = c;
330     }
331     *q = '\0';
332 }
333
334 /* 'buf' must be ID3v1_TAG_SIZE byte long */
335 static int id3v1_parse_tag(AVFormatContext *s, const uint8_t *buf)
336 {
337     char str[5];
338     int genre;
339
340     if (!(buf[0] == 'T' &&
341           buf[1] == 'A' &&
342           buf[2] == 'G'))
343         return -1;
344     id3v1_get_string(s->title, sizeof(s->title), buf + 3, 30);
345     id3v1_get_string(s->author, sizeof(s->author), buf + 33, 30);
346     id3v1_get_string(s->album, sizeof(s->album), buf + 63, 30);
347     id3v1_get_string(str, sizeof(str), buf + 93, 4);
348     s->year = atoi(str);
349     id3v1_get_string(s->comment, sizeof(s->comment), buf + 97, 30);
350     if (buf[125] == 0 && buf[126] != 0)
351         s->track = buf[126];
352     genre = buf[127];
353     if (genre <= ID3v1_GENRE_MAX)
354         av_strlcpy(s->genre, id3v1_genre_str[genre], sizeof(s->genre));
355     return 0;
356 }
357
358 static void id3v1_create_tag(AVFormatContext *s, uint8_t *buf)
359 {
360     int v, i;
361
362     memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */
363     buf[0] = 'T';
364     buf[1] = 'A';
365     buf[2] = 'G';
366     strncpy(buf + 3, s->title, 30);
367     strncpy(buf + 33, s->author, 30);
368     strncpy(buf + 63, s->album, 30);
369     v = s->year;
370     if (v > 0) {
371         for(i = 0;i < 4; i++) {
372             buf[96 - i] = '0' + (v % 10);
373             v = v / 10;
374         }
375     }
376     strncpy(buf + 97, s->comment, 30);
377     if (s->track != 0) {
378         buf[125] = 0;
379         buf[126] = s->track;
380     }
381     for(i = 0; i <= ID3v1_GENRE_MAX; i++) {
382         if (!strcasecmp(s->genre, id3v1_genre_str[i])) {
383             buf[127] = i;
384             break;
385         }
386     }
387 }
388
389 /* mp3 read */
390
391 static int mp3_read_probe(AVProbeData *p)
392 {
393     int max_frames, first_frames;
394     int fsize, frames, sample_rate;
395     uint32_t header;
396     uint8_t *buf, *buf2, *end;
397     AVCodecContext avctx;
398
399     if(id3v2_match(p->buf))
400         return AVPROBE_SCORE_MAX/2+1; // this must be less than mpeg-ps because some retards put id3v2 tags before mpeg-ps files
401
402     max_frames = 0;
403     buf = p->buf;
404     end = buf + FFMIN(4096, p->buf_size - sizeof(uint32_t));
405
406     for(; buf < end; buf++) {
407         buf2 = buf;
408
409         for(frames = 0; buf2 < end; frames++) {
410             header = AV_RB32(buf2);
411             fsize = ff_mpa_decode_header(&avctx, header, &sample_rate);
412             if(fsize < 0)
413                 break;
414             buf2 += fsize;
415         }
416         max_frames = FFMAX(max_frames, frames);
417         if(buf == p->buf)
418             first_frames= frames;
419     }
420     if   (first_frames>=3) return AVPROBE_SCORE_MAX/2+1;
421     else if(max_frames>=3) return AVPROBE_SCORE_MAX/4;
422     else if(max_frames>=1) return 1;
423     else                   return 0;
424 }
425
426 static int mp3_read_header(AVFormatContext *s,
427                            AVFormatParameters *ap)
428 {
429     AVStream *st;
430     uint8_t buf[ID3v1_TAG_SIZE];
431     int len, ret, filesize;
432
433     st = av_new_stream(s, 0);
434     if (!st)
435         return AVERROR_NOMEM;
436
437     st->codec->codec_type = CODEC_TYPE_AUDIO;
438     st->codec->codec_id = CODEC_ID_MP3;
439     st->need_parsing = AVSTREAM_PARSE_FULL;
440
441     /* try to get the TAG */
442     if (!url_is_streamed(&s->pb)) {
443         /* XXX: change that */
444         filesize = url_fsize(&s->pb);
445         if (filesize > 128) {
446             url_fseek(&s->pb, filesize - 128, SEEK_SET);
447             ret = get_buffer(&s->pb, buf, ID3v1_TAG_SIZE);
448             if (ret == ID3v1_TAG_SIZE) {
449                 id3v1_parse_tag(s, buf);
450             }
451             url_fseek(&s->pb, 0, SEEK_SET);
452         }
453     }
454
455     /* if ID3v2 header found, skip it */
456     ret = get_buffer(&s->pb, buf, ID3v2_HEADER_SIZE);
457     if (ret != ID3v2_HEADER_SIZE)
458         return -1;
459     if (id3v2_match(buf)) {
460         /* parse ID3v2 header */
461         len = ((buf[6] & 0x7f) << 21) |
462             ((buf[7] & 0x7f) << 14) |
463             ((buf[8] & 0x7f) << 7) |
464             (buf[9] & 0x7f);
465         id3v2_parse(s, len, buf[3], buf[5]);
466     } else {
467         url_fseek(&s->pb, 0, SEEK_SET);
468     }
469
470     /* the parameters will be extracted from the compressed bitstream */
471     return 0;
472 }
473
474 #define MP3_PACKET_SIZE 1024
475
476 static int mp3_read_packet(AVFormatContext *s, AVPacket *pkt)
477 {
478     int ret, size;
479     //    AVStream *st = s->streams[0];
480
481     size= MP3_PACKET_SIZE;
482
483     ret= av_get_packet(&s->pb, pkt, size);
484
485     pkt->stream_index = 0;
486     if (ret <= 0) {
487         return AVERROR_IO;
488     }
489     /* note: we need to modify the packet size here to handle the last
490        packet */
491     pkt->size = ret;
492     return ret;
493 }
494
495 static int mp3_read_close(AVFormatContext *s)
496 {
497     return 0;
498 }
499
500 #ifdef CONFIG_MUXERS
501 /* simple formats */
502
503 static void id3v2_put_size(AVFormatContext *s, int size)
504 {
505     put_byte(&s->pb, size >> 21 & 0x7f);
506     put_byte(&s->pb, size >> 14 & 0x7f);
507     put_byte(&s->pb, size >> 7  & 0x7f);
508     put_byte(&s->pb, size       & 0x7f);
509 }
510
511 static void id3v2_put_ttag(AVFormatContext *s, char *string, uint32_t tag)
512 {
513     int len = strlen(string);
514     put_be32(&s->pb, tag);
515     id3v2_put_size(s, len + 1);
516     put_be16(&s->pb, 0);
517     put_byte(&s->pb, 3); /* UTF-8 */
518     put_buffer(&s->pb, string, len);
519 }
520
521
522 /**
523  * Write an ID3v2.4 header at beginning of stream
524  */
525
526 static int mp3_write_header(struct AVFormatContext *s)
527 {
528     int totlen = 0;
529     char tracktxt[10];
530
531     if(s->track)
532         snprintf(tracktxt, sizeof(tracktxt) - 1, "%d", s->track);
533
534     if(s->title[0])     totlen += 11 + strlen(s->title);
535     if(s->author[0])    totlen += 11 + strlen(s->author);
536     if(s->album[0])     totlen += 11 + strlen(s->album);
537     if(s->genre[0])     totlen += 11 + strlen(s->genre);
538     if(s->copyright[0]) totlen += 11 + strlen(s->copyright);
539     if(s->track)        totlen += 11 + strlen(tracktxt);
540     if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
541         totlen += strlen(LIBAVFORMAT_IDENT) + 11;
542
543     if(totlen == 0)
544         return 0;
545
546     put_be32(&s->pb, MKBETAG('I', 'D', '3', 0x04)); /* ID3v2.4 */
547     put_byte(&s->pb, 0);
548     put_byte(&s->pb, 0); /* flags */
549
550     id3v2_put_size(s, totlen);
551
552     if(s->title[0])     id3v2_put_ttag(s, s->title,     MKBETAG('T', 'I', 'T', '2'));
553     if(s->author[0])    id3v2_put_ttag(s, s->author,    MKBETAG('T', 'P', 'E', '1'));
554     if(s->album[0])     id3v2_put_ttag(s, s->album,     MKBETAG('T', 'A', 'L', 'B'));
555     if(s->genre[0])     id3v2_put_ttag(s, s->genre,     MKBETAG('T', 'C', 'O', 'N'));
556     if(s->copyright[0]) id3v2_put_ttag(s, s->copyright, MKBETAG('T', 'C', 'O', 'P'));
557     if(s->track)        id3v2_put_ttag(s, tracktxt,     MKBETAG('T', 'R', 'C', 'K'));
558     if(!(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT))
559         id3v2_put_ttag(s, LIBAVFORMAT_IDENT,            MKBETAG('T', 'E', 'N', 'C'));
560     return 0;
561 }
562
563 static int mp3_write_packet(struct AVFormatContext *s, AVPacket *pkt)
564 {
565     put_buffer(&s->pb, pkt->data, pkt->size);
566     put_flush_packet(&s->pb);
567     return 0;
568 }
569
570 static int mp3_write_trailer(struct AVFormatContext *s)
571 {
572     uint8_t buf[ID3v1_TAG_SIZE];
573
574     /* write the id3v1 tag */
575     if (s->title[0] != '\0') {
576         id3v1_create_tag(s, buf);
577         put_buffer(&s->pb, buf, ID3v1_TAG_SIZE);
578         put_flush_packet(&s->pb);
579     }
580     return 0;
581 }
582 #endif //CONFIG_MUXERS
583
584 #ifdef CONFIG_MP3_DEMUXER
585 AVInputFormat mp3_demuxer = {
586     "mp3",
587     "MPEG audio",
588     0,
589     mp3_read_probe,
590     mp3_read_header,
591     mp3_read_packet,
592     mp3_read_close,
593     .flags= AVFMT_GENERIC_INDEX,
594     .extensions = "mp2,mp3,m2a", /* XXX: use probe */
595 };
596 #endif
597 #ifdef CONFIG_MP2_MUXER
598 AVOutputFormat mp2_muxer = {
599     "mp2",
600     "MPEG audio layer 2",
601     "audio/x-mpeg",
602 #ifdef CONFIG_LIBMP3LAME
603     "mp2,m2a",
604 #else
605     "mp2,mp3,m2a",
606 #endif
607     0,
608     CODEC_ID_MP2,
609     0,
610     mp3_write_header,
611     mp3_write_packet,
612     mp3_write_trailer,
613 };
614 #endif
615 #ifdef CONFIG_MP3_MUXER
616 AVOutputFormat mp3_muxer = {
617     "mp3",
618     "MPEG audio layer 3",
619     "audio/x-mpeg",
620     "mp3",
621     0,
622     CODEC_ID_MP3,
623     0,
624     mp3_write_header,
625     mp3_write_packet,
626     mp3_write_trailer,
627 };
628 #endif