First draft of the dccp sender/receiver pair.
[paraslash.git] / mp3.c
1 /*
2 * Copyright (C) 2003-2006 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.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 "afs.h"
34 #include "error.h"
35
36 /** \cond some defines and structs which are only used in this file */
37
38 /*
39 * MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames we need
40 * to see before we decide we are looking at a real MP3 file
41 */
42 #define MIN_CONSEC_GOOD_FRAMES 3
43
44 #define FRAME_HEADER_SIZE 4
45 #define MIN_FRAME_SIZE 21
46
47 struct mp3header {
48 unsigned long sync;
49 unsigned int version;
50 unsigned int layer;
51 unsigned int crc;
52 unsigned int bitrate;
53 unsigned int freq;
54 unsigned int padding;
55 unsigned int mode;
56 unsigned int copyright;
57 unsigned int original;
58 unsigned int emphasis;
59 };
60
61 struct id3tag {
62 char title[31];
63 char artist[31];
64 char album[31];
65 char year[5];
66 char comment[31];
67 };
68
69 struct mp3info {
70 char *filename;
71 FILE *file;
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 frames;
79 int freq;
80 };
81
82 /** \endcond */
83 static 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 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 int frame_size_index[] = {24000, 72000, 72000};
104 static char *mode_text[] = {"stereo", "joint stereo", "dual channel", "mono", "invalid"};
105
106 static struct mp3info mp3;
107 static char mp3buf[8192];
108 static int chunk_size;
109 static struct audio_format *af;
110
111 static __must_check int para_fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
112 {
113 size_t res = fread(ptr, size, nmemb, stream);
114 if (res == nmemb)
115 return size * nmemb;
116 if (feof(stream))
117 return 0;
118 return -E_FREAD;
119 }
120
121 static int header_frequency(struct mp3header *h)
122 {
123 if (h->version > 2 || h->freq > 3)
124 return -E_HEADER_FREQ;
125 return frequencies[h->version][h->freq];
126 }
127
128 static char *header_mode(struct mp3header *h)
129 {
130 if (h->mode > 4)
131 h->mode = 4; /* invalid */
132 return mode_text[h->mode];
133 }
134 static int header_bitrate(struct mp3header *h)
135 {
136 if (h->layer > 3 || h->bitrate > 14)
137 return -E_HEADER_BITRATE;
138 return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
139 }
140
141 static int frame_length(struct mp3header *header)
142 {
143 int hb, hf = header_frequency(header);
144
145 if (hf < 0)
146 return hf;
147 hb = header_bitrate(header);
148 if (hb < 0)
149 return hb;
150 if (header->sync != 0xFFE || header->layer > 3)
151 return -E_FRAME;
152 return frame_size_index[3 - header->layer] *
153 ((header->version & 1) + 1) * hb / hf
154 + header->padding;
155 }
156
157 static void write_info_str(char *info_str)
158 {
159 int v = mp3.id3_isvalid;
160
161 snprintf(info_str, MMD_INFO_SIZE,
162 "audio_file_info1:%d x %lu, %lu kbit/s (%cbr) %i KHz %s\n"
163 "audio_file_info2:%s, by %s\n"
164 "audio_file_info3:A: %s, Y: %s, C: %s\n",
165 mp3.frames,
166 af->chunk_tv.tv_usec,
167 mp3.br_average,
168 mp3.vbr? 'v' : 'c',
169 mp3.freq / 1000,
170 header_mode(&mp3.header),
171 v && *mp3.id3.title? mp3.id3.title : "(title tag not set)",
172 v && *mp3.id3.artist? mp3.id3.artist : "(artist tag not set)",
173 v && *mp3.id3.album? mp3.id3.album : "(album tag not set)",
174 v && *mp3.id3.year? mp3.id3.year : "????",
175 v && *mp3.id3.comment? mp3.id3.comment : "(comment tag not set)"
176 );
177 }
178
179 /*
180 * Remove trailing whitespace from the end of a string
181 */
182 static char *unpad(char *string)
183 {
184 char *pos = string + strlen(string) - 1;
185 while (isspace(pos[0]))
186 (pos--)[0] = 0;
187 return string;
188 }
189
190 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
191 {
192 if ((*(uint*)h1) == (*(uint*)h2))
193 return 1;
194 if ((h1->version == h2->version) &&
195 (h1->layer == h2->layer) &&
196 (h1->crc == h2->crc) &&
197 (h1->freq == h2->freq) &&
198 (h1->mode == h2->mode) &&
199 (h1->copyright == h2->copyright) &&
200 (h1->original == h2->original) &&
201 (h1->emphasis == h2->emphasis))
202 return 1;
203 else
204 return 0;
205 }
206
207 /**
208 * get next MP3 frame header.
209 *
210 * \param stream to read the header from
211 * \param header structure that gets filled in by get_header()
212 *
213 * \return On success, the header frame length is returned. A return value of
214 * zero means that we did not retrieve a valid frame header, and a negative
215 * return value indicates an error.
216 */
217 static int get_header(FILE *file, struct mp3header *header)
218 {
219 unsigned char buffer[FRAME_HEADER_SIZE];
220 int fl, ret;
221
222 if (!file || !header)
223 return -E_MP3_NO_FILE;
224 ret = para_fread(buffer, FRAME_HEADER_SIZE, 1, file);
225 if (ret < FRAME_HEADER_SIZE) {
226 header->sync = 0;
227 return ret < 0? ret : 0;
228 }
229 header->layer = (buffer[1] >> 1) & 3;
230 header->sync = (((int)buffer[0]<<4) | ((int)(buffer[1]&0xE0)>>4));
231 if (buffer[1] & 0x10)
232 header->version = (buffer[1] >> 3) & 1;
233 else
234 header->version = 2;
235 if ((header->sync != 0xFFE) || (header->layer != 1)) {
236 header->sync = 0;
237 // PARA_DEBUG_LOG("%s: header not found\n", __func__);
238 return 0;
239 }
240 header->crc = buffer[1] & 1;
241 header->bitrate = (buffer[2] >> 4) & 0x0F;
242 // PARA_DEBUG_LOG("%s: found header, bitrate: %u\n", __func__,
243 // header->bitrate);
244 header->freq = (buffer[2] >> 2) & 0x3;
245 header->padding = (buffer[2] >>1) & 0x1;
246 header->mode = (buffer[3] >> 6) & 0x3;
247 fl = frame_length(header);
248 return (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
249 }
250
251 /**
252 * find the next mp3 header
253 *
254 * \return On success, the length of the next frame header. If the end of the
255 * file was reached, the function returns zero. On errors, a negative value is
256 * returned.
257 *
258 */
259 static int mp3_seek_next_header(void)
260 {
261 int k, l = 0, c, first_len;
262 struct mp3header h, h2;
263 long valid_start = 0;
264
265 while (1) {
266 while ((c = fgetc(mp3.file)) != 255 && (c != EOF))
267 ; /* nothing */
268 if (c != 255)
269 return 0;
270 ungetc(c, mp3.file);
271 valid_start = ftell(mp3.file);
272 first_len = get_header(mp3.file, &h);
273 if (first_len <= 0)
274 continue;
275 if (fseek(mp3.file, first_len - FRAME_HEADER_SIZE, SEEK_CUR) < 0)
276 return -E_FSEEK;
277 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
278 if ((l = get_header(mp3.file, &h2)) <= 0)
279 break;
280 if (!compare_headers(&h, &h2))
281 break;
282 fseek(mp3.file, l - FRAME_HEADER_SIZE, SEEK_CUR);
283 }
284 if (k == MIN_CONSEC_GOOD_FRAMES) {
285 fseek(mp3.file, valid_start, SEEK_SET);
286 memcpy(&(mp3.header), &h2, sizeof(struct mp3header));
287 return first_len;
288 }
289 }
290 }
291
292 static int mp3_get_id3(void)
293 {
294 char fbuf[4];
295
296 mp3.id3_isvalid = 0;
297 mp3.id3.title[0] = '\0';
298 mp3.id3.artist[0] = '\0';
299 mp3.id3.album[0] = '\0';
300 mp3.id3.comment[0] = '\0';
301 mp3.id3.year[0] = '\0';
302 if (fseek(mp3.file, -128, SEEK_END))
303 return -E_FSEEK;
304 if (para_fread(fbuf, 1, 3, mp3.file) < 0)
305 return -E_FREAD;
306 fbuf[3] = '\0';
307 if (strcmp("TAG", fbuf)) {
308 PARA_INFO_LOG("%s", "no id3 tag\n");
309 return 0;
310 }
311 if (fseek(mp3.file, -125, SEEK_END) < 0)
312 return -E_FSEEK;
313 if (para_fread(mp3.id3.title, 1, 30, mp3.file) != 30)
314 return -E_FREAD;
315 mp3.id3.title[30] = '\0';
316 if (para_fread(mp3.id3.artist, 1, 30, mp3.file) != 30)
317 return -E_FREAD;
318 mp3.id3.artist[30] = '\0';
319 if (para_fread(mp3.id3.album, 1, 30, mp3.file) != 30)
320 return -E_FREAD;
321 mp3.id3.album[30] = '\0';
322 if (para_fread(mp3.id3.year, 1, 4, mp3.file) != 4)
323 return -E_FREAD;
324 mp3.id3.year[4] = '\0';
325 if (para_fread(mp3.id3.comment, 1, 30, mp3.file) != 30)
326 return -E_FREAD;
327 mp3.id3.comment[30] = '\0';
328 mp3.id3_isvalid = 1;
329 unpad(mp3.id3.title);
330 unpad(mp3.id3.artist);
331 unpad(mp3.id3.album);
332 unpad(mp3.id3.year);
333 unpad(mp3.id3.comment);
334 return 1;
335 }
336
337 static int find_valid_start(void)
338 {
339 int frame_len;
340
341 if (!mp3.file)
342 return -E_MP3_NO_FILE;
343 frame_len = get_header(mp3.file, &mp3.header);
344 if (frame_len < 0)
345 return frame_len;
346 if (!frame_len) {
347 frame_len = mp3_seek_next_header();
348 if (frame_len <= 0)
349 return frame_len;
350 } else
351 if (fseek(mp3.file, -FRAME_HEADER_SIZE, SEEK_CUR) < 0)
352 return -E_FSEEK;
353 if (frame_len <= 1) /* FRAME_HEADER_SIZE? */
354 return -E_FRAME_LENGTH;
355 return frame_len;
356 }
357
358 static int mp3_read_info(void)
359 {
360 long fl_avg = 0, freq_avg = 0, br_avg = 0, fcount = 0;
361 int ret, len = 0, old_br = -1;
362 struct timeval total_time = {0, 0};
363
364 ret = mp3_get_id3();
365 if (ret < 0)
366 return ret;
367 rewind(mp3.file);
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 if (fseek(mp3.file, len, SEEK_CUR) < 0)
375 return -E_FSEEK;
376 len = find_valid_start();
377 if (len <= 0)
378 break;
379 freq = header_frequency(&mp3.header);
380 br = header_bitrate(&mp3.header);
381 fl = frame_length(&mp3.header);
382 if (freq < 0 || br < 0 || fl < 0)
383 continue;
384 tmp.tv_sec = fl;
385 tmp.tv_usec = 0;
386 tv_divide(br * 125, &tmp, &cct);
387 tv_add(&cct, &total_time, &tmp);
388 total_time = tmp;
389 // PARA_DEBUG_LOG("%s: br: %d, freq: %d, fl: %d, cct: %lu\n", __func__, br, freq, fl, cct.tv_usec);
390 fcount++;
391 if (fcount == 1) {
392 freq_avg = freq;
393 br_avg = br;
394 old_br = br;
395 fl_avg = fl;
396 continue;
397 }
398 freq_avg += (freq - freq_avg) / (fcount + 1);
399 fl_avg += (fl - fl_avg) / (fcount + 1);
400 br_avg += (br - br_avg) / (fcount + 1);
401 if (old_br != br)
402 mp3.vbr = 1;
403 old_br = br;
404 }
405 if (!fcount || !freq_avg || !br_avg)
406 return -E_MP3_INFO;
407 mp3.br_average = br_avg;
408 mp3.freq = freq_avg;
409 mp3.frames = fcount;
410 mp3.seconds = (tv2ms(&total_time) + 500) / 1000;
411 tv_divide(fcount, &total_time, &af->chunk_tv);
412 rewind(mp3.file);
413 PARA_DEBUG_LOG("chunk_time: %lu\n", af->chunk_tv.tv_usec);
414 tv_scale(10, &af->chunk_tv, &af->eof_tv);
415 return 1;
416 }
417
418 /*
419 * Read mp3 information from audio file
420 */
421 static int mp3_get_file_info(FILE *audio_file, char *info_str,
422 long unsigned *frames, int *seconds)
423 {
424 int ret;
425
426 if (!audio_file)
427 return -E_MP3_NO_FILE;
428 mp3.file = audio_file;
429 ret = mp3_read_info();
430 if (ret < 0) {
431 mp3.file = NULL;
432 return ret;
433 }
434 write_info_str(info_str);
435 *frames = mp3.frames;
436 *seconds = mp3.seconds;
437 if (*seconds < 2 || !*frames)
438 return -E_MP3_INFO;
439 return 1;
440 }
441
442 static int mp3_reposition_stream(long unsigned new_frame)
443 {
444 int count = 0, len;
445
446 PARA_DEBUG_LOG("jmp to frame %lu/%i\n", new_frame, mp3.frames);
447 rewind(mp3.file);
448 while (count < new_frame && (len = find_valid_start()) > 0) {
449 // PARA_DEBUG_LOG("%s: jmp to frame %d\n", __func__, count);
450 if (fseek(mp3.file, len, SEEK_CUR) < 0)
451 return -E_FSEEK;
452 count++;
453 }
454 if (count != new_frame) {
455 rewind(mp3.file);
456 return -E_MP3_REPOS;
457 }
458 return 1;
459 }
460
461 static int mp3_read_next_chunk(void)
462 {
463 int len = find_valid_start();
464
465 if (len <= 0) {
466 if (len < 0)
467 PARA_ERROR_LOG("invalid frame len (%d)\n", len);
468 return len;
469 }
470 chunk_size = para_fread(mp3buf, len, 1, mp3.file);
471 if (len != chunk_size)
472 PARA_DEBUG_LOG("short read (%d/%d)\n", chunk_size, len);
473 return chunk_size;
474 }
475
476 static char *mp3_read_chunk(__unused long unsigned chunk_num, ssize_t *len)
477 {
478 *len = mp3_read_next_chunk();
479 if (*len <= 0)
480 return NULL;
481 return mp3buf;
482 }
483
484 static void mp3_close_audio_file(void)
485 {
486 if (!mp3.file)
487 return;
488 fclose(mp3.file);
489 mp3.file = NULL;
490 }
491
492 void mp3_init(void *p)
493 {
494 af = p;
495 af->get_file_info = mp3_get_file_info;
496 af->reposition_stream = mp3_reposition_stream;
497 af->read_chunk = mp3_read_chunk;
498 af->close_audio_file = mp3_close_audio_file;
499 af->get_header_info = NULL;
500 /* eof_tv gets overwritten in mp3_get_file_info() */
501 af->eof_tv.tv_sec = 0;
502 af->eof_tv.tv_usec = 100 * 1000;
503 }