Make all commands print git version and improve version string.
[paraslash.git] / mp3_afh.c
1 /*
2  * Copyright (C) 2003-2013 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 <regex.h>
20
21 #include "para.h"
22 #include "error.h"
23 #include "afh.h"
24 #include "string.h"
25
26 /*
27  * MIN_CONSEC_GOOD_FRAMES defines how many consecutive valid MP3 frames we need
28  * to see before we decide we are looking at a real MP3 file
29  */
30 #define MIN_CONSEC_GOOD_FRAMES 4
31 #define FRAME_HEADER_SIZE 4
32 #define MIN_FRAME_SIZE 21
33
34 struct mp3header {
35         unsigned long sync;
36         unsigned int version;
37         unsigned int layer;
38         unsigned int crc;
39         unsigned int bitrate;
40         unsigned int freq;
41         unsigned int padding;
42         unsigned int mode;
43         unsigned int copyright;
44         unsigned int original;
45         unsigned int emphasis;
46 };
47
48 static const int frequencies[3][4] = {
49         {22050,24000,16000,50000}, /* MPEG 2.0 */
50         {44100,48000,32000,50000}, /* MPEG 1.0 */
51         {11025,12000,8000,50000} /* MPEG 2.5 */
52 };
53
54 static const int mp3info_bitrate[2][3][14] = {
55 { /* MPEG 2.0 */
56         {32,48,56,64,80,96,112,128,144,160,176,192,224,256}, /* layer 1 */
57         {8,16,24,32,40,48,56,64,80,96,112,128,144,160}, /* layer 2 */
58         {8,16,24,32,40,48,56,64,80,96,112,128,144,160} /* layer 3 */
59 },
60
61 { /* MPEG 1.0 */
62         {32,64,96,128,160,192,224,256,288,320,352,384,416,448}, /* layer 1 */
63         {32,48,56,64,80,96,112,128,160,192,224,256,320,384}, /* layer 2 */
64         {32,40,48,56,64,80,96,112,128,160,192,224,256,320} /* layer 3 */
65 }
66 };
67
68 static const int frame_size_index[] = {24000, 72000, 72000};
69 static const char *mode_text[] = {"stereo", "joint stereo", "dual channel", "mono", "invalid"};
70
71 #ifdef HAVE_LIBID3TAG
72
73 #include <id3tag.h>
74
75 static char *get_utf8(id3_ucs4_t const *string)
76 {
77         if (!string)
78                 return NULL;
79         return (char *)id3_ucs4_utf8duplicate(string);
80 }
81
82 static char *get_stringlist(union id3_field *field)
83 {
84         unsigned int k, nstrings = id3_field_getnstrings(field);
85         char *result = NULL;
86
87         for (k = 0; k < nstrings; k++) {
88                 char *tmp = (char *)get_utf8(id3_field_getstrings(field, k));
89                 if (result) {
90                         char *tmp2 = result;
91                         result = make_message("%s %s", tmp2, tmp);
92                         free(tmp);
93                         free(tmp2);
94                 } else
95                         result = tmp;
96         }
97         return result;
98 }
99
100 static char *get_string(union id3_field *field)
101 {
102         id3_ucs4_t const *string = id3_field_getfullstring(field);
103
104         return get_utf8(string);
105 }
106
107 #define FOR_EACH_FIELD(f, j, fr) for (j = 0; j < (fr)->nfields && \
108         (f = id3_frame_field((fr), j)); j++)
109
110 static char *get_strings(struct id3_frame *fr)
111 {
112         int j;
113         union id3_field *field;
114
115         FOR_EACH_FIELD(field, j, fr) {
116                 enum id3_field_type type = id3_field_type(field);
117
118                 if (type == ID3_FIELD_TYPE_STRINGLIST)
119                         return get_stringlist(field);
120                 if (type == ID3_FIELD_TYPE_STRINGFULL)
121                         return get_string(field);
122         }
123         return NULL;
124 }
125
126 static void mp3_get_id3(__a_unused unsigned char *map,
127                 __a_unused size_t numbytes, int fd, struct taginfo *tags)
128 {
129         int i;
130         struct id3_tag *id3_t;
131         struct id3_file *id3_f = id3_file_fdopen(fd, ID3_FILE_MODE_READONLY);
132
133         if (!id3_f)
134                 return;
135         id3_t = id3_file_tag(id3_f);
136         if (!id3_t) {
137                 id3_file_close(id3_f);
138                 return;
139         }
140         for (i = 0; i < id3_t->nframes; i++) {
141                 struct id3_frame *fr = id3_t->frames[i];
142                 if (!strcmp(fr->id, "TIT2")) {
143                         if (!tags->title)
144                                 tags->title = get_strings(fr);
145                         continue;
146                 }
147                 if (!strcmp(fr->id, "TPE1")) {
148                         if (!tags->artist)
149                                 tags->artist = get_strings(fr);
150                         continue;
151                 }
152                 if (!strcmp(fr->id, "TALB")) {
153                         if (!tags->album)
154                                 tags->album = get_strings(fr);
155                         continue;
156                 }
157                 if (!strcmp(fr->id, "TDRC")) {
158                         if (!tags->year)
159                                 tags->year = get_strings(fr);
160                         continue;
161                 }
162                 if (!strcmp(fr->id, "COMM")) {
163                         if (!tags->comment)
164                                 tags->comment = get_strings(fr);
165                         continue;
166                 }
167         }
168         id3_file_close(id3_f);
169 }
170
171 #else /* HAVE_LIBID3TAG */
172
173 /*
174  * Remove trailing whitespace from the end of a string
175  */
176 static char *unpad(char *string)
177 {
178         char *pos = string + strlen(string) - 1;
179         while (para_isspace(pos[0]))
180                 (pos--)[0] = 0;
181         return string;
182 }
183
184 static void mp3_get_id3(unsigned char *map, size_t numbytes, __a_unused int fd,
185         struct taginfo *tags)
186 {
187         char title[31], artist[31], album[31], year[5], comment[31];
188         off_t fpos;
189
190         if (numbytes < 128 || strncmp("TAG", (char *)map + numbytes - 128, 3)) {
191                 PARA_DEBUG_LOG("no id3 v1 tag\n");
192                 return;
193         }
194         fpos = numbytes - 125;
195         memcpy(title, map + fpos, 30);
196         fpos += 30;
197         title[30] = '\0';
198         memcpy(artist, map + fpos, 30);
199         fpos += 30;
200         artist[30] = '\0';
201         memcpy(album, map + fpos, 30);
202         fpos += 30;
203         album[30] = '\0';
204         memcpy(year, map + fpos, 4);
205         fpos += 4;
206         year[4] = '\0';
207         memcpy(comment, map + fpos, 30);
208         comment[30] = '\0';
209         unpad(title);
210         unpad(artist);
211         unpad(album);
212         unpad(year);
213         unpad(comment);
214         tags->artist = para_strdup(artist);
215         tags->title = para_strdup(title);
216         tags->year = para_strdup(year);
217         tags->album = para_strdup(album);
218         tags->comment = para_strdup(comment);
219 }
220 #endif /* HAVE_LIBID3TAG */
221
222 static int header_frequency(struct mp3header *h)
223 {
224         if (h->version > 2 || h->freq > 3)
225                 return -E_HEADER_FREQ;
226         return frequencies[h->version][h->freq];
227 }
228
229 static const char *header_mode(struct mp3header *h)
230 {
231         if (h->mode > 4)
232                 h->mode = 4; /* invalid */
233         return mode_text[h->mode];
234 }
235
236 static int header_channels(struct mp3header *h)
237 {
238         if (h->mode > 3)
239                 return 0;
240         if (h->mode < 3)
241                 return 2;
242         return 1;
243 }
244
245 static int header_bitrate(struct mp3header *h)
246 {
247         if (!h->layer || h->layer > 3 || h->bitrate > 14 || !h->bitrate)
248                 return -E_HEADER_BITRATE;
249         return mp3info_bitrate[h->version & 1][3 - h->layer][h->bitrate - 1];
250 }
251
252 static int frame_length(struct mp3header *header)
253 {
254         int hb, hf = header_frequency(header);
255
256         if (hf < 0)
257                 return hf;
258         hb = header_bitrate(header);
259         if (hb < 0)
260                 return hb;
261         if (header->sync != 0xFFE || header->layer > 3)
262                 return -E_FRAME;
263         return frame_size_index[3 - header->layer] *
264                 ((header->version & 1) + 1) * hb / hf
265                 + header->padding;
266 }
267
268 static int compare_headers(struct mp3header *h1,struct mp3header *h2)
269 {
270         if ((*(unsigned int*)h1) == (*(unsigned int*)h2))
271                 return 1;
272         if ((h1->version == h2->version) &&
273                         (h1->layer == h2->layer) &&
274                         (h1->crc == h2->crc) &&
275                         (h1->freq == h2->freq) &&
276                         (h1->mode == h2->mode) &&
277                         (h1->copyright == h2->copyright) &&
278                         (h1->original == h2->original) &&
279                         (h1->emphasis == h2->emphasis))
280                 return 1;
281         return 0;
282 }
283
284 /*
285  * get next MP3 frame header.
286  *
287  * On success, the header frame length is returned and the given header
288  * structure that is filled in.  A return value of zero means that we did not
289  * retrieve a valid frame header, and a negative return value indicates an
290  * error.
291  */
292 static int get_header(unsigned char *map, size_t numbytes, off_t *fpos,
293         struct mp3header *header)
294 {
295         int fl, ret;
296
297         if (*fpos + FRAME_HEADER_SIZE > numbytes) {
298                 *fpos = numbytes - 1;
299                 header->sync = 0;
300                 return 0;
301         }
302         header->layer = (map[*fpos + 1] >> 1) & 3;
303         header->sync = (((int)map[*fpos]<<4) | ((int)(map[*fpos + 1]&0xE0)>>4));
304         if (map[*fpos + 1] & 0x10)
305                 header->version = (map[*fpos + 1] >> 3) & 1;
306         else
307                 header->version = 2;
308         if ((header->sync != 0xFFE) || (header->layer != 1)) {
309                 ret = 0;
310                 header->sync = 0;
311                 goto out;
312         }
313         header->crc = map[*fpos + 1] & 1;
314         header->bitrate = (map[*fpos + 2] >> 4) & 0x0F;
315         header->freq = (map[*fpos + 2] >> 2) & 0x3;
316         header->padding = (map[*fpos + 2] >>1) & 0x1;
317         header->mode = (map[*fpos + 3] >> 6) & 0x3;
318         fl = frame_length(header);
319         ret = (fl >= MIN_FRAME_SIZE)? fl : -E_FRAME_LENGTH;
320 out:
321         *fpos += FRAME_HEADER_SIZE;
322         return ret;
323 }
324
325 /*
326  * find the next mp3 header
327  *
328  * Return the length of the next frame header or zero if the end of the file is
329  * reached.
330  */
331 static int mp3_seek_next_header(unsigned char *map, size_t numbytes, off_t *fpos,
332         struct mp3header *result)
333 {
334         int k, l = 0, first_len;
335         struct mp3header h, h2;
336         long valid_start = 0;
337
338         for (; *fpos < numbytes; (*fpos)++) {
339                 if (map[*fpos] != 0xff)
340                         continue;
341                 valid_start = *fpos;
342                 first_len = get_header(map, numbytes, fpos, &h);
343                 if (first_len <= 0)
344                         continue;
345                 *fpos += first_len - FRAME_HEADER_SIZE;
346                 for (k = 1; k < MIN_CONSEC_GOOD_FRAMES; k++) {
347                         if ((l = get_header(map, numbytes, fpos, &h2)) <= 0)
348                                 break;
349                         if (!compare_headers(&h, &h2))
350                                 break;
351                         *fpos += l - FRAME_HEADER_SIZE;
352                 }
353                 if (k == MIN_CONSEC_GOOD_FRAMES) {
354                         *fpos = valid_start;
355                         *result = h2;
356                         return first_len;
357                 }
358         }
359         return 0;
360 }
361
362 static int find_valid_start(unsigned char *map, size_t numbytes, off_t *fpos,
363         struct mp3header *header)
364 {
365         int frame_len;
366
367         frame_len = get_header(map, numbytes, fpos, header);
368         if (frame_len < 0)
369                 return frame_len;
370         if (!frame_len) {
371                 frame_len = mp3_seek_next_header(map, numbytes, fpos, header);
372                 if (frame_len <= 0)
373                         return frame_len;
374         } else
375                 *fpos -= FRAME_HEADER_SIZE;
376         if (frame_len <= 1)
377                 return -E_FRAME_LENGTH;
378         return frame_len;
379 }
380
381 static int mp3_read_info(unsigned char *map, size_t numbytes, int fd,
382                 struct afh_info *afhi)
383 {
384         uint64_t freq_sum = 0, br_sum = 0;
385         int fl = 0, ret, len = 0, old_br = -1, vbr = 0;
386         struct timeval total_time = {0, 0};
387         unsigned chunk_table_size = 1000; /* gets increased on demand */
388         off_t fpos = 0;
389         struct mp3header header;
390
391         afhi->chunks_total = 0;
392         afhi->chunk_table = para_malloc(chunk_table_size * sizeof(uint32_t));
393         while (1) {
394                 int freq, br;
395                 struct timeval tmp, cct; /* current chunk time */
396                 fpos += len;
397                 len = find_valid_start(map, numbytes, &fpos, &header);
398                 if (len <= 0) {
399                         size_t end;
400                         ret = -E_MP3_INFO;
401                         if (!afhi->chunks_total)
402                                 goto err_out;
403                         end = afhi->chunk_table[afhi->chunks_total - 1] + fl;
404                         afhi->chunk_table[afhi->chunks_total]
405                                 = PARA_MIN(end, numbytes);
406                         break;
407                 }
408                 ret = header_frequency(&header);
409                 if (ret < 0)
410                         continue;
411                 freq = ret;
412                 ret = header_bitrate(&header);
413                 if (ret < 0)
414                         continue;
415                 br = ret;
416                 ret = frame_length(&header);
417                 if (ret < 0)
418                         continue;
419                 fl = ret;
420                 tmp.tv_sec = fl - header.padding;
421                 tmp.tv_usec = 0;
422                 tv_divide(br * 125, &tmp, &cct);
423                 tv_add(&cct, &total_time, &tmp);
424                 total_time = tmp;
425                 if (afhi->chunks_total >= chunk_table_size) {
426                         chunk_table_size *= 2;
427                         afhi->chunk_table = para_realloc(afhi->chunk_table,
428                                 chunk_table_size * sizeof(uint32_t));
429                 }
430                 afhi->chunk_table[afhi->chunks_total] = fpos;
431                 afhi->chunks_total++;
432                 freq_sum += freq;
433                 br_sum += br;
434                 if (afhi->chunks_total != 1 && old_br != br)
435                         vbr = 1;
436                 old_br = br;
437         }
438         ret = -E_MP3_INFO;
439         if (!freq_sum || !br_sum)
440                 goto err_out;
441         afhi->bitrate = br_sum / afhi->chunks_total;
442         afhi->frequency = freq_sum / afhi->chunks_total;
443         afhi->channels = header_channels(&header);
444         afhi->seconds_total = (tv2ms(&total_time) + 500) / 1000;
445         tv_divide(afhi->chunks_total, &total_time, &afhi->chunk_tv);
446         PARA_DEBUG_LOG("%lu chunks, each %lums\n", afhi->chunks_total,
447                 tv2ms(&afhi->chunk_tv));
448         afhi->techinfo = make_message("%cbr, %s", vbr? 'v' : 'c',
449                 header_mode(&header));
450         mp3_get_id3(map, numbytes, fd, &afhi->tags);
451         return 1;
452 err_out:
453         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
454         free(afhi->chunk_table);
455         return ret;
456 }
457
458 /*
459  * Read mp3 information from audio file
460  */
461 static int mp3_get_file_info(char *map, size_t numbytes, int fd,
462                 struct afh_info *afhi)
463 {
464         int ret;
465
466         ret = mp3_read_info((unsigned char *)map, numbytes, fd, afhi);
467         if (ret < 0)
468                 return ret;
469         if (afhi->seconds_total < 2 || !afhi->chunks_total)
470                 return -E_MP3_INFO;
471         return 1;
472 }
473
474 static const char* mp3_suffixes[] = {"mp3", NULL};
475
476 /**
477  * the init function of the mp3 audio format handler
478  *
479  * \param afh pointer to the struct to initialize
480  */
481 void mp3_init(struct audio_format_handler *afh)
482 {
483         afh->get_file_info = mp3_get_file_info;
484         afh->suffixes = mp3_suffixes;
485 }