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