Link para_server and para_afh against libid3tag if available.
[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 /*
75  * Remove trailing whitespace from the end of a string
76  */
77 static char *unpad(char *string)
78 {
79         char *pos = string + strlen(string) - 1;
80         while (para_isspace(pos[0]))
81                 (pos--)[0] = 0;
82         return string;
83 }
84
85 static char *mp3_get_id3(unsigned char *map, size_t numbytes)
86 {
87         char title[31], artist[31], album[31], year[5], comment[31];
88         off_t fpos;
89
90         if (numbytes < 128 || strncmp("TAG", (char *)map + numbytes - 128, 3)) {
91                 PARA_DEBUG_LOG("no id3 v1 tag\n");
92                 return make_message("%s: (no id3 v1 tag)\n%s:\n",
93                         status_item_list[SI_TAGINFO1],
94                         status_item_list[SI_TAGINFO2]);
95         }
96         fpos = numbytes - 125;
97         memcpy(title, map + fpos, 30);
98         fpos += 30;
99         title[30] = '\0';
100         memcpy(artist, map + fpos, 30);
101         fpos += 30;
102         artist[30] = '\0';
103         memcpy(album, map + fpos, 30);
104         fpos += 30;
105         album[30] = '\0';
106         memcpy(year, map + fpos, 4);
107         fpos += 4;
108         year[4] = '\0';
109         memcpy(comment, map + fpos, 30);
110         comment[30] = '\0';
111         unpad(title);
112         unpad(artist);
113         unpad(album);
114         unpad(year);
115         unpad(comment);
116         return make_message("%s: %s, by %s\n" /* taginfo1 */
117                 "%s: A: %s, Y: %s, C: %s\n", /* taginfo 2*/
118                 status_item_list[SI_TAGINFO1],
119                 *title? title : "(title tag not set)",
120                 *artist? artist : "(artist tag not set)",
121                 status_item_list[SI_TAGINFO2],
122                 *album?  album : "(album tag not set)",
123                 *year? year : "????",
124                 *comment? comment : "(comment tag not set)"
125         );
126 }
127
128 static int header_frequency(struct mp3header *h)
129 {
130         if (h->version > 2 || h->freq > 3)
131                 return -E_HEADER_FREQ;
132         return frequencies[h->version][h->freq];
133 }
134
135 static const char *header_mode(struct mp3header *h)
136 {
137         if (h->mode > 4)
138                 h->mode = 4; /* invalid */
139         return mode_text[h->mode];
140 }
141
142 static int header_channels(struct mp3header *h)
143 {
144         if (h->mode > 3)
145                 return 0;
146         if (h->mode < 3)
147                 return 2;
148         return 1;
149 }
150
151 static int header_bitrate(struct mp3header *h)
152 {
153         if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
154                 return -E_HEADER_BITRATE;
155         return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
156 }
157
158 static int frame_length(struct mp3header *header)
159 {
160         int hb, hf = header_frequency(header);
161
162         if (hf < 0)
163                 return hf;
164         hb = header_bitrate(header);
165         if (hb < 0)
166                 return hb;
167         if (header->sync != 0xFFE || header->layer > 3)
168                 return -E_FRAME;
169         return frame_size_index[3 - header->layer] *
170                 ((header->version & 1) + 1) * hb / hf
171                 + header->padding;
172 }
173
174 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
175 {
176         if ((*(uint*)h1) == (*(uint*)h2))
177                 return 1;
178         if ((h1->version == h2->version) &&
179                         (h1->layer == h2->layer) &&
180                         (h1->crc == h2->crc) &&
181                         (h1->freq == h2->freq) &&
182                         (h1->mode == h2->mode) &&
183                         (h1->copyright == h2->copyright) &&
184                         (h1->original == h2->original) &&
185                         (h1->emphasis == h2->emphasis))
186                 return 1;
187         return 0;
188 }
189
190 /*
191  * get next MP3 frame header.
192  *
193  * On success, the header frame length is returned and the given header
194  * structure that is filled in.  A return value of zero means that we did not
195  * retrieve a valid frame header, and a negative return value indicates an
196  * error.
197  */
198 static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
199         struct mp3header *header)
200 {
201         int fl, ret;
202
203         if (*fpos + FRAME_HEADER_SIZE > numbytes) {
204                 *fpos = numbytes - 1;
205                 header->sync = 0;
206                 return 0;
207         }
208         header->layer = (map[*fpos + 1] >> 1) & 3;
209         header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
210         if (map[*fpos + 1] & 0x10)
211                 header->version = (map[*fpos + 1] >> 3) & 1;
212         else
213                 header->version = 2;
214         if ((header->sync != 0xFFE) || (header->layer != 1)) {
215                 ret = 0;
216                 header->sync = 0;
217                 goto out;
218         }
219         header->crc = map[*fpos + 1] & 1;
220         header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
221         header->freq = (map[*fpos + 2] >> 2) & 0x3;
222         header->padding = (map[*fpos + 2] >>1) & 0x1;
223         header->mode = (map[*fpos + 3] >> 6) & 0x3;
224         fl = frame_length(header);
225         ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
226 out:
227         *fpos += FRAME_HEADER_SIZE;
228         return ret;
229 }
230
231 /*
232  * find the next mp3 header
233  *
234  * Return the length of the next frame header or zero if the end of the file is
235  * reached.
236  */
237 static int mp3_seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
238         struct mp3header *result)
239 {
240         int k, l = 0, first_len;
241         struct mp3header h, h2;
242         long valid_start = 0;
243
244         for (; *fpos < numbytes; (*fpos)++) {
245                 if (map[*fpos] != 0xff)
246                         continue;
247                 valid_start = *fpos;
248                 first_len = get_header(map, numbytes, fpos, &h);
249                 if (first_len <= 0)
250                         continue;
251                 *fpos += first_len - FRAME_HEADER_SIZE;
252                 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
253                         if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
254                                 break;
255                         if (!compare_headers(&h, &h2))
256                                 break;
257                         *fpos += l - FRAME_HEADER_SIZE;
258                 }
259                 if (k == MIN_CONSEC_GOOD_FRAMES) {
260                         *fpos = valid_start;
261                         *result = h2;
262                         return first_len;
263                 }
264         }
265         return 0;
266 }
267
268 static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
269         struct mp3header *header)
270 {
271         int frame_len;
272
273         frame_len = get_header(map, numbytes, fpos, header);
274         if (frame_len < 0)
275                 return frame_len;
276         if (!frame_len) {
277                 frame_len = mp3_seek_next_header(map, numbytes, fpos, header);
278                 if (frame_len <= 0)
279                         return frame_len;
280         } else
281                 *fpos -= FRAME_HEADER_SIZE;
282         if (frame_len <= 1)
283                 return -E_FRAME_LENGTH;
284         return frame_len;
285 }
286
287 static int mp3_read_info(unsigned char *map, size_t numbytes,
288                 struct afh_info *afhi)
289 {
290         long freq_avg = 0, br_avg = 0;
291         int ret, len = 0, old_br = -1, vbr = 0;
292         struct timeval total_time = {0, 0};
293         unsigned chunk_table_size = 1000; /* gets increased on demand */
294         off_t fpos = 0;
295         struct mp3header header;
296         char *taginfo;
297
298         afhi->chunks_total = 0;
299         afhi->chunk_table = para_malloc(chunk_table_size * sizeof(size_t));
300         taginfo = mp3_get_id3(map, numbytes);
301         while (1) {
302                 unsigned long freq, br, fl;
303                 struct timeval tmp, cct; /* current chunk time */
304                 fpos += len;
305                 len = find_valid_start(map, numbytes, &fpos, &header);
306                 if (len <= 0)
307                         break;
308                 ret = header_frequency(&header);
309                 if (ret < 0)
310                         continue;
311                 freq = ret;
312                 ret = header_bitrate(&header);
313                 if (ret < 0)
314                         continue;
315                 br = ret;
316                 ret = frame_length(&header);
317                 if (ret < 0)
318                         continue;
319                 fl = ret;
320                 tmp.tv_sec = fl;
321                 tmp.tv_usec = 0;
322                 tv_divide(br * 125, &tmp, &cct);
323                 tv_add(&cct, &total_time, &tmp);
324                 total_time = tmp;
325                 //PARA_DEBUG_LOG("%s: br: %d, freq: %d, fl: %d, cct: %lu\n", __func__, br, freq, fl, cct.tv_usec);
326                 if (afhi->chunks_total >= chunk_table_size) {
327                         chunk_table_size *= 2;
328                         afhi->chunk_table = para_realloc(afhi->chunk_table,
329                                 chunk_table_size * sizeof(size_t));
330                 }
331                 afhi->chunk_table[afhi->chunks_total] = fpos;
332 //              if (afhi->chunks_total < 10 || !(afhi->chunks_total % 1000))
333 //                      PARA_INFO_LOG("chunk #%lu: %zd\n", afhi->chunks_total,
334 //                              afhi->chunk_table[afhi->chunks_total]);
335                 afhi->chunks_total++;
336                 if (afhi->chunks_total == 1) {
337                         freq_avg = freq;
338                         br_avg = br;
339                         old_br = br;
340                         continue;
341                 }
342                 freq_avg += ((long)freq - freq_avg) / ((long)afhi->chunks_total + 1);
343                 br_avg += ((long)br - br_avg) / ((long)afhi->chunks_total + 1);
344                 if (old_br != br)
345                         vbr = 1;
346                 old_br = br;
347         }
348         ret = -E_MP3_INFO;
349         if (!afhi->chunks_total || !freq_avg || !br_avg)
350                 goto err_out;
351         afhi->chunk_table[afhi->chunks_total] = numbytes - 1;
352         afhi->bitrate = br_avg;
353         afhi->frequency = freq_avg;
354         afhi->channels = header_channels(&header);
355         afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
356         tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
357         PARA_DEBUG_LOG("%lu chunks, each %lums\n", afhi->chunks_total,
358                 tv2ms(&afhi->chunk_tv));
359         tv_scale(3, &afhi->chunk_tv, &afhi->eof_tv);
360         PARA_DEBUG_LOG("eof timeout: %lu\n", tv2ms(&afhi->eof_tv));
361         afhi->info_string = make_message("%s: %cbr, %s\n%s",
362                 status_item_list[SI_AUDIO_FILE_INFO], vbr? 'v' : 'c',
363                 header_mode(&header), taginfo);
364         free(taginfo);
365         return 1;
366 err_out:
367         free(taginfo);
368         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
369         free(afhi->chunk_table);
370         return ret;
371 }
372
373 /*
374  * Read mp3 information from audio file
375  */
376 static int mp3_get_file_info(char *map, size_t numbytes,
377                 struct afh_info *afhi)
378 {
379         int ret;
380
381         ret = mp3_read_info((unsigned char *)map, numbytes, afhi);
382         if (ret < 0)
383                 return ret;
384         if (afhi->seconds_total < 2 || !afhi->chunks_total)
385                 return -E_MP3_INFO;
386         return 1;
387 }
388
389 static const char* mp3_suffixes[] = {"mp3", NULL};
390
391 /**
392  * the init function of the mp3 audio format handler
393  *
394  * \param afh pointer to the struct to initialize
395  */
396 void mp3_init(struct audio_format_handler *afh)
397 {
398         afh->get_file_info = mp3_get_file_info;
399         afh->suffixes = mp3_suffixes;
400 }