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