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