comparison src/madplug/decoder.c @ 610:862190d39e00 trunk

[svn] - add madplug. It is not yet hooked up, I'll do that later.
author nenolod
date Mon, 05 Feb 2007 12:28:01 -0800
parents
children 3f7a52adfe0e
comparison
equal deleted inserted replaced
609:9b73eb35f4ff 610:862190d39e00
1 /*
2 * mad plugin for audacious
3 * Copyright (C) 2005-2007 William Pitcock, Yoshiki Yazawa
4 *
5 * Portions derived from xmms-mad:
6 * Copyright (C) 2001-2002 Sam Clegg - See COPYING
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; under version 2 of the License.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22 #include <math.h>
23 #include <assert.h>
24 #include <pthread.h>
25 #include <signal.h>
26
27 #include <audacious/plugin.h>
28 #include <audacious/output.h>
29 #include <audacious/util.h>
30 #include "plugin.h"
31 #include "input.h"
32
33 #define BUFFER_SIZE 16*1024
34 #define N_AVERAGE_FRAMES 10
35
36 extern long triangular_dither_noise(int nbits);
37
38 /**
39 * Scale PCM data
40 */
41 static inline signed int
42 scale(mad_fixed_t sample, struct mad_info_t *file_info)
43 {
44 /* replayGain by SamKR */
45 gdouble scale = -1;
46 if (audmad_config.replaygain.enable) {
47 if (file_info->has_replaygain) {
48 scale = file_info->replaygain_track_scale;
49 if (file_info->replaygain_album_scale != -1
50 && (scale == -1 || !audmad_config.replaygain.track_mode))
51 {
52 scale = file_info->replaygain_album_scale;
53 }
54 }
55 if (scale == -1)
56 scale = audmad_config.replaygain.default_scale;
57 }
58 if (scale == -1)
59 scale = 1.0;
60 if (audmad_config.pregain_scale != 1)
61 scale = scale * audmad_config.pregain_scale;
62
63 /* hard-limit (clipping-prevention) */
64 if (audmad_config.hard_limit) {
65 /* convert to double before computation, to avoid mad_fixed_t wrapping */
66 double x = mad_f_todouble(sample) * scale;
67 static const double k = 0.5; // -6dBFS
68 if (x > k) {
69 x = tanh((x - k) / (1 - k)) * (1 - k) + k;
70 }
71 else if (x < -k) {
72 x = tanh((x + k) / (1 - k)) * (1 - k) - k;
73 }
74 sample = x * (MAD_F_ONE);
75 }
76 else
77 sample *= scale;
78
79 int n_bits_to_loose = MAD_F_FRACBITS + 1 - 16;
80
81 /* round */
82 /* add half of the bits_to_loose range to round */
83 sample += (1L << (n_bits_to_loose - 1));
84
85 #ifdef DEBUG_DITHER
86 mad_fixed_t no_dither = sample;
87 #endif
88
89 /* dither one bit of actual output */
90 if (audmad_config.dither) {
91 int dither = triangular_dither_noise(n_bits_to_loose + 1);
92 sample += dither;
93 }
94
95 /* clip */
96 /* make sure we are between -1 and 1 */
97 if (sample >= MAD_F_ONE) {
98 sample = MAD_F_ONE - 1;
99 }
100 else if (sample < -MAD_F_ONE) {
101 sample = -MAD_F_ONE;
102 }
103
104 /* quantize */
105 /*
106 * Turn our mad_fixed_t into an integer.
107 * Shift all but 16-bits of the fractional part
108 * off the right hand side and shift an extra place
109 * to get the sign bit.
110 */
111 sample >>= n_bits_to_loose;
112 #ifdef DEBUG_DITHER
113 static int n_zeros = 0;
114 no_dither >>= n_bits_to_loose;
115 if (no_dither - sample == 0)
116 n_zeros++;
117 else {
118 g_message("dither: %d %d", n_zeros, no_dither - sample);
119 n_zeros = 0;
120 }
121 #endif
122 return sample;
123 }
124
125 void
126 write_output(struct mad_info_t *info, struct mad_pcm *pcm,
127 struct mad_header *header)
128 {
129 unsigned int nsamples;
130 mad_fixed_t const *left_ch, *right_ch;
131 char *output;
132 int olen = 0;
133 int pos = 0;
134
135 nsamples = pcm->length;
136 left_ch = pcm->samples[0];
137 right_ch = pcm->samples[1];
138 olen = nsamples * MAD_NCHANNELS(header) * 2;
139 output = (char *) g_malloc(olen * sizeof(char));
140
141 while (nsamples--) {
142 signed int sample;
143 /* output sample(s) in 16-bit signed little-endian PCM */
144 sample = scale(*left_ch++, info);
145 output[pos++] = (sample >> 0) & 0xff;
146 output[pos++] = (sample >> 8) & 0xff;
147
148 if (MAD_NCHANNELS(header) == 2) {
149 sample = scale(*right_ch++, info);
150 output[pos++] = (sample >> 0) & 0xff;
151 output[pos++] = (sample >> 8) & 0xff;
152 }
153 }
154 assert(pos == olen);
155 if (info->playback->playing == 0)
156 return;
157 produce_audio(mad_plugin->output->written_time(),
158 FMT_S16_LE, MAD_NCHANNELS(header), olen, output, NULL);
159 if (info->playback->playing == 0)
160 return;
161 g_free(output);
162 }
163
164 /**
165 * Decode all headers in the file and fill in stats
166 * @return FALSE if scan failed.
167 */
168 gboolean scan_file(struct mad_info_t * info, gboolean fast)
169 {
170 struct mad_stream stream;
171 struct mad_header header;
172 int remainder = 0;
173 int data_used = 0;
174 int len = 0;
175 int tagsize = 0;
176 unsigned char buffer[BUFFER_SIZE];
177 struct mad_frame frame; /* to read xing data */
178 gboolean has_xing = FALSE;
179
180 mad_stream_init(&stream);
181 mad_header_init(&header);
182 mad_frame_init(&frame);
183 xing_init(&info->xing);
184
185 info->bitrate = 0;
186 info->pos = mad_timer_zero;
187
188 #ifdef DEBUG
189 g_message("f: scan_file");
190 #endif /* DEBUG */
191
192 while (1) {
193 remainder = stream.bufend - stream.next_frame;
194
195 /*
196 if (remainder >= BUFFER_SIZE)
197 {
198 printf("oh dear.. remainder = %d\n", remainder);
199 }
200 */
201
202 memcpy(buffer, stream.this_frame, remainder);
203 len = input_get_data(info, buffer + remainder,
204 BUFFER_SIZE - remainder);
205
206 if (len <= 0)
207 break;
208
209 mad_stream_buffer(&stream, buffer, len + remainder);
210
211 while (1) {
212 if (mad_header_decode(&header, &stream) == -1) {
213 if (stream.error == MAD_ERROR_BUFLEN) {
214 break;
215 }
216 if (!MAD_RECOVERABLE(stream.error)) {
217 #ifdef DEBUG
218 g_message("(fatal) error decoding header %d: %s",
219 info->frames, mad_stream_errorstr(&stream));
220 g_message("remainder = %d", remainder);
221 g_message("len = %d", len);
222 #endif /* DEBUG */
223 break;
224 }
225 if (stream.error == MAD_ERROR_LOSTSYNC) {
226 /* ignore LOSTSYNC due to ID3 tags */
227 tagsize = id3_tag_query(stream.this_frame,
228 stream.bufend -
229 stream.this_frame);
230 if (tagsize > 0) {
231 #ifdef DEBUG
232 g_message("skipping id3_tag: %d", tagsize);
233 #endif /* DEBUG */
234 mad_stream_skip(&stream, tagsize);
235 continue;
236 }
237 }
238 #ifdef DEBUG
239 g_message("(recovered) error decoding header %d: %s",
240 info->frames, mad_stream_errorstr(&stream));
241 g_message("remainder = %d", remainder);
242 g_message("len = %d", len);
243 #endif /* DEBUG */
244 continue;
245 }
246 info->frames++;
247 #ifdef DEBUG
248 g_message("duration = %lu",
249 mad_timer_count(header.duration,
250 MAD_UNITS_MILLISECONDS));
251 g_message("size = %d", stream.next_frame - stream.this_frame);
252 #endif
253 mad_timer_add(&info->duration, header.duration);
254 data_used += stream.next_frame - stream.this_frame;
255 if (info->frames == 1) {
256 /* most of these *should* remain constant */
257 info->bitrate = header.bitrate;
258 info->freq = header.samplerate;
259 info->channels = MAD_NCHANNELS(&header);
260 info->mpeg_layer = header.layer;
261 info->mode = header.mode;
262
263 if (audmad_config.use_xing) {
264 frame.header = header;
265 if (mad_frame_decode(&frame, &stream) == -1)
266 break;
267 if (xing_parse
268 (&info->xing, stream.anc_ptr,
269 stream.anc_bitlen) == 0) {
270 #ifdef DEBUG
271 g_message("found xing header");
272 #endif /* DEBUG */
273 has_xing = TRUE;
274 info->vbr = TRUE; /* otherwise xing header would have been 'Info' */
275 info->frames = info->xing.frames;
276 mad_timer_multiply(&info->duration, info->frames);
277 info->bitrate =
278 8.0 * info->xing.bytes /
279 mad_timer_count(info->duration,
280 MAD_UNITS_SECONDS);
281 break;
282 }
283 }
284
285 }
286 else {
287 /* perhaps we have a VRB file */
288 if (info->bitrate != header.bitrate)
289 info->vbr = TRUE;
290 if (info->vbr)
291 info->bitrate += header.bitrate;
292 /* check for changin layer/samplerate/channels */
293 if (info->mpeg_layer != header.layer)
294 g_warning("layer varies!!");
295 if (info->freq != header.samplerate)
296 g_warning("samplerate varies!!");
297 if (info->channels != MAD_NCHANNELS(&header))
298 g_warning("number of channels varies!!");
299 }
300
301 if (fast && info->frames >= N_AVERAGE_FRAMES) {
302 float frame_size = ((double) data_used) / N_AVERAGE_FRAMES;
303 info->frames = (info->size - tagsize) / frame_size;
304 //int frame_frac = (info->size - tagsize) % frame_size;
305 info->duration.seconds /= N_AVERAGE_FRAMES;
306 info->duration.fraction /= N_AVERAGE_FRAMES;
307 mad_timer_multiply(&info->duration, info->frames);
308 #ifdef DEBUG
309 g_message("using fast playtime calculation");
310 g_message("data used = %d [tagsize=%d framesize=%f]",
311 data_used, tagsize, frame_size);
312 //g_message ("frame_size = %f [frac=%d]", frame_size, frame_frac);
313 g_message("frames = %d, frequecy = %d, channels = %d",
314 info->frames, info->freq, info->channels);
315 long millis = mad_timer_count(info->duration,
316 MAD_UNITS_MILLISECONDS);
317 g_message("duration = %lu:%lu", millis / 1000 / 60,
318 (millis / 1000) % 60);
319 #endif /* DEBUG */
320 break;
321 }
322 }
323 if (stream.error != MAD_ERROR_BUFLEN)
324 break;
325 }
326
327 if (info->vbr && !has_xing)
328 info->bitrate = info->bitrate / info->frames;
329
330 mad_frame_finish(&frame);
331 mad_header_finish(&header);
332 mad_stream_finish(&stream);
333 xing_finish(&info->xing);
334
335 #ifdef DEBUG
336 g_message("e: scan_file");
337 #endif /* DEBUG */
338 return (info->frames != 0 || info->remote == TRUE);
339 }
340
341 gpointer decode_loop(gpointer arg)
342 {
343 unsigned char buffer[BUFFER_SIZE];
344 int len;
345 int seek_skip = 0;
346 int remainder = 0;
347 gint tlen;
348
349 /* mad structs */
350 struct mad_stream stream;
351 struct mad_frame frame;
352 struct mad_synth synth;
353
354 /* track info is passed in as thread argument */
355 struct mad_info_t *info = (struct mad_info_t *) arg;
356
357 #ifdef DEBUG
358 g_message("f: decode");
359 #endif /* DEBUG */
360
361 /* init mad stuff */
362 mad_frame_init(&frame);
363 mad_stream_init(&stream);
364 mad_synth_init(&synth);
365
366 if (!mad_plugin->output->
367 open_audio(info->fmt, info->freq, info->channels)) {
368 audmad_error("failed to open audio output: %s",
369 mad_plugin->output->description);
370 g_message("failed to open audio output: %s",
371 mad_plugin->output->description);
372 return NULL;
373 }
374
375 /* set mainwin title */
376 if (info->title)
377 g_free(info->title);
378 info->title =
379 xmms_get_titlestring(xmms_get_gentitle_format(), info->tuple);
380
381 tlen = (gint) mad_timer_count(info->duration, MAD_UNITS_MILLISECONDS),
382
383 mad_plugin->set_info(info->title,
384 tlen == 0 ? -1 : tlen,
385 info->bitrate, info->freq, info->channels);
386
387 /* main loop */
388 do {
389 if (info->playback->playing == 0) {
390 #ifdef DEBUG
391 g_message("decode: stop signaled");
392 #endif /* DEBUG */
393 break;
394 }
395 if (seek_skip)
396 remainder = 0;
397 else {
398 remainder = stream.bufend - stream.next_frame;
399 memcpy(buffer, stream.this_frame, remainder);
400 }
401 len = input_get_data(info, buffer + remainder,
402 BUFFER_SIZE - remainder);
403 if (len <= 0) {
404 #ifdef DEBUG
405 g_message("finished decoding");
406 #endif /* DEBUG */
407 break;
408 }
409 len += remainder;
410 if (len < MAD_BUFFER_GUARD) {
411 int i;
412 for (i = len; i < MAD_BUFFER_GUARD; i++)
413 buffer[i] = 0;
414 len = MAD_BUFFER_GUARD;
415 }
416
417 mad_stream_buffer(&stream, buffer, len);
418
419 if (seek_skip) {
420 #ifdef DEBUG
421 g_message("skipping: %d", seek_skip);
422 #endif
423 int skip = 2;
424 do {
425 if (mad_frame_decode(&frame, &stream) == 0) {
426 mad_timer_add(&info->pos, frame.header.duration);
427 if (--skip == 0)
428 mad_synth_frame(&synth, &frame);
429 }
430 else if (!MAD_RECOVERABLE(stream.error))
431 break;
432 }
433 while (skip);
434 seek_skip = 0;
435 }
436
437 while (!info->playback->playing == 0) {
438 if (info->seek != -1 && !info->remote) {
439 #ifdef DEBUG
440 g_message("seeking: %d", info->seek);
441 #endif
442 int new_position;
443 int seconds =
444 mad_timer_count(info->duration, MAD_UNITS_SECONDS);
445 if (info->seek >= seconds)
446 info->seek = seconds;
447
448 mad_timer_set(&info->pos, info->seek, 0, 0);
449 new_position =
450 ((double) info->seek / (double) seconds) * info->size;
451 #ifdef DEBUG
452 g_message("seeking to: %d bytes", new_position);
453 #endif
454 if (vfs_fseek(info->infile, new_position, SEEK_SET) == -1)
455 audmad_error("failed to seek to: %d", new_position);
456 mad_frame_mute(&frame);
457 mad_synth_mute(&synth);
458 stream.error = MAD_ERROR_BUFLEN;
459 mad_plugin->output->flush(mad_timer_count
460 (info->pos,
461 MAD_UNITS_MILLISECONDS));
462 stream.sync = 0;
463 info->seek = -1;
464 seek_skip = 1;
465 break;
466 }
467
468 if (mad_header_decode(&frame.header, &stream) == -1) {
469 if (!MAD_RECOVERABLE(stream.error))
470 break;
471 if (stream.error == MAD_ERROR_LOSTSYNC) {
472 /* ignore LOSTSYNC due to ID3 tags */
473 int tagsize = id3_tag_query(stream.this_frame,
474 stream.bufend -
475 stream.this_frame);
476 if (tagsize > 0) {
477 mad_stream_skip(&stream, tagsize);
478 continue;
479 }
480 }
481 #ifdef DEBUG
482 g_message("(recovered) error decoding header %d: %s",
483 info->current_frame,
484 mad_stream_errorstr(&stream));
485 #endif /* DEBUG */
486 continue;
487 }
488
489 if (mad_frame_decode(&frame, &stream) == -1) {
490 if (!MAD_RECOVERABLE(stream.error))
491 break;
492 #ifdef DEBUG
493 g_message("(recovered) error decoding frame %d: %s",
494 info->current_frame,
495 mad_stream_errorstr(&stream));
496 #endif /* DEBUG */
497 }
498
499 info->current_frame++;
500
501 if (info->freq != frame.header.samplerate
502 || info->channels !=
503 (guint) MAD_NCHANNELS(&frame.header))
504 {
505 tlen = mad_timer_count(info->duration, MAD_UNITS_MILLISECONDS);
506 #ifdef DEBUG
507 g_message("re-opening audio due to change in audio type");
508 g_message("old: frequency = %d, channels = %d", info->freq,
509 info->channels);
510 g_message("new: frequency = %d, channels = %d",
511 frame.header.samplerate,
512 (guint) MAD_NCHANNELS(&frame.header));
513 #endif /* DEBUG */
514
515 info->freq = frame.header.samplerate;
516 info->channels = MAD_NCHANNELS(&frame.header);
517 mad_plugin->output->close_audio();
518 if (!mad_plugin->output->open_audio(info->fmt, info->freq,
519 info->channels)) {
520 audmad_error("failed to re-open audio output: %s",
521 mad_plugin->output->description);
522 }
523
524 mad_plugin->set_info(info->title,
525 tlen != 0 ? tlen : -1,
526 info->bitrate, info->freq, info->channels);
527 }
528 if (info->playback->playing == 0)
529 break;
530 mad_synth_frame(&synth, &frame);
531 mad_stream_sync(&stream);
532 write_output(info, &synth.pcm, &frame.header);
533 mad_timer_add(&info->pos, frame.header.duration);
534 }
535 }
536 while (stream.error == MAD_ERROR_BUFLEN);
537
538 /* free mad stuff */
539 mad_frame_finish(&frame);
540 mad_stream_finish(&stream);
541 mad_synth_finish(&synth);
542
543 if (!info->playback->playing == 0) {
544 mad_plugin->output->buffer_free();
545 mad_plugin->output->buffer_free();
546 while (mad_plugin->output->buffer_playing()) {
547 #ifdef DEBUG
548 g_message("f: buffer_playing=%d",
549 mad_plugin->output->buffer_playing());
550 #endif
551 xmms_usleep(10000);
552 if (info->playback->playing == 0)
553 break;
554 }
555 }
556 #ifdef DEBUG
557 g_message("e: decode");
558 #endif /* DEBUG */
559
560 bmp_title_input_free(info->tuple);
561 info->tuple = NULL;
562
563 mad_plugin->output->close_audio();
564 info->playback->playing = 0;
565 g_thread_exit(0);
566 return NULL; /* dummy */
567 }