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