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