ebb6bf5291281d2fa9343fea21544617c79bfcdc
[paraslash.git] / mp3_afh.c
1 /*
2 * Copyright (C) 2003-2008 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file mp3_afh.c para_server's mp3 audio format handler */
8
9 /*
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
12 * in part on
13 *
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>
17 */
18
19 #include "para.h"
20 #include "error.h"
21 #include "afh.h"
22 #include "string.h"
23 #include "afs.h"
24 #include "server.h"
25
26 /** \cond some defines and structs which are only used in this file */
27
28 /*
29 * MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames we need
30 * to see before we decide we are looking at a real MP3 file
31 */
32 #define MIN_CONSEC_GOOD_FRAMES 4
33 #define FRAME_HEADER_SIZE 4
34 #define MIN_FRAME_SIZE 21
35
36 struct mp3header {
37 unsigned long sync;
38 unsigned int version;
39 unsigned int layer;
40 unsigned int crc;
41 unsigned int bitrate;
42 unsigned int freq;
43 unsigned int padding;
44 unsigned int mode;
45 unsigned int copyright;
46 unsigned int original;
47 unsigned int emphasis;
48 };
49
50 /** \endcond */
51 static const int frequencies[3][4] = {
52 {22050,24000,16000,50000}, /* MPEG 2.0 */
53 {44100,48000,32000,50000}, /* MPEG 1.0 */
54 {11025,12000,8000,50000} /* MPEG 2.5 */
55 };
56
57 static const int mp3info_bitrate[2][3][14] = {
58 { /* MPEG 2.0 */
59 {32,48,56,64,80,96,112,128,144,160,176,192,224,256}, /* layer 1 */
60 {8,16,24,32,40,48,56,64,80,96,112,128,144,160}, /* layer 2 */
61 {8,16,24,32,40,48,56,64,80,96,112,128,144,160} /* layer 3 */
62 },
63
64 { /* MPEG 1.0 */
65 {32,64,96,128,160,192,224,256,288,320,352,384,416,448}, /* layer 1 */
66 {32,48,56,64,80,96,112,128,160,192,224,256,320,384}, /* layer 2 */
67 {32,40,48,56,64,80,96,112,128,160,192,224,256,320} /* layer 3 */
68 }
69 };
70
71 static const int frame_size_index[] = {24000, 72000, 72000};
72 static const char *mode_text[] = {"stereo", "joint stereo", "dual channel", "mono", "invalid"};
73
74 static char *make_taginfo(char *title, char *artist, char *album, char *year,
75 char *comment)
76 {
77 return make_message("%s: %s, by %s\n" /* taginfo1 */
78 "%s: A: %s, Y: %s, C: %s\n", /* taginfo 2*/
79 status_item_list[SI_TAGINFO1],
80 (title && *title)? title : "(title tag not set)",
81 (artist && *artist)? artist : "(artist tag not set)",
82 status_item_list[SI_TAGINFO2],
83 (album && *album)? album : "(album tag not set)",
84 (year && *year)? year : "????",
85 (comment && *comment)? comment : "(comment tag not set)"
86 );
87 }
88
89 #ifdef HAVE_LIBID3TAG
90
91 #include <id3tag.h>
92
93 static char *get_latin1(id3_ucs4_t const *string)
94 {
95 if (!string)
96 return NULL;
97 return (char *)id3_ucs4_latin1duplicate(string);
98 }
99
100 char *get_stringlist(union id3_field *field)
101 {
102 unsigned int k, nstrings = id3_field_getnstrings(field);
103 char *result = NULL;
104
105 for (k = 0; k < nstrings; k++) {
106 char *tmp = (char *)get_latin1(id3_field_getstrings(field, k));
107 if (result) {
108 char *tmp2 = result;
109 result = make_message("%s %s", tmp2, tmp);
110 free(tmp);
111 free(tmp2);
112 } else
113 result = tmp;
114 }
115 return result;
116 }
117
118 static char *get_string(union id3_field *field)
119 {
120 id3_ucs4_t const *string = id3_field_getfullstring(field);
121
122 return get_latin1(string);
123 }
124
125 #define FOR_EACH_FIELD(f, j, fr) for (j = 0; j < (fr)->nfields && \
126 (f = id3_frame_field((fr), j)); j++)
127
128 static char *get_strings(struct id3_frame *fr)
129 {
130 int j;
131 union id3_field *field;
132
133 FOR_EACH_FIELD(field, j, fr) {
134 enum id3_field_type type = id3_field_type(field);
135
136 if (type == ID3_FIELD_TYPE_STRINGLIST)
137 return get_stringlist(field);
138 if (type == ID3_FIELD_TYPE_STRINGFULL)
139 return get_string(field);
140 }
141 return NULL;
142 }
143
144 static char *mp3_get_id3(__a_unused unsigned char *map,
145 __a_unused size_t numbytes, int fd)
146 {
147 int i;
148 struct id3_tag *id3_t;
149 char *title = NULL, *artist = NULL, *album = NULL, *year = NULL,
150 *comment = NULL, *result;
151 struct id3_file *id3_f = id3_file_fdopen(fd, ID3_FILE_MODE_READONLY);
152
153 if (!id3_f)
154 goto no_tag;
155 id3_t = id3_file_tag(id3_f);
156 if (!id3_t)
157 goto no_tag;
158 for (i = 0; i < id3_t->nframes; i++) {
159 struct id3_frame *fr = id3_t->frames[i];
160 if (!strcmp(fr->id, "TIT2")) {
161 if (!title)
162 title = get_strings(fr);
163 continue;
164 }
165 if (!strcmp(fr->id, "TPE1")) {
166 if (!artist)
167 artist = get_strings(fr);
168 continue;
169 }
170 if (!strcmp(fr->id, "TALB")) {
171 if (!album)
172 album = get_strings(fr);
173 continue;
174 }
175 if (!strcmp(fr->id, "TDRC")) {
176 if (!year)
177 year = get_strings(fr);
178 continue;
179 }
180 if (!strcmp(fr->id, "COMM")) {
181 if (!comment)
182 comment = get_strings(fr);
183 continue;
184 }
185 }
186 id3_file_close(id3_f);
187 result = make_taginfo(title, artist, album, year, comment);
188 free(title);
189 free(artist);
190 free(album);
191 free(year);
192 free(comment);
193 return result;
194 no_tag:
195 if (id3_f)
196 id3_file_close(id3_f);
197 return make_message("%s: (no id3 v1/v2 tag)\n%s:\n",
198 status_item_list[SI_TAGINFO1],
199 status_item_list[SI_TAGINFO2]);
200 }
201
202 #else /* HAVE_LIBID3TAG */
203
204 /*
205 * Remove trailing whitespace from the end of a string
206 */
207 static char *unpad(char *string)
208 {
209 char *pos = string + strlen(string) - 1;
210 while (para_isspace(pos[0]))
211 (pos--)[0] = 0;
212 return string;
213 }
214
215 static char *mp3_get_id3(unsigned char *map, size_t numbytes, __a_unused int fd)
216 {
217 char title[31], artist[31], album[31], year[5], comment[31];
218 off_t fpos;
219
220 if (numbytes < 128 || strncmp("TAG", (char *)map + numbytes - 128, 3)) {
221 PARA_DEBUG_LOG("no id3 v1 tag\n");
222 return make_message("%s: (no id3 v1 tag)\n%s:\n",
223 status_item_list[SI_TAGINFO1],
224 status_item_list[SI_TAGINFO2]);
225 }
226 fpos = numbytes - 125;
227 memcpy(title, map + fpos, 30);
228 fpos += 30;
229 title[30] = '\0';
230 memcpy(artist, map + fpos, 30);
231 fpos += 30;
232 artist[30] = '\0';
233 memcpy(album, map + fpos, 30);
234 fpos += 30;
235 album[30] = '\0';
236 memcpy(year, map + fpos, 4);
237 fpos += 4;
238 year[4] = '\0';
239 memcpy(comment, map + fpos, 30);
240 comment[30] = '\0';
241 unpad(title);
242 unpad(artist);
243 unpad(album);
244 unpad(year);
245 unpad(comment);
246 return make_taginfo(title, artist, album, year, comment);
247 }
248 #endif /* HAVE_LIBID3TAG */
249
250 static int header_frequency(struct mp3header *h)
251 {
252 if (h->version > 2 || h->freq > 3)
253 return -E_HEADER_FREQ;
254 return frequencies[h->version][h->freq];
255 }
256
257 static const char *header_mode(struct mp3header *h)
258 {
259 if (h->mode > 4)
260 h->mode = 4; /* invalid */
261 return mode_text[h->mode];
262 }
263
264 static int header_channels(struct mp3header *h)
265 {
266 if (h->mode > 3)
267 return 0;
268 if (h->mode < 3)
269 return 2;
270 return 1;
271 }
272
273 static int header_bitrate(struct mp3header *h)
274 {
275 if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
276 return -E_HEADER_BITRATE;
277 return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
278 }
279
280 static int frame_length(struct mp3header *header)
281 {
282 int hb, hf = header_frequency(header);
283
284 if (hf < 0)
285 return hf;
286 hb = header_bitrate(header);
287 if (hb < 0)
288 return hb;
289 if (header->sync != 0xFFE || header->layer > 3)
290 return -E_FRAME;
291 return frame_size_index[3 - header->layer] *
292 ((header->version & 1) + 1) * hb / hf
293 + header->padding;
294 }
295
296 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
297 {
298 if ((*(uint*)h1) == (*(uint*)h2))
299 return 1;
300 if ((h1->version == h2->version) &&
301 (h1->layer == h2->layer) &&
302 (h1->crc == h2->crc) &&
303 (h1->freq == h2->freq) &&
304 (h1->mode == h2->mode) &&
305 (h1->copyright == h2->copyright) &&
306 (h1->original == h2->original) &&
307 (h1->emphasis == h2->emphasis))
308 return 1;
309 return 0;
310 }
311
312 /*
313 * get next MP3 frame header.
314 *
315 * On success, the header frame length is returned and the given header
316 * structure that is filled in. A return value of zero means that we did not
317 * retrieve a valid frame header, and a negative return value indicates an
318 * error.
319 */
320 static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
321 struct mp3header *header)
322 {
323 int fl, ret;
324
325 if (*fpos + FRAME_HEADER_SIZE > numbytes) {
326 *fpos = numbytes - 1;
327 header->sync = 0;
328 return 0;
329 }
330 header->layer = (map[*fpos + 1] >> 1) & 3;
331 header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
332 if (map[*fpos + 1] & 0x10)
333 header->version = (map[*fpos + 1] >> 3) & 1;
334 else
335 header->version = 2;
336 if ((header->sync != 0xFFE) || (header->layer != 1)) {
337 ret = 0;
338 header->sync = 0;
339 goto out;
340 }
341 header->crc = map[*fpos + 1] & 1;
342 header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
343 header->freq = (map[*fpos + 2] >> 2) & 0x3;
344 header->padding = (map[*fpos + 2] >>1) & 0x1;
345 header->mode = (map[*fpos + 3] >> 6) & 0x3;
346 fl = frame_length(header);
347 ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
348 out:
349 *fpos += FRAME_HEADER_SIZE;
350 return ret;
351 }
352
353 /*
354 * find the next mp3 header
355 *
356 * Return the length of the next frame header or zero if the end of the file is
357 * reached.
358 */
359 static int mp3_seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
360 struct mp3header *result)
361 {
362 int k, l = 0, first_len;
363 struct mp3header h, h2;
364 long valid_start = 0;
365
366 for (; *fpos < numbytes; (*fpos)++) {
367 if (map[*fpos] != 0xff)
368 continue;
369 valid_start = *fpos;
370 first_len = get_header(map, numbytes, fpos, &h);
371 if (first_len <= 0)
372 continue;
373 *fpos += first_len - FRAME_HEADER_SIZE;
374 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
375 if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
376 break;
377 if (!compare_headers(&h, &h2))
378 break;
379 *fpos += l - FRAME_HEADER_SIZE;
380 }
381 if (k == MIN_CONSEC_GOOD_FRAMES) {
382 *fpos = valid_start;
383 *result = h2;
384 return first_len;
385 }
386 }
387 return 0;
388 }
389
390 static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
391 struct mp3header *header)
392 {
393 int frame_len;
394
395 frame_len = get_header(map, numbytes, fpos, header);
396 if (frame_len < 0)
397 return frame_len;
398 if (!frame_len) {
399 frame_len = mp3_seek_next_header(map, numbytes, fpos, header);
400 if (frame_len <= 0)
401 return frame_len;
402 } else
403 *fpos -= FRAME_HEADER_SIZE;
404 if (frame_len <= 1)
405 return -E_FRAME_LENGTH;
406 return frame_len;
407 }
408
409 static int mp3_read_info(unsigned char *map, size_t numbytes, int fd,
410 struct afh_info *afhi)
411 {
412 long freq_avg = 0, br_avg = 0;
413 int ret, len = 0, old_br = -1, vbr = 0;
414 struct timeval total_time = {0, 0};
415 unsigned chunk_table_size = 1000; /* gets increased on demand */
416 off_t fpos = 0;
417 struct mp3header header;
418 char *taginfo;
419
420 afhi->chunks_total = 0;
421 afhi->chunk_table = para_malloc(chunk_table_size * sizeof(size_t));
422 taginfo = mp3_get_id3(map, numbytes, fd);
423 while (1) {
424 unsigned long freq, br, fl;
425 struct timeval tmp, cct; /* current chunk time */
426 fpos += len;
427 len = find_valid_start(map, numbytes, &fpos, &header);
428 if (len <= 0)
429 break;
430 ret = header_frequency(&header);
431 if (ret < 0)
432 continue;
433 freq = ret;
434 ret = header_bitrate(&header);
435 if (ret < 0)
436 continue;
437 br = ret;
438 ret = frame_length(&header);
439 if (ret < 0)
440 continue;
441 fl = ret;
442 tmp.tv_sec = fl;
443 tmp.tv_usec = 0;
444 tv_divide(br * 125, &tmp, &cct);
445 tv_add(&cct, &total_time, &tmp);
446 total_time = tmp;
447 //PARA_DEBUG_LOG("%s: br: %d, freq: %d, fl: %d, cct: %lu\n", __func__, br, freq, fl, cct.tv_usec);
448 if (afhi->chunks_total >= chunk_table_size) {
449 chunk_table_size *= 2;
450 afhi->chunk_table = para_realloc(afhi->chunk_table,
451 chunk_table_size * sizeof(size_t));
452 }
453 afhi->chunk_table[afhi->chunks_total] = fpos;
454 // if (afhi->chunks_total < 10 || !(afhi->chunks_total % 1000))
455 // PARA_INFO_LOG("chunk #%lu: %zd\n", afhi->chunks_total,
456 // afhi->chunk_table[afhi->chunks_total]);
457 afhi->chunks_total++;
458 if (afhi->chunks_total == 1) {
459 freq_avg = freq;
460 br_avg = br;
461 old_br = br;
462 continue;
463 }
464 freq_avg += ((long)freq - freq_avg) / ((long)afhi->chunks_total + 1);
465 br_avg += ((long)br - br_avg) / ((long)afhi->chunks_total + 1);
466 if (old_br != br)
467 vbr = 1;
468 old_br = br;
469 }
470 ret = -E_MP3_INFO;
471 if (!afhi->chunks_total || !freq_avg || !br_avg)
472 goto err_out;
473 afhi->chunk_table[afhi->chunks_total] = numbytes - 1;
474 afhi->bitrate = br_avg;
475 afhi->frequency = freq_avg;
476 afhi->channels = header_channels(&header);
477 afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
478 tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
479 PARA_DEBUG_LOG("%lu chunks, each %lums\n", afhi->chunks_total,
480 tv2ms(&afhi->chunk_tv));
481 tv_scale(3, &afhi->chunk_tv, &afhi->eof_tv);
482 PARA_DEBUG_LOG("eof timeout: %lu\n", tv2ms(&afhi->eof_tv));
483 afhi->info_string = make_message("%s: %cbr, %s\n%s",
484 status_item_list[SI_AUDIO_FILE_INFO], vbr? 'v' : 'c',
485 header_mode(&header), taginfo);
486 free(taginfo);
487 return 1;
488 err_out:
489 free(taginfo);
490 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
491 free(afhi->chunk_table);
492 return ret;
493 }
494
495 /*
496 * Read mp3 information from audio file
497 */
498 static int mp3_get_file_info(char *map, size_t numbytes, int fd,
499 struct afh_info *afhi)
500 {
501 int ret;
502
503 ret = mp3_read_info((unsigned char *)map, numbytes, fd, afhi);
504 if (ret < 0)
505 return ret;
506 if (afhi->seconds_total < 2 || !afhi->chunks_total)
507 return -E_MP3_INFO;
508 return 1;
509 }
510
511 static const char* mp3_suffixes[] = {"mp3", NULL};
512
513 /**
514 * the init function of the mp3 audio format handler
515 *
516 * \param afh pointer to the struct to initialize
517 */
518 void mp3_init(struct audio_format_handler *afh)
519 {
520 afh->get_file_info = mp3_get_file_info;
521 afh->suffixes = mp3_suffixes;
522 }