2 * Copyright (C) 2003 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file mp3_afh.c para_server's mp3 audio format handler */
10 * This file is based in part on mp3tech.c and mp3tech.h, Copyright (C)
11 * 2000-2001 Cedric Tefft <cedric@earthling.net>, which in turn is based
14 * * MP3Info 0.5 by Ricardo Cerqueira <rmc@rccn.net>
15 * * MP3Stat 0.9 by Ed Sweetman <safemode@voicenet.com> and
16 * Johannes Overmann <overmann@iname.com>
28 * MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames we need
29 * to see before we decide we are looking at a real MP3 file
31 #define MIN_CONSEC_GOOD_FRAMES 4
32 #define FRAME_HEADER_SIZE 4
33 #define MIN_FRAME_SIZE 21
44 unsigned int copyright;
45 unsigned int original;
46 unsigned int emphasis;
49 static const int frequencies[3][4] = {
50 {22050,24000,16000,50000}, /* MPEG 2.0 */
51 {44100,48000,32000,50000}, /* MPEG 1.0 */
52 {11025,12000,8000,50000} /* MPEG 2.5 */
55 static const int mp3info_bitrate[2][3][14] = {
57 {32,48,56,64,80,96,112,128,144,160,176,192,224,256}, /* layer 1 */
58 {8,16,24,32,40,48,56,64,80,96,112,128,144,160}, /* layer 2 */
59 {8,16,24,32,40,48,56,64,80,96,112,128,144,160} /* layer 3 */
63 {32,64,96,128,160,192,224,256,288,320,352,384,416,448}, /* layer 1 */
64 {32,48,56,64,80,96,112,128,160,192,224,256,320,384}, /* layer 2 */
65 {32,40,48,56,64,80,96,112,128,160,192,224,256,320} /* layer 3 */
69 static const int frame_size_index[] = {24000, 72000, 72000};
70 static const char *mode_text[] = {"stereo", "joint stereo", "dual channel", "mono", "invalid"};
76 static char *get_utf8(id3_ucs4_t const *string)
80 return (char *)id3_ucs4_utf8duplicate(string);
83 static char *get_stringlist(union id3_field *field)
85 unsigned int k, nstrings = id3_field_getnstrings(field);
88 for (k = 0; k < nstrings; k++) {
89 char *tmp = (char *)get_utf8(id3_field_getstrings(field, k));
92 result = make_message("%s %s", tmp2, tmp);
101 static char *get_string(union id3_field *field)
103 id3_ucs4_t const *string = id3_field_getfullstring(field);
105 return get_utf8(string);
108 #define FOR_EACH_FIELD(f, j, fr) for (j = 0; j < (fr)->nfields && \
109 (f = id3_frame_field((fr), j)); j++)
111 static char *get_strings(struct id3_frame *fr)
114 union id3_field *field;
116 FOR_EACH_FIELD(field, j, fr) {
117 enum id3_field_type type = id3_field_type(field);
119 if (type == ID3_FIELD_TYPE_STRINGLIST)
120 return get_stringlist(field);
121 if (type == ID3_FIELD_TYPE_STRINGFULL)
122 return get_string(field);
127 /* this only sets values which are undefined so far */
128 static void parse_frames(struct id3_tag *id3_t, struct taginfo *tags)
132 for (i = 0; i < id3_t->nframes; i++) {
133 struct id3_frame *fr = id3_t->frames[i];
134 if (!strcmp(fr->id, ID3_FRAME_TITLE)) {
136 tags->title = get_strings(fr);
139 if (!strcmp(fr->id, ID3_FRAME_ARTIST)) {
141 tags->artist = get_strings(fr);
144 if (!strcmp(fr->id, ID3_FRAME_ALBUM)) {
146 tags->album = get_strings(fr);
149 if (!strcmp(fr->id, ID3_FRAME_YEAR)) {
151 tags->year = get_strings(fr);
154 if (!strcmp(fr->id, ID3_FRAME_COMMENT)) {
156 tags->comment = get_strings(fr);
162 static int mp3_get_id3(unsigned char *map, size_t numbytes, __a_unused int fd,
163 struct taginfo *tags)
166 struct id3_tag *id3_t;
168 /* id3v2 tags are usually located at the beginning. */
169 id3_t = id3_tag_parse(map, numbytes);
171 parse_frames(id3_t, tags);
173 id3_tag_delete(id3_t);
175 /* Also look for an id3v1 tag at the end of the file. */
176 if (numbytes >= 128) {
177 id3_t = id3_tag_parse(map + numbytes - 128, 128);
179 parse_frames(id3_t, tags);
181 id3_tag_delete(id3_t);
187 /* These helpers are not mentioned in the libid3tag header file. */
188 void id3_field_init(union id3_field *field, enum id3_field_type type);
189 void id3_field_finish(union id3_field *field);
192 * Frames of type ID3_FRAME_COMMENT contain three fields of type language,
193 * string, and fullstring. The third field contains the actual comment.
195 static int set_comment_fields(struct id3_frame *fr, id3_ucs4_t *ucs4_val)
198 union id3_field *field;
200 field = id3_frame_field(fr, 1);
201 id3_field_init(field, ID3_FIELD_TYPE_LANGUAGE);
203 field = id3_frame_field(fr, 2);
204 id3_field_init(field, ID3_FIELD_TYPE_STRING);
206 field = id3_frame_field(fr, 3);
207 id3_field_init(field, ID3_FIELD_TYPE_STRINGFULL);
208 ret = id3_field_setfullstring(field, ucs4_val);
210 return -E_ID3_SETSTRING;
215 * UCS-4 stands for Universal Character Set where each character uses exactly
216 * 32 bits. It is also known as UTF-32, see ISO 10646.
218 * We have to use UCS-4 as an intermediate representation because the functions
219 * of libid3tag which set the tag content expect an array of UCS-4 characters.
220 * Fortunately, libid3tag contains conversion functions from and to UTF-8.
222 static int replace_tag(char const *id, const char *val, struct id3_tag *id3_t,
226 struct id3_frame *fr;
227 union id3_field *field;
228 id3_ucs4_t *ucs4_val;
230 /* First, detach all frames that match the given id. */
231 while ((fr = id3_tag_findframe(id3_t, id, 0))) {
232 PARA_INFO_LOG("deleting %s frame\n", id);
233 ret = id3_tag_detachframe(id3_t, fr);
235 return -E_ID3_DETACH;
236 id3_frame_delete(fr);
240 fr = id3_frame_new(id);
241 PARA_DEBUG_LOG("frame desc: %s, %d fields\n", fr->description, fr->nfields);
243 /* Frame 0 contains the encoding. We always use UTF-8. */
244 field = id3_frame_field(fr, 0);
245 id3_field_init(field, ID3_FIELD_TYPE_TEXTENCODING);
246 ret = id3_field_settextencoding(field, ID3_FIELD_TEXTENCODING_UTF_8);
248 return -E_ID3_SETENCODING;
249 /* create UCS-4 representation */
250 ucs4_val = id3_utf8_ucs4duplicate((const id3_utf8_t *)val);
252 if (strcmp(id, ID3_FRAME_COMMENT) == 0)
253 ret = set_comment_fields(fr, ucs4_val);
255 /* Non-comment frames contain the value in field 1. */
256 field = id3_frame_field(fr, 1);
257 if (options & ID3_TAG_OPTION_ID3V1) {
258 id3_ucs4_t *ptr[] = {ucs4_val, NULL};
259 id3_field_init(field, ID3_FIELD_TYPE_STRINGLIST);
260 ret = id3_field_setstrings(field, 1, ptr);
262 id3_field_init(field, ID3_FIELD_TYPE_STRINGFULL);
263 ret = id3_field_setfullstring(field, ucs4_val);
268 return -E_ID3_SETSTRING;
270 PARA_INFO_LOG("attaching %s frame, value: %s\n", id, val);
271 ret = id3_tag_attachframe(id3_t, fr);
273 return -E_ID3_ATTACH;
277 static int replace_tags(struct id3_tag *id3_t, struct taginfo *tags)
279 int ret, options = id3_tag_options(id3_t, 0, 0);
281 ret = replace_tag(ID3_FRAME_ARTIST, tags->artist, id3_t, options);
284 ret = replace_tag(ID3_FRAME_TITLE, tags->title, id3_t, options);
287 ret = replace_tag(ID3_FRAME_ALBUM, tags->album, id3_t, options);
290 ret = replace_tag(ID3_FRAME_YEAR, tags->year, id3_t, options);
293 ret = replace_tag(ID3_FRAME_COMMENT, tags->comment, id3_t, options);
299 /* id3_tag_delete() does not seem to work due to refcount issues. */
300 static void free_tag(struct id3_tag *id3_t)
303 for (i = 0; i < id3_t->nframes; i++) {
304 struct id3_frame *fr = id3_t->frames[i];
305 for (j = 0; j < fr->nfields; j++) {
306 union id3_field *field = &fr->fields[j];
307 id3_field_finish(field);
315 static int mp3_rewrite_tags(const char *map, size_t mapsize,
316 struct taginfo *tags, int fd, __a_unused const char *filename)
319 id3_length_t old_v2size, new_v2size;
320 id3_byte_t v1_buffer[128], *v2_buffer;
322 struct id3_tag *v1_tag = NULL, *v2_tag = NULL;
324 if (mapsize >= 128) {
325 v1_tag = id3_tag_parse((const id3_byte_t *)map + mapsize - 128,
328 PARA_NOTICE_LOG("replacing id3v1 tag\n");
329 ret = replace_tags(v1_tag, tags);
332 id3_tag_render(v1_tag, v1_buffer);
336 v2_tag = id3_tag_parse((const id3_byte_t *)map, mapsize);
338 PARA_NOTICE_LOG("replacing id3v2 tag\n");
339 old_v2size = v2_tag->paddedsize;
340 } else if (!v1_tag) {
341 PARA_NOTICE_LOG("no id3 tags found, adding id3v2 tag\n");
342 v2_tag = id3_tag_new();
347 * Turn off all options to avoid creating an extended header.
348 * id321 does not understand it.
350 id3_tag_options(v2_tag, ~0U, 0);
351 ret = replace_tags(v2_tag, tags);
354 new_v2size = id3_tag_render(v2_tag, NULL);
355 v2_buffer = para_malloc(new_v2size);
356 id3_tag_render(v2_tag, v2_buffer);
357 PARA_INFO_LOG("writing v2 tag (%lu bytes)\n", new_v2size);
358 ret = write_all(fd, (char *)v2_buffer, new_v2size);
363 data_sz = mapsize - old_v2size;
364 if (v1_tag && data_sz >= 128)
366 PARA_INFO_LOG("writing data part (%zu bytes)\n", data_sz);
367 ret = write_all(fd, map + old_v2size, data_sz);
371 PARA_INFO_LOG("writing v1 tag\n");
372 ret = write_all(fd, (char *)v1_buffer, 128);
382 #else /* HAVE_ID3TAG */
385 * Remove trailing whitespace from the end of a string
387 static char *unpad(char *string)
389 char *pos = string + strlen(string) - 1;
390 while (para_isspace(pos[0]))
395 static int mp3_get_id3(unsigned char *map, size_t numbytes, __a_unused int fd,
396 struct taginfo *tags)
398 char title[31], artist[31], album[31], year[5], comment[31];
401 if (numbytes < 128 || strncmp("TAG", (char *)map + numbytes - 128, 3)) {
402 PARA_DEBUG_LOG("no id3 v1 tag\n");
405 fpos = numbytes - 125;
406 memcpy(title, map + fpos, 30);
409 memcpy(artist, map + fpos, 30);
412 memcpy(album, map + fpos, 30);
415 memcpy(year, map + fpos, 4);
418 memcpy(comment, map + fpos, 30);
425 tags->artist = para_strdup(artist);
426 tags->title = para_strdup(title);
427 tags->year = para_strdup(year);
428 tags->album = para_strdup(album);
429 tags->comment = para_strdup(comment);
432 #endif /* HAVE_ID3TAG */
434 static int header_frequency(struct mp3header *h)
436 if (h->version > 2 || h->freq > 3)
437 return -E_HEADER_FREQ;
438 return frequencies[h->version][h->freq];
441 static const char *header_mode(struct mp3header *h)
444 h->mode = 4; /* invalid */
445 return mode_text[h->mode];
448 static int header_channels(struct mp3header *h)
457 static int header_bitrate(struct mp3header *h)
459 if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
460 return -E_HEADER_BITRATE;
461 return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
464 static int frame_length(struct mp3header *header)
466 int hb, hf = header_frequency(header);
470 hb = header_bitrate(header);
473 if (header->sync != 0xFFE || header->layer > 3)
475 return frame_size_index[3 - header->layer] *
476 ((header->version & 1) + 1) * hb / hf
480 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
482 if ((*(unsigned int*)h1) == (*(unsigned int*)h2))
484 if ((h1->version == h2->version) &&
485 (h1->layer == h2->layer) &&
486 (h1->crc == h2->crc) &&
487 (h1->freq == h2->freq) &&
488 (h1->mode == h2->mode) &&
489 (h1->copyright == h2->copyright) &&
490 (h1->original == h2->original) &&
491 (h1->emphasis == h2->emphasis))
497 * get next MP3 frame header.
499 * On success, the header frame length is returned and the given header
500 * structure that is filled in. A return value of zero means that we did not
501 * retrieve a valid frame header, and a negative return value indicates an
504 static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
505 struct mp3header *header)
509 if (*fpos + FRAME_HEADER_SIZE > numbytes) {
510 *fpos = numbytes - 1;
514 header->layer = (map[*fpos + 1] >> 1) & 3;
515 header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
516 if (map[*fpos + 1] & 0x10)
517 header->version = (map[*fpos + 1] >> 3) & 1;
520 if ((header->sync != 0xFFE) || (header->layer != 1)) {
525 header->crc = map[*fpos + 1] & 1;
526 header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
527 header->freq = (map[*fpos + 2] >> 2) & 0x3;
528 header->padding = (map[*fpos + 2] >>1) & 0x1;
529 header->mode = (map[*fpos + 3] >> 6) & 0x3;
530 fl = frame_length(header);
531 ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
533 *fpos += FRAME_HEADER_SIZE;
538 * find the next mp3 header
540 * Return the length of the next frame header or zero if the end of the file is
543 static int mp3_seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
544 struct mp3header *result)
546 int k, l = 0, first_len;
547 struct mp3header h, h2;
548 long valid_start = 0;
550 for (; *fpos < numbytes; (*fpos)++) {
551 if (map[*fpos] != 0xff)
554 first_len = get_header(map, numbytes, fpos, &h);
557 *fpos += first_len - FRAME_HEADER_SIZE;
558 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
559 if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
561 if (!compare_headers(&h, &h2))
563 *fpos += l - FRAME_HEADER_SIZE;
565 if (k == MIN_CONSEC_GOOD_FRAMES) {
574 static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
575 struct mp3header *header)
579 frame_len = get_header(map, numbytes, fpos, header);
583 frame_len = mp3_seek_next_header(map, numbytes, fpos, header);
587 *fpos -= FRAME_HEADER_SIZE;
589 return -E_FRAME_LENGTH;
593 static int mp3_read_info(unsigned char *map, size_t numbytes, int fd,
594 struct afh_info *afhi)
596 uint64_t freq_sum = 0, br_sum = 0;
597 int fl = 0, ret, len = 0, old_br = -1, vbr = 0;
598 struct timeval total_time = {0, 0};
599 unsigned chunk_table_size = 1000; /* gets increased on demand */
601 struct mp3header header;
602 const char *tag_versions[] = {"no", "id3v1", "id3v2", "id3v1+id3v2"};
604 afhi->chunks_total = 0;
605 afhi->chunk_table = para_malloc(chunk_table_size * sizeof(uint32_t));
608 struct timeval tmp, cct; /* current chunk time */
610 len = find_valid_start(map, numbytes, &fpos, &header);
614 if (!afhi->chunks_total)
616 end = afhi->chunk_table[afhi->chunks_total - 1] + fl;
617 afhi->chunk_table[afhi->chunks_total]
618 = PARA_MIN(end, numbytes);
621 ret = header_frequency(&header);
625 ret = header_bitrate(&header);
629 ret = frame_length(&header);
633 tmp.tv_sec = fl - header.padding;
635 tv_divide(br * 125, &tmp, &cct);
636 tv_add(&cct, &total_time, &tmp);
638 if (afhi->chunks_total >= chunk_table_size) {
639 chunk_table_size *= 2;
640 afhi->chunk_table = para_realloc(afhi->chunk_table,
641 chunk_table_size * sizeof(uint32_t));
643 afhi->chunk_table[afhi->chunks_total] = fpos;
644 afhi->chunks_total++;
647 if (afhi->chunks_total != 1 && old_br != br)
652 if (!freq_sum || !br_sum)
654 afhi->bitrate = br_sum / afhi->chunks_total;
655 afhi->frequency = freq_sum / afhi->chunks_total;
656 afhi->channels = header_channels(&header);
657 afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
658 tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
659 PARA_DEBUG_LOG("%" PRIu32 "chunks, each %lums\n", afhi->chunks_total,
660 tv2ms(&afhi->chunk_tv));
661 ret = mp3_get_id3(map, numbytes, fd, &afhi->tags);
662 afhi->techinfo = make_message("%cbr, %s, %s tags", vbr? 'v' : 'c',
663 header_mode(&header), tag_versions[ret]);
666 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
667 free(afhi->chunk_table);
672 * Read mp3 information from audio file
674 static int mp3_get_file_info(char *map, size_t numbytes, int fd,
675 struct afh_info *afhi)
679 ret = mp3_read_info((unsigned char *)map, numbytes, fd, afhi);
682 if (afhi->seconds_total < 2 || !afhi->chunks_total)
687 static const char* mp3_suffixes[] = {"mp3", NULL};
690 * the init function of the mp3 audio format handler
692 * \param afh pointer to the struct to initialize
694 void mp3_init(struct audio_format_handler *afh)
696 afh->get_file_info = mp3_get_file_info;
697 afh->suffixes = mp3_suffixes;
698 #ifdef HAVE_LIBID3TAG
699 afh->rewrite_tags = mp3_rewrite_tags;
700 #endif /* HAVE_LIBID3TAG */