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