afh: Fix fd leak.
[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_LIBID3TAG
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 static void mp3_get_id3(__a_unused unsigned char *map,
127                 __a_unused size_t numbytes, int fd, struct taginfo *tags)
128 {
129         int i, new_fd;
130         struct id3_tag *id3_t;
131         struct id3_file *id3_f;
132
133         /*
134          * We are not supposed to close fd, but to avoid memory leaks we must
135          * call id3_file_close() on the id3_file after we are done. As
136          * id3_file_close() closes fd, we first create a copy for libid3tag.
137          */
138         new_fd = dup(fd);
139         if (new_fd < 0)
140                 return;
141         id3_f = id3_file_fdopen(new_fd, ID3_FILE_MODE_READONLY);
142
143         if (!id3_f)
144                 return;
145         id3_t = id3_file_tag(id3_f);
146         if (!id3_t) {
147                 id3_file_close(id3_f);
148                 return;
149         }
150         for (i = 0; i < id3_t->nframes; i++) {
151                 struct id3_frame *fr = id3_t->frames[i];
152                 if (!strcmp(fr->id, ID3_FRAME_TITLE)) {
153                         if (!tags->title)
154                                 tags->title = get_strings(fr);
155                         continue;
156                 }
157                 if (!strcmp(fr->id, ID3_FRAME_ARTIST)) {
158                         if (!tags->artist)
159                                 tags->artist = get_strings(fr);
160                         continue;
161                 }
162                 if (!strcmp(fr->id, ID3_FRAME_ALBUM)) {
163                         if (!tags->album)
164                                 tags->album = get_strings(fr);
165                         continue;
166                 }
167                 if (!strcmp(fr->id, ID3_FRAME_YEAR)) {
168                         if (!tags->year)
169                                 tags->year = get_strings(fr);
170                         continue;
171                 }
172                 if (!strcmp(fr->id, ID3_FRAME_COMMENT)) {
173                         if (!tags->comment)
174                                 tags->comment = get_strings(fr);
175                         continue;
176                 }
177         }
178         id3_file_close(id3_f);
179 }
180
181 #else /* HAVE_LIBID3TAG */
182
183 /*
184  * Remove trailing whitespace from the end of a string
185  */
186 static char *unpad(char *string)
187 {
188         char *pos = string + strlen(string) - 1;
189         while (para_isspace(pos[0]))
190                 (pos--)[0] = 0;
191         return string;
192 }
193
194 static void mp3_get_id3(unsigned char *map, size_t numbytes, __a_unused int fd,
195         struct taginfo *tags)
196 {
197         char title[31], artist[31], album[31], year[5], comment[31];
198         off_t fpos;
199
200         if (numbytes < 128 || strncmp("TAG", (char *)map + numbytes - 128, 3)) {
201                 PARA_DEBUG_LOG("no id3 v1 tag\n");
202                 return;
203         }
204         fpos = numbytes - 125;
205         memcpy(title, map + fpos, 30);
206         fpos += 30;
207         title[30] = '\0';
208         memcpy(artist, map + fpos, 30);
209         fpos += 30;
210         artist[30] = '\0';
211         memcpy(album, map + fpos, 30);
212         fpos += 30;
213         album[30] = '\0';
214         memcpy(year, map + fpos, 4);
215         fpos += 4;
216         year[4] = '\0';
217         memcpy(comment, map + fpos, 30);
218         comment[30] = '\0';
219         unpad(title);
220         unpad(artist);
221         unpad(album);
222         unpad(year);
223         unpad(comment);
224         tags->artist = para_strdup(artist);
225         tags->title = para_strdup(title);
226         tags->year = para_strdup(year);
227         tags->album = para_strdup(album);
228         tags->comment = para_strdup(comment);
229 }
230 #endif /* HAVE_LIBID3TAG */
231
232 static int header_frequency(struct mp3header *h)
233 {
234         if (h->version > 2 || h->freq > 3)
235                 return -E_HEADER_FREQ;
236         return frequencies[h->version][h->freq];
237 }
238
239 static const char *header_mode(struct mp3header *h)
240 {
241         if (h->mode > 4)
242                 h->mode = 4; /* invalid */
243         return mode_text[h->mode];
244 }
245
246 static int header_channels(struct mp3header *h)
247 {
248         if (h->mode > 3)
249                 return 0;
250         if (h->mode < 3)
251                 return 2;
252         return 1;
253 }
254
255 static int header_bitrate(struct mp3header *h)
256 {
257         if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
258                 return -E_HEADER_BITRATE;
259         return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
260 }
261
262 static int frame_length(struct mp3header *header)
263 {
264         int hb, hf = header_frequency(header);
265
266         if (hf < 0)
267                 return hf;
268         hb = header_bitrate(header);
269         if (hb < 0)
270                 return hb;
271         if (header->sync != 0xFFE || header->layer > 3)
272                 return -E_FRAME;
273         return frame_size_index[3 - header->layer] *
274                 ((header->version & 1) + 1) * hb / hf
275                 + header->padding;
276 }
277
278 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
279 {
280         if ((*(unsigned int*)h1) == (*(unsigned int*)h2))
281                 return 1;
282         if ((h1->version == h2->version) &&
283                         (h1->layer == h2->layer) &&
284                         (h1->crc == h2->crc) &&
285                         (h1->freq == h2->freq) &&
286                         (h1->mode == h2->mode) &&
287                         (h1->copyright == h2->copyright) &&
288                         (h1->original == h2->original) &&
289                         (h1->emphasis == h2->emphasis))
290                 return 1;
291         return 0;
292 }
293
294 /*
295  * get next MP3 frame header.
296  *
297  * On success, the header frame length is returned and the given header
298  * structure that is filled in.  A return value of zero means that we did not
299  * retrieve a valid frame header, and a negative return value indicates an
300  * error.
301  */
302 static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
303         struct mp3header *header)
304 {
305         int fl, ret;
306
307         if (*fpos + FRAME_HEADER_SIZE > numbytes) {
308                 *fpos = numbytes - 1;
309                 header->sync = 0;
310                 return 0;
311         }
312         header->layer = (map[*fpos + 1] >> 1) & 3;
313         header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
314         if (map[*fpos + 1] & 0x10)
315                 header->version = (map[*fpos + 1] >> 3) & 1;
316         else
317                 header->version = 2;
318         if ((header->sync != 0xFFE) || (header->layer != 1)) {
319                 ret = 0;
320                 header->sync = 0;
321                 goto out;
322         }
323         header->crc = map[*fpos + 1] & 1;
324         header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
325         header->freq = (map[*fpos + 2] >> 2) & 0x3;
326         header->padding = (map[*fpos + 2] >>1) & 0x1;
327         header->mode = (map[*fpos + 3] >> 6) & 0x3;
328         fl = frame_length(header);
329         ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
330 out:
331         *fpos += FRAME_HEADER_SIZE;
332         return ret;
333 }
334
335 /*
336  * find the next mp3 header
337  *
338  * Return the length of the next frame header or zero if the end of the file is
339  * reached.
340  */
341 static int mp3_seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
342         struct mp3header *result)
343 {
344         int k, l = 0, first_len;
345         struct mp3header h, h2;
346         long valid_start = 0;
347
348         for (; *fpos < numbytes; (*fpos)++) {
349                 if (map[*fpos] != 0xff)
350                         continue;
351                 valid_start = *fpos;
352                 first_len = get_header(map, numbytes, fpos, &h);
353                 if (first_len <= 0)
354                         continue;
355                 *fpos += first_len - FRAME_HEADER_SIZE;
356                 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
357                         if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
358                                 break;
359                         if (!compare_headers(&h, &h2))
360                                 break;
361                         *fpos += l - FRAME_HEADER_SIZE;
362                 }
363                 if (k == MIN_CONSEC_GOOD_FRAMES) {
364                         *fpos = valid_start;
365                         *result = h2;
366                         return first_len;
367                 }
368         }
369         return 0;
370 }
371
372 static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
373         struct mp3header *header)
374 {
375         int frame_len;
376
377         frame_len = get_header(map, numbytes, fpos, header);
378         if (frame_len < 0)
379                 return frame_len;
380         if (!frame_len) {
381                 frame_len = mp3_seek_next_header(map, numbytes, fpos, header);
382                 if (frame_len <= 0)
383                         return frame_len;
384         } else
385                 *fpos -= FRAME_HEADER_SIZE;
386         if (frame_len <= 1)
387                 return -E_FRAME_LENGTH;
388         return frame_len;
389 }
390
391 static int mp3_read_info(unsigned char *map, size_t numbytes, int fd,
392                 struct afh_info *afhi)
393 {
394         uint64_t freq_sum = 0, br_sum = 0;
395         int fl = 0, ret, len = 0, old_br = -1, vbr = 0;
396         struct timeval total_time = {0, 0};
397         unsigned chunk_table_size = 1000; /* gets increased on demand */
398         off_t fpos = 0;
399         struct mp3header header;
400
401         afhi->chunks_total = 0;
402         afhi->chunk_table = para_malloc(chunk_table_size * sizeof(uint32_t));
403         while (1) {
404                 int freq, br;
405                 struct timeval tmp, cct; /* current chunk time */
406                 fpos += len;
407                 len = find_valid_start(map, numbytes, &fpos, &header);
408                 if (len <= 0) {
409                         size_t end;
410                         ret = -E_MP3_INFO;
411                         if (!afhi->chunks_total)
412                                 goto err_out;
413                         end = afhi->chunk_table[afhi->chunks_total - 1] + fl;
414                         afhi->chunk_table[afhi->chunks_total]
415                                 = PARA_MIN(end, numbytes);
416                         break;
417                 }
418                 ret = header_frequency(&header);
419                 if (ret < 0)
420                         continue;
421                 freq = ret;
422                 ret = header_bitrate(&header);
423                 if (ret < 0)
424                         continue;
425                 br = ret;
426                 ret = frame_length(&header);
427                 if (ret < 0)
428                         continue;
429                 fl = ret;
430                 tmp.tv_sec = fl - header.padding;
431                 tmp.tv_usec = 0;
432                 tv_divide(br * 125, &tmp, &cct);
433                 tv_add(&cct, &total_time, &tmp);
434                 total_time = tmp;
435                 if (afhi->chunks_total >= chunk_table_size) {
436                         chunk_table_size *= 2;
437                         afhi->chunk_table = para_realloc(afhi->chunk_table,
438                                 chunk_table_size * sizeof(uint32_t));
439                 }
440                 afhi->chunk_table[afhi->chunks_total] = fpos;
441                 afhi->chunks_total++;
442                 freq_sum += freq;
443                 br_sum += br;
444                 if (afhi->chunks_total != 1 && old_br != br)
445                         vbr = 1;
446                 old_br = br;
447         }
448         ret = -E_MP3_INFO;
449         if (!freq_sum || !br_sum)
450                 goto err_out;
451         afhi->bitrate = br_sum / afhi->chunks_total;
452         afhi->frequency = freq_sum / afhi->chunks_total;
453         afhi->channels = header_channels(&header);
454         afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
455         tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
456         PARA_DEBUG_LOG("%lu chunks, each %lums\n", afhi->chunks_total,
457                 tv2ms(&afhi->chunk_tv));
458         afhi->techinfo = make_message("%cbr, %s", vbr? 'v' : 'c',
459                 header_mode(&header));
460         mp3_get_id3(map, numbytes, fd, &afhi->tags);
461         return 1;
462 err_out:
463         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
464         free(afhi->chunk_table);
465         return ret;
466 }
467
468 /*
469  * Read mp3 information from audio file
470  */
471 static int mp3_get_file_info(char *map, size_t numbytes, int fd,
472                 struct afh_info *afhi)
473 {
474         int ret;
475
476         ret = mp3_read_info((unsigned char *)map, numbytes, fd, afhi);
477         if (ret < 0)
478                 return ret;
479         if (afhi->seconds_total < 2 || !afhi->chunks_total)
480                 return -E_MP3_INFO;
481         return 1;
482 }
483
484 static const char* mp3_suffixes[] = {"mp3", NULL};
485
486 /**
487  * the init function of the mp3 audio format handler
488  *
489  * \param afh pointer to the struct to initialize
490  */
491 void mp3_init(struct audio_format_handler *afh)
492 {
493         afh->get_file_info = mp3_get_file_info;
494         afh->suffixes = mp3_suffixes;
495 }