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