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