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