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