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