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