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