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