ca487efc40abfde3a2778ae3b9b63ecfd36c8613
[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;
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 if (fseek(infile, first_len - FRAME_HEADER_SIZE, SEEK_CUR) < 0)
270 return -E_FSEEK;
271 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
272 if ((l = get_header(infile, &h2)) <= 0)
273 break;
274 if (!compare_headers(&h, &h2))
275 break;
276 fseek(infile, l - FRAME_HEADER_SIZE, SEEK_CUR);
277 }
278 if (k == MIN_CONSEC_GOOD_FRAMES) {
279 fseek(infile, valid_start, SEEK_SET);
280 memcpy(&(mp3.header), &h2, sizeof(struct mp3header));
281 return first_len;
282 }
283 }
284 }
285
286 static int mp3_get_id3(void)
287 {
288 char fbuf[4];
289
290 mp3.id3_isvalid = 0;
291 mp3.id3.title[0] = '\0';
292 mp3.id3.artist[0] = '\0';
293 mp3.id3.album[0] = '\0';
294 mp3.id3.comment[0] = '\0';
295 mp3.id3.year[0] = '\0';
296 if (fseek(infile, -128, SEEK_END))
297 return -E_FSEEK;
298 if (para_fread(fbuf, 1, 3, infile) < 0)
299 return -E_FREAD;
300 fbuf[3] = '\0';
301 if (strcmp("TAG", fbuf)) {
302 PARA_INFO_LOG("%s", "no id3 tag\n");
303 return 0;
304 }
305 if (fseek(infile, -125, SEEK_END) < 0)
306 return -E_FSEEK;
307 if (para_fread(mp3.id3.title, 1, 30, infile) != 30)
308 return -E_FREAD;
309 mp3.id3.title[30] = '\0';
310 if (para_fread(mp3.id3.artist, 1, 30, infile) != 30)
311 return -E_FREAD;
312 mp3.id3.artist[30] = '\0';
313 if (para_fread(mp3.id3.album, 1, 30, infile) != 30)
314 return -E_FREAD;
315 mp3.id3.album[30] = '\0';
316 if (para_fread(mp3.id3.year, 1, 4, infile) != 4)
317 return -E_FREAD;
318 mp3.id3.year[4] = '\0';
319 if (para_fread(mp3.id3.comment, 1, 30, infile) != 30)
320 return -E_FREAD;
321 mp3.id3.comment[30] = '\0';
322 mp3.id3_isvalid = 1;
323 unpad(mp3.id3.title);
324 unpad(mp3.id3.artist);
325 unpad(mp3.id3.album);
326 unpad(mp3.id3.year);
327 unpad(mp3.id3.comment);
328 return 1;
329 }
330
331 static int find_valid_start(void)
332 {
333 int frame_len;
334
335 if (!infile)
336 return -E_MP3_NO_FILE;
337 frame_len = get_header(infile, &mp3.header);
338 if (frame_len < 0)
339 return frame_len;
340 if (!frame_len) {
341 frame_len = mp3_seek_next_header();
342 if (frame_len <= 0)
343 return frame_len;
344 } else
345 if (fseek(infile, -FRAME_HEADER_SIZE, SEEK_CUR) < 0)
346 return -E_FSEEK;
347 if (frame_len <= 1)
348 return -E_FRAME_LENGTH;
349 return frame_len;
350 }
351
352 static int mp3_read_info(void)
353 {
354 long fl_avg = 0, freq_avg = 0, br_avg = 0;
355 int ret, len = 0, old_br = -1;
356 struct timeval total_time = {0, 0};
357 unsigned chunk_table_size = 1000; /* gets increased on demand */
358
359 num_chunks = 0;
360 inbuf = para_malloc(DEFAULT_INBUF_SIZE);
361 inbuf_size = DEFAULT_INBUF_SIZE;
362 chunk_table = para_malloc(chunk_table_size * sizeof(size_t));
363 ret = mp3_get_id3();
364 if (ret < 0)
365 goto err_out;
366 rewind(infile);
367 mp3.vbr = 0;
368 mp3.freq = 0;
369 while (1) {
370 int freq, br, fl;
371 struct timeval tmp, cct; /* current chunk time */
372 if (len > 0) {
373 ret = -E_FSEEK;
374 if (fseek(infile, len, SEEK_CUR) < 0)
375 goto err_out;
376 }
377 len = find_valid_start();
378 if (len <= 0)
379 break;
380 freq = header_frequency(&mp3.header);
381 br = header_bitrate(&mp3.header);
382 fl = frame_length(&mp3.header);
383 if (freq < 0 || br < 0 || fl < 0)
384 continue;
385 tmp.tv_sec = fl;
386 tmp.tv_usec = 0;
387 tv_divide(br * 125, &tmp, &cct);
388 tv_add(&cct, &total_time, &tmp);
389 total_time = tmp;
390 //PARA_DEBUG_LOG("%s: br: %d, freq: %d, fl: %d, cct: %lu\n", __func__, br, freq, fl, cct.tv_usec);
391 if (num_chunks >= chunk_table_size) {
392 chunk_table_size *= 2;
393 chunk_table = para_realloc(chunk_table,
394 chunk_table_size * sizeof(size_t));
395 }
396 chunk_table[num_chunks] = ftell(infile);
397 if (num_chunks < 10 || !(num_chunks % 1000))
398 PARA_INFO_LOG("chunk #%d: %zd\n", num_chunks,
399 chunk_table[num_chunks]);
400 num_chunks++;
401 if (num_chunks == 1) {
402 // entry = ftell(infile);
403 // PARA_INFO_LOG("entry: %zd\n", entry);
404 freq_avg = freq;
405 br_avg = br;
406 old_br = br;
407 fl_avg = fl;
408 continue;
409 }
410 freq_avg += (freq - freq_avg) / (num_chunks + 1);
411 fl_avg += (fl - fl_avg) / (num_chunks + 1);
412 br_avg += (br - br_avg) / (num_chunks + 1);
413 if (old_br != br)
414 mp3.vbr = 1;
415 old_br = br;
416 }
417 ret = -E_MP3_INFO;
418 if (!num_chunks || !freq_avg || !br_avg)
419 goto err_out;
420 ret = -E_FSEEK;
421 if (fseek(infile, 0, SEEK_END) < 0)
422 goto err_out;
423 chunk_table[num_chunks] = ftell(infile);
424 mp3.br_average = br_avg;
425 mp3.freq = freq_avg;
426 mp3.seconds = (tv2ms(&total_time) + 500) / 1000;
427 tv_divide(num_chunks, &total_time, &af->chunk_tv);
428 rewind(infile);
429 PARA_DEBUG_LOG("%zu chunks, each %lums\n", num_chunks, tv2ms(&af->chunk_tv));
430 tv_scale(3, &af->chunk_tv, &af->eof_tv);
431 PARA_DEBUG_LOG("eof timeout: %lu\n", tv2ms(&af->eof_tv));
432 return 1;
433 err_out:
434 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
435 free(chunk_table);
436 free(inbuf);
437 return ret;
438 }
439
440 /*
441 * Read mp3 information from audio file
442 */
443 static int mp3_get_file_info(FILE *audio_file, char *info_str,
444 long unsigned *frames, int *seconds)
445 {
446 int ret;
447
448 if (!audio_file)
449 return -E_MP3_NO_FILE;
450 infile = audio_file;
451 ret = mp3_read_info();
452 if (ret < 0) {
453 infile = NULL;
454 return ret;
455 }
456 write_info_str(info_str);
457 *frames = num_chunks;
458 *seconds = mp3.seconds;
459 if (*seconds < 2 || !*frames)
460 return -E_MP3_INFO;
461 return 1;
462 }
463
464 static int mp3_reposition_stream(__a_unused long unsigned new_frame)
465 {
466 return 1;
467 }
468
469 static char *mp3_read_chunk(long unsigned current_chunk, ssize_t *len)
470 {
471 int ret;
472 size_t pos;
473
474 *len = 0;
475 if (current_chunk >= num_chunks)
476 return NULL;
477 pos = chunk_table[current_chunk];
478 *len = chunk_table[current_chunk + 1] - chunk_table[current_chunk];
479 if (inbuf_size < *len) {
480 PARA_INFO_LOG("increasing inbuf for chunk #%lu/%zu to %zd bytes\n",
481 current_chunk, num_chunks, *len);
482 inbuf = para_realloc(inbuf, *len);
483 inbuf_size = *len;
484 }
485 // PARA_DEBUG_LOG("reading chunk #%lu@%zd (%zd bytes)\n", current_chunk,
486 // pos, *len);
487 ret = fseek(infile, pos, SEEK_SET);
488 if (ret < 0)
489 return NULL;
490 ret = para_fread(inbuf, *len, 1, infile);
491 if (ret != *len)
492 return NULL;
493 // PARA_DEBUG_LOG("ret: %d, inbuf[0]: %lx - %lx\n", ret, (long unsigned) inbuf[0],
494 // (long unsigned) inbuf[4]);
495 return (char *)inbuf;
496 }
497
498 static void mp3_close_audio_file(void)
499 {
500 if (!infile)
501 return;
502 fclose(infile);
503 infile = NULL;
504 free(chunk_table);
505 free(inbuf);
506 }
507
508 static const char* mp3_suffixes[] = {"mp3", NULL};
509
510 /**
511 * the init function of the mp3 audio format handler
512 *
513 * \param p pointer to the struct to initialize
514 */
515 void mp3_init(struct audio_format_handler *p)
516 {
517 af = p;
518 af->get_file_info = mp3_get_file_info;
519 af->reposition_stream = mp3_reposition_stream;
520 af->read_chunk = mp3_read_chunk;
521 af->close_audio_file = mp3_close_audio_file;
522 af->get_header_info = NULL;
523 /* eof_tv gets overwritten in mp3_get_file_info() */
524 af->eof_tv.tv_sec = 0;
525 af->eof_tv.tv_usec = 100 * 1000;
526 af->suffixes = mp3_suffixes;
527 }