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