4eaad087f1405d3b7ee85d8ec4121c0cac15bf21
[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 "afh.h"
35 #include "error.h"
36 #include "fd.h"
37 #include "string.h"
38
39 /** \cond some defines and structs which are only used in this file */
40
41 /*
42 * MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames we need
43 * to see before we decide we are looking at a real MP3 file
44 */
45 #define MIN_CONSEC_GOOD_FRAMES 4
46
47 #define FRAME_HEADER_SIZE 4
48 #define MIN_FRAME_SIZE 21
49 #define DEFAULT_INBUF_SIZE 8192
50
51 struct mp3header {
52 unsigned long sync;
53 unsigned int version;
54 unsigned int layer;
55 unsigned int crc;
56 unsigned int bitrate;
57 unsigned int freq;
58 unsigned int padding;
59 unsigned int mode;
60 unsigned int copyright;
61 unsigned int original;
62 unsigned int emphasis;
63 };
64
65 struct id3tag {
66 char title[31];
67 char artist[31];
68 char album[31];
69 char year[5];
70 char comment[31];
71 };
72
73 struct mp3info {
74 char *filename;
75 struct mp3header header;
76 int id3_isvalid;
77 struct id3tag id3;
78 int vbr;
79 long unsigned br_average;
80 long unsigned seconds;
81 int freq;
82 };
83
84 /** \endcond */
85 static int frequencies[3][4] = {
86 {22050,24000,16000,50000}, /* MPEG 2.0 */
87 {44100,48000,32000,50000}, /* MPEG 1.0 */
88 {11025,12000,8000,50000} /* MPEG 2.5 */
89 };
90
91 static int mp3info_bitrate[2][3][14] = {
92 { /* MPEG 2.0 */
93 {32,48,56,64,80,96,112,128,144,160,176,192,224,256}, /* layer 1 */
94 {8,16,24,32,40,48,56,64,80,96,112,128,144,160}, /* layer 2 */
95 {8,16,24,32,40,48,56,64,80,96,112,128,144,160} /* layer 3 */
96 },
97
98 { /* MPEG 1.0 */
99 {32,64,96,128,160,192,224,256,288,320,352,384,416,448}, /* layer 1 */
100 {32,48,56,64,80,96,112,128,160,192,224,256,320,384}, /* layer 2 */
101 {32,40,48,56,64,80,96,112,128,160,192,224,256,320} /* layer 3 */
102 }
103 };
104
105 static int frame_size_index[] = {24000, 72000, 72000};
106 static const char *mode_text[] = {"stereo", "joint stereo", "dual channel", "mono", "invalid"};
107
108 static FILE *infile;
109 static struct mp3info mp3;
110 static char *inbuf;
111 static size_t inbuf_size;
112 static struct audio_format_handler *af;
113 static ssize_t *chunk_table, num_chunks;
114
115 static int header_frequency(struct mp3header *h)
116 {
117 if (h->version > 2 || h->freq > 3)
118 return -E_HEADER_FREQ;
119 return frequencies[h->version][h->freq];
120 }
121
122 static const char *header_mode(struct mp3header *h)
123 {
124 if (h->mode > 4)
125 h->mode = 4; /* invalid */
126 return mode_text[h->mode];
127 }
128 static int header_bitrate(struct mp3header *h)
129 {
130 if (h->layer > 3 || h->bitrate > 14)
131 return -E_HEADER_BITRATE;
132 return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
133 }
134
135 static int frame_length(struct mp3header *header)
136 {
137 int hb, hf = header_frequency(header);
138
139 if (hf < 0)
140 return hf;
141 hb = header_bitrate(header);
142 if (hb < 0)
143 return hb;
144 if (header->sync != 0xFFE || header->layer > 3)
145 return -E_FRAME;
146 return frame_size_index[3 - header->layer] *
147 ((header->version & 1) + 1) * hb / hf
148 + header->padding;
149 }
150
151 static void write_info_str(char *info_str)
152 {
153 int v = mp3.id3_isvalid;
154
155 snprintf(info_str, MMD_INFO_SIZE,
156 "audio_file_info1:%d x %lums, %lu kbit/s (%cbr) %i KHz %s\n"
157 "audio_file_info2:%s, by %s\n"
158 "audio_file_info3:A: %s, Y: %s, C: %s\n",
159 num_chunks,
160 tv2ms(&af->chunk_tv),
161 mp3.br_average,
162 mp3.vbr? 'v' : 'c',
163 mp3.freq / 1000,
164 header_mode(&mp3.header),
165 v && *mp3.id3.title? mp3.id3.title : "(title tag not set)",
166 v && *mp3.id3.artist? mp3.id3.artist : "(artist tag not set)",
167 v && *mp3.id3.album? mp3.id3.album : "(album tag not set)",
168 v && *mp3.id3.year? mp3.id3.year : "????",
169 v && *mp3.id3.comment? mp3.id3.comment : "(comment tag not set)"
170 );
171 }
172
173 /*
174 * Remove trailing whitespace from the end of a string
175 */
176 static char *unpad(char *string)
177 {
178 char *pos = string + strlen(string) - 1;
179 while (isspace(pos[0]))
180 (pos--)[0] = 0;
181 return string;
182 }
183
184 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
185 {
186 if ((*(uint*)h1) == (*(uint*)h2))
187 return 1;
188 if ((h1->version == h2->version) &&
189 (h1->layer == h2->layer) &&
190 (h1->crc == h2->crc) &&
191 (h1->freq == h2->freq) &&
192 (h1->mode == h2->mode) &&
193 (h1->copyright == h2->copyright) &&
194 (h1->original == h2->original) &&
195 (h1->emphasis == h2->emphasis))
196 return 1;
197 else
198 return 0;
199 }
200
201 /**
202 * get next MP3 frame header.
203 *
204 * \param stream to read the header from
205 * \param header structure that gets filled in by get_header()
206 *
207 * \return On success, the header frame length is returned. A return value of
208 * zero means that we did not retrieve a valid frame header, and a negative
209 * return value indicates an error.
210 */
211 static int get_header(FILE *file, struct mp3header *header)
212 {
213 unsigned char buffer[FRAME_HEADER_SIZE];
214 int fl, ret;
215
216 if (!file || !header)
217 return -E_MP3_NO_FILE;
218 ret = para_fread(buffer, FRAME_HEADER_SIZE, 1, file);
219 if (ret < FRAME_HEADER_SIZE) {
220 header->sync = 0;
221 return ret < 0? ret : 0;
222 }
223 header->layer = (buffer[1] >> 1) & 3;
224 header->sync = (((int)buffer[0]<<4) | ((int)(buffer[1]&0xE0)>>4));
225 if (buffer[1] & 0x10)
226 header->version = (buffer[1] >> 3) & 1;
227 else
228 header->version = 2;
229 if ((header->sync != 0xFFE) || (header->layer != 1)) {
230 header->sync = 0;
231 // PARA_DEBUG_LOG("%s: header not found\n", __func__);
232 return 0;
233 }
234 header->crc = buffer[1] & 1;
235 header->bitrate = (buffer[2] >> 4) & 0x0F;
236 // PARA_DEBUG_LOG("%s: found header, bitrate: %u\n", __func__,
237 // header->bitrate);
238 header->freq = (buffer[2] >> 2) & 0x3;
239 header->padding = (buffer[2] >>1) & 0x1;
240 header->mode = (buffer[3] >> 6) & 0x3;
241 fl = frame_length(header);
242 return (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
243 }
244
245 /**
246 * find the next mp3 header
247 *
248 * \return On success, the length of the next frame header. If the end of the
249 * file was reached, the function returns zero. On errors, a negative value is
250 * returned.
251 *
252 */
253 static int mp3_seek_next_header(void)
254 {
255 int k, l = 0, c, first_len, ret;
256 struct mp3header h, h2;
257 long valid_start = 0;
258
259 while (1) {
260 while ((c = fgetc(infile)) != 255 && (c != EOF))
261 ; /* nothing */
262 if (c != 255)
263 return 0;
264 ungetc(c, infile);
265 valid_start = ftell(infile);
266 first_len = get_header(infile, &h);
267 if (first_len <= 0)
268 continue;
269 ret = para_fseek(infile, first_len - FRAME_HEADER_SIZE, SEEK_CUR);
270 if (ret < 0)
271 return ret;
272 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
273 if ((l = get_header(infile, &h2)) <= 0)
274 break;
275 if (!compare_headers(&h, &h2))
276 break;
277 ret = para_fseek(infile, l - FRAME_HEADER_SIZE, SEEK_CUR);
278 if (ret < 0)
279 return ret;
280 }
281 if (k == MIN_CONSEC_GOOD_FRAMES) {
282 ret = para_fseek(infile, valid_start, SEEK_SET);
283 if (ret < 0)
284 return ret;
285 memcpy(&(mp3.header), &h2, sizeof(struct mp3header));
286 return first_len;
287 }
288 }
289 }
290
291 static int mp3_get_id3(void)
292 {
293 char fbuf[4];
294 int ret;
295
296 mp3.id3_isvalid = 0;
297 mp3.id3.title[0] = '\0';
298 mp3.id3.artist[0] = '\0';
299 mp3.id3.album[0] = '\0';
300 mp3.id3.comment[0] = '\0';
301 mp3.id3.year[0] = '\0';
302 ret = para_fseek(infile, -128, SEEK_END);
303 if (ret < 0 )
304 return ret;
305 if (para_fread(fbuf, 1, 3, infile) < 0)
306 return -E_FREAD;
307 fbuf[3] = '\0';
308 if (strcmp("TAG", fbuf)) {
309 PARA_INFO_LOG("%s", "no id3 tag\n");
310 return 0;
311 }
312 ret = para_fseek(infile, -125, SEEK_END);
313 if (ret < 0)
314 return ret;
315 if (para_fread(mp3.id3.title, 1, 30, infile) != 30)
316 return -E_FREAD;
317 mp3.id3.title[30] = '\0';
318 if (para_fread(mp3.id3.artist, 1, 30, infile) != 30)
319 return -E_FREAD;
320 mp3.id3.artist[30] = '\0';
321 if (para_fread(mp3.id3.album, 1, 30, infile) != 30)
322 return -E_FREAD;
323 mp3.id3.album[30] = '\0';
324 if (para_fread(mp3.id3.year, 1, 4, infile) != 4)
325 return -E_FREAD;
326 mp3.id3.year[4] = '\0';
327 if (para_fread(mp3.id3.comment, 1, 30, infile) != 30)
328 return -E_FREAD;
329 mp3.id3.comment[30] = '\0';
330 mp3.id3_isvalid = 1;
331 unpad(mp3.id3.title);
332 unpad(mp3.id3.artist);
333 unpad(mp3.id3.album);
334 unpad(mp3.id3.year);
335 unpad(mp3.id3.comment);
336 return 1;
337 }
338
339 static int find_valid_start(void)
340 {
341 int ret, frame_len;
342
343 if (!infile)
344 return -E_MP3_NO_FILE;
345 frame_len = get_header(infile, &mp3.header);
346 if (frame_len < 0)
347 return frame_len;
348 if (!frame_len) {
349 frame_len = mp3_seek_next_header();
350 if (frame_len <= 0)
351 return frame_len;
352 } else {
353 ret = para_fseek(infile, -FRAME_HEADER_SIZE, SEEK_CUR);
354 if (ret < 0)
355 return ret;
356 }
357 if (frame_len <= 1)
358 return -E_FRAME_LENGTH;
359 return frame_len;
360 }
361
362 static int mp3_read_info(void)
363 {
364 long fl_avg = 0, freq_avg = 0, br_avg = 0;
365 int ret, len = 0, old_br = -1;
366 struct timeval total_time = {0, 0};
367 unsigned chunk_table_size = 1000; /* gets increased on demand */
368
369 num_chunks = 0;
370 inbuf = para_malloc(DEFAULT_INBUF_SIZE);
371 inbuf_size = DEFAULT_INBUF_SIZE;
372 chunk_table = para_malloc(chunk_table_size * sizeof(size_t));
373 ret = mp3_get_id3();
374 if (ret < 0)
375 goto err_out;
376 rewind(infile);
377 mp3.vbr = 0;
378 mp3.freq = 0;
379 while (1) {
380 int freq, br, fl;
381 struct timeval tmp, cct; /* current chunk time */
382 if (len > 0) {
383 ret = para_fseek(infile, len, SEEK_CUR);
384 if (ret < 0)
385 goto err_out;
386 }
387 len = find_valid_start();
388 if (len <= 0)
389 break;
390 freq = header_frequency(&mp3.header);
391 br = header_bitrate(&mp3.header);
392 fl = frame_length(&mp3.header);
393 if (freq < 0 || br < 0 || fl < 0)
394 continue;
395 tmp.tv_sec = fl;
396 tmp.tv_usec = 0;
397 tv_divide(br * 125, &tmp, &cct);
398 tv_add(&cct, &total_time, &tmp);
399 total_time = tmp;
400 //PARA_DEBUG_LOG("%s: br: %d, freq: %d, fl: %d, cct: %lu\n", __func__, br, freq, fl, cct.tv_usec);
401 if (num_chunks >= chunk_table_size) {
402 chunk_table_size *= 2;
403 chunk_table = para_realloc(chunk_table,
404 chunk_table_size * sizeof(size_t));
405 }
406 chunk_table[num_chunks] = ftell(infile);
407 if (num_chunks < 10 || !(num_chunks % 1000))
408 PARA_INFO_LOG("chunk #%d: %zd\n", num_chunks,
409 chunk_table[num_chunks]);
410 num_chunks++;
411 if (num_chunks == 1) {
412 // entry = ftell(infile);
413 // PARA_INFO_LOG("entry: %zd\n", entry);
414 freq_avg = freq;
415 br_avg = br;
416 old_br = br;
417 fl_avg = fl;
418 continue;
419 }
420 freq_avg += (freq - freq_avg) / (num_chunks + 1);
421 fl_avg += (fl - fl_avg) / (num_chunks + 1);
422 br_avg += (br - br_avg) / (num_chunks + 1);
423 if (old_br != br)
424 mp3.vbr = 1;
425 old_br = br;
426 }
427 ret = -E_MP3_INFO;
428 if (!num_chunks || !freq_avg || !br_avg)
429 goto err_out;
430 ret= para_fseek(infile, 0, SEEK_END);
431 if (ret < 0)
432 goto err_out;
433 chunk_table[num_chunks] = ftell(infile);
434 mp3.br_average = br_avg;
435 mp3.freq = freq_avg;
436 mp3.seconds = (tv2ms(&total_time) + 500) / 1000;
437 tv_divide(num_chunks, &total_time, &af->chunk_tv);
438 rewind(infile);
439 PARA_DEBUG_LOG("%zu chunks, each %lums\n", num_chunks, tv2ms(&af->chunk_tv));
440 tv_scale(3, &af->chunk_tv, &af->eof_tv);
441 PARA_DEBUG_LOG("eof timeout: %lu\n", tv2ms(&af->eof_tv));
442 return 1;
443 err_out:
444 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
445 free(chunk_table);
446 free(inbuf);
447 return ret;
448 }
449
450 /*
451 * Read mp3 information from audio file
452 */
453 static int mp3_get_file_info(FILE *audio_file, char *info_str,
454 long unsigned *frames, int *seconds, size_t **vss_chunk_table)
455 {
456 int ret;
457
458 if (!audio_file)
459 return -E_MP3_NO_FILE;
460 infile = audio_file;
461 ret = mp3_read_info();
462 if (ret < 0) {
463 infile = NULL;
464 return ret;
465 }
466 write_info_str(info_str);
467 *frames = num_chunks;
468 *seconds = mp3.seconds;
469 *vss_chunk_table = chunk_table;
470 if (*seconds < 2 || !*frames)
471 return -E_MP3_INFO;
472 return 1;
473 }
474
475 static void mp3_close_audio_file(void)
476 {
477 if (!infile)
478 return;
479 fclose(infile);
480 infile = NULL;
481 free(chunk_table);
482 free(inbuf);
483 }
484
485 static const char* mp3_suffixes[] = {"mp3", NULL};
486
487 /**
488 * the init function of the mp3 audio format handler
489 *
490 * \param p pointer to the struct to initialize
491 */
492 void mp3_init(struct audio_format_handler *p)
493 {
494 af = p;
495 af->get_file_info = mp3_get_file_info;
496 af->close_audio_file = mp3_close_audio_file;
497 af->get_header_info = NULL;
498 /* eof_tv gets overwritten in mp3_get_file_info() */
499 af->eof_tv.tv_sec = 0;
500 af->eof_tv.tv_usec = 100 * 1000;
501 af->suffixes = mp3_suffixes;
502 }