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