2 terminatorX - realtime audio scratching software
3 Copyright (C) 1999-2003 Alexander König
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 Description: This implements the new audiofile class. Unlike earlier
22 versions of terminatorX where wav_read.c was evilishly
23 "#ifdef"ed to support multiple loading strategies this new
24 design allows multiple load_*()-methods/strategies at
25 the same time. (e.g. tx can now try to load a wavfile
26 with the builtin routines and if that fails it'll try
27 to load the file through sox (if available)).
31 13 Sept 2002 - Wrote a seperate loading routine to be used with
32 libmad, which is significantly better then piping mpg?1?.
33 Rewrote load_piped to use realloc() instead - much easier,
34 faster and uses less memory - wish I'd known about realloc()
35 when coding load_piped() for the first time ;)
39 #include "tX_audiofile.h"
44 #include "tX_loaddlg.h"
45 #include "tX_endian.h"
49 # include <sys/types.h>
51 # ifndef _POSIX_MAPPED_FILES
52 # define _POSIX_MAPPED_FILES
54 # include <sys/stat.h>
56 # include <sys/mman.h>
59 #ifdef USE_VORBIS_INPUT
60 # include <vorbis/codec.h>
61 # include <vorbis/vorbisfile.h>
63 # include <sys/stat.h>
65 # include <sys/mman.h>
68 #ifdef USE_AUDIOFILE_INPUT
69 # include <audiofile.h>
72 #define min(a,b) ((a) < (b) ? (a) : (b))
74 tx_audiofile :: tx_audiofile()
76 mem_type=TX_AUDIO_UNDEFINED;
77 file_type=TX_FILE_UNDEFINED;
85 void tx_audiofile :: figure_file_type()
89 ext=strrchr(filename, (int) '.');
96 if (!strcasecmp("wav", ext)) file_type=TX_FILE_WAV;
97 else if (!strncasecmp("mp", ext, 2)) file_type=TX_FILE_MPG123;
98 else if (!strncasecmp("ogg", ext, 2)) file_type=TX_FILE_OGG123;
103 tX_audio_error tx_audiofile :: load(char *p_file_name)
105 tX_audio_error load_err=TX_AUDIO_ERR_NOT_SUPPORTED;
107 strcpy(filename, p_file_name);
113 if (mem) { free(mem); mem=NULL; }
115 #ifdef USE_AUDIOFILE_INPUT
116 if ((load_err) && (file_type!=TX_FILE_MPG123) && (file_type!=TX_FILE_OGG123)) {
121 #ifdef USE_BUILTIN_WAV
122 if ((load_err) && (file_type==TX_FILE_WAV)) {
124 // if (load_err==TX_AUDIO_SUCCESS) return(load_err);
129 if ((load_err) && (file_type==TX_FILE_MPG123)) {
131 //if (load_err==TX_AUDIO_SUCCESS) return(load_err);
135 #ifdef USE_MPG123_INPUT
136 if ((load_err) && (file_type==TX_FILE_MPG123)) {
137 load_err=load_mpg123();
142 #ifdef USE_VORBIS_INPUT
143 if ((load_err) && (file_type==TX_FILE_OGG123)) {
144 load_err=load_vorbis();
145 //if (load_err==TX_AUDIO_SUCCESS) return(load_err);
149 #ifdef USE_OGG123_INPUT
150 if ((load_err) && (file_type==TX_FILE_OGG123)) {
151 load_err=load_ogg123();
163 tX_debug("tx_audiofile::load() Set samplerate to %i for file %s.", sample_rate, filename);
168 tx_audiofile :: ~tx_audiofile() {
176 tX_audio_error tx_audiofile :: load_piped()
182 unsigned char buffer[SOX_BLOCKSIZE];
185 /* Irritating the user... */
186 ld_set_progress(0.5);
187 mem_type=TX_AUDIO_LOAD;
190 bytes = fread(buffer, 1, SOX_BLOCKSIZE, file);
195 int16_t *new_data=(int16_t *) realloc(data, allbytes);
196 //printf("All: %i, Bytes: %i, new: %08x, old: %08x\n", allbytes, bytes, new_data, data);
199 pclose(file); file=NULL;
200 if (data) free(data);
202 return TX_AUDIO_ERR_ALLOC;
206 ptr=(unsigned char *) data;
207 memcpy((void *) &ptr[prev_bytes],(void *) buffer, bytes);
211 pclose(file); file=NULL;
214 // If we get here we read zero Bytes...
215 if (data) free(data);
216 return TX_AUDIO_ERR_PIPE_READ;
219 no_samples=allbytes/sizeof(int16_t);
222 /* Irritating the user just a little more ;)*/
223 ld_set_progress(1.0);
225 return TX_AUDIO_SUCCESS;
231 tX_audio_error tx_audiofile :: load_sox() {
232 tX_debug("tx_audiofile::load_sox()");
234 char command[PATH_MAX*2];
236 sprintf(command, SOX_STR, filename);
237 file = popen(command, "r");
239 if (!file) return TX_AUDIO_ERR_SOX;
246 #ifdef USE_MPG123_INPUT
247 tX_audio_error tx_audiofile :: load_mpg123() {
248 tX_debug("tx_audiofile::load_mpg123()");
250 char command[PATH_MAX*2];
252 sprintf(command, MPG123_STR, filename);
253 file = popen(command, "r");
255 if (!file) return TX_AUDIO_ERR_MPG123;
261 #ifdef USE_OGG123_INPUT
262 tX_audio_error tx_audiofile :: load_ogg123() {
263 tX_debug("tx_audiofile::load_ogg123()");
265 char command[PATH_MAX*2];
267 sprintf(command, OGG123_STR, filename);
268 file = popen(command, "r");
270 if (!file) return TX_AUDIO_ERR_OGG123;
276 #ifdef USE_BUILTIN_WAV
277 tX_audio_error tx_audiofile :: load_wav() {
278 tX_debug("tx_audiofile::load_wav()");
286 mem_type=TX_AUDIO_LOAD;
288 if (!init_wav_read(filename, &wav_in))
290 return(TX_AUDIO_ERR_WAV_NOTFOUND);
293 if (wav_in.depth != 16)
295 return(TX_AUDIO_ERR_NOT_16BIT);
298 if (wav_in.chans != 1)
300 return(TX_AUDIO_ERR_NOT_MONO);
303 sample_rate=wav_in.srate;
306 data = (int16_t *) malloc (memsize);
310 return(TX_AUDIO_ERR_ALLOC);
314 #ifdef ENABLE_DEBUG_OUTPUT
317 while (wav_in.len>allbytes)
319 bytes = fread(p, 1, min(1024, wav_in.len-allbytes), wav_in.handle);
321 #ifdef ENABLE_DEBUG_OUTPUT
322 if (output) { tX_debug("tX_audiofile::load_wav() read %i Bytes [%04x %04x %04x %04x %04x %04x ..]", bytes, (unsigned int) p[0], (unsigned int) p[1], (unsigned int) p[2], (unsigned int) p[3], (unsigned int) p[4], (unsigned int) p[5]); }
327 return (TX_AUDIO_ERR_WAV_READ);
330 #ifdef BIG_ENDIAN_MACHINE
331 swapbuffer(p, bytes/sizeof(int16_t));
332 # ifdef ENABLE_DEBUG_OUTPUT
333 if (output) { tX_debug("tX_audiofile::load_wav() swapped %i Bytes [%04x %04x %04x %04x %04x %04x ..]",
334 bytes, (unsigned int) p[0], (unsigned int) p[1], (unsigned int) p[2], (unsigned int) p[3], (unsigned int) p[4], (unsigned int) p[5]); }
338 #ifdef ENABLE_DEBUG_OUTPUT
344 ld_set_progress((float) allbytes/(float)wav_in.len);
346 p+=(ssize_t) bytes/sizeof(int16_t);
349 wav_close(wav_in.handle);
352 no_samples=memsize/sizeof(int16_t);
354 return (TX_AUDIO_SUCCESS);
359 tX_audio_error tx_audiofile::load_mad() {
360 tX_debug("tx_audiofile::load_mad()");
362 struct stat stat_dat;
367 fd=open(filename, O_RDONLY);
368 if (!fd) return TX_AUDIO_ERR_MAD_OPEN;
370 if (fstat(fd, &stat_dat) == -1 ||
371 stat_dat.st_size == 0) {
372 return TX_AUDIO_ERR_MAD_STAT;
375 mp3_file = mmap(0, stat_dat.st_size, PROT_READ, MAP_SHARED, fd, 0);
377 if (mp3_file == MAP_FAILED) {
378 return TX_AUDIO_ERR_MAD_MMAP;
381 res=mad_decode((const unsigned char *) mp3_file, stat_dat.st_size);
384 return TX_AUDIO_ERR_MAD_DECODE;
387 mem_type=TX_AUDIO_LOAD;
389 if (munmap(mp3_file, stat_dat.st_size) == -1) {
390 return TX_AUDIO_ERR_MAD_MUNMAP;
393 return TX_AUDIO_SUCCESS;
396 #define TX_MAD_BLOCKSIZE 8096
399 const unsigned char *start;
400 const unsigned char *end;
401 const unsigned char *last_frame;
404 int16_t *target_buffer;
405 unsigned int target_samples;
406 unsigned int current_sample;
407 unsigned int sample_rate;
408 unsigned int lost_sync_counter;
411 const unsigned char *last_current=NULL;
413 static enum mad_flow tX_mad_input(void *data, struct mad_stream *stream) {
414 tX_mad_buffer *buffer = (tX_mad_buffer *) data;
418 if (buffer->first_call) {
419 bs=min(TX_MAD_BLOCKSIZE, buffer->size);
420 mad_stream_buffer(stream, buffer->start, bs);
421 buffer->first_call=false;
422 return MAD_FLOW_CONTINUE;
424 if (!stream->next_frame) return MAD_FLOW_STOP;
426 pos=stream->next_frame-buffer->start;
427 bs=min(TX_MAD_BLOCKSIZE, buffer->size-pos);
428 //tX_debug("last: %08x, new %08x, bs: %i, pos: %i", buffer->last_frame, stream->next_frame, bs, pos);
430 mad_stream_buffer(stream, stream->next_frame, bs);
431 if (stream->next_frame==buffer->last_frame) {
432 //tX_debug("tX_mad_input(): No new frame? Stopping.");
433 return MAD_FLOW_STOP;
435 ld_set_progress((float) pos/(float) buffer->size);
436 buffer->last_frame=stream->next_frame;
438 return MAD_FLOW_CONTINUE;
442 static enum mad_flow tX_mad_error(void *data, struct mad_stream *stream, struct mad_frame *frame) {
443 tX_mad_buffer *buffer = (tX_mad_buffer *) data;
444 if (MAD_RECOVERABLE(stream->error)) {
445 if ((stream->error==MAD_ERROR_LOSTSYNC) && (buffer->lost_sync_counter<3)) {
446 /* Ignore at least two sync errors to not annoy people
449 buffer->lost_sync_counter++;
450 return MAD_FLOW_CONTINUE;
452 tX_warning("mad reported stream error (%i) '%s'.", stream->error, mad_stream_errorstr(stream));
453 return MAD_FLOW_CONTINUE;
455 tX_error("mad reported fatal stream error (%i) '%s'.", stream->error, mad_stream_errorstr(stream));
456 return MAD_FLOW_STOP;
459 /* From minimad.c of mad */
460 static inline signed int scale(mad_fixed_t sample) {
461 //#ifdef BIG_ENDIAN_MACHINE
462 // swap32_inline(&sample);
465 sample += (1L << (MAD_F_FRACBITS - 16));
468 if (sample >= MAD_F_ONE)
469 sample = MAD_F_ONE - 1;
470 else if (sample < -MAD_F_ONE)
474 return sample >> (MAD_F_FRACBITS + 1 - 16);
477 static enum mad_flow tX_mad_output(void *data, struct mad_header const *header, struct mad_pcm *pcm) {
478 tX_mad_buffer *buffer=(tX_mad_buffer *) data;
479 unsigned int nchannels, nsamples;
480 mad_fixed_t const *left_ch, *right_ch;
482 nchannels = pcm->channels;
483 nsamples = pcm->length;
484 left_ch = pcm->samples[0];
485 right_ch = pcm->samples[1];
486 buffer->sample_rate = pcm->samplerate;
488 buffer->target_samples+=nsamples;
490 buffer->target_buffer=(int16_t *) realloc(buffer->target_buffer, buffer->target_samples<<1);
491 if (!buffer->target_buffer) {
492 tX_error("tX_mad_output(): Failed allocating sample memory!\n");
493 return MAD_FLOW_STOP;
500 sample=scale(*left_ch++);
502 double sample_l=(double) (*left_ch++);
503 double sample_r=(double) (*right_ch++);
504 double res=(sample_l+sample_r)/2.0;
505 mad_fixed_t mad_res=(mad_fixed_t) res;
507 sample=scale(mad_res);
510 buffer->target_buffer[buffer->current_sample]=sample;
511 buffer->current_sample++;
514 return MAD_FLOW_CONTINUE;
517 int tx_audiofile::mad_decode(unsigned char const *start, unsigned long length) {
518 tX_mad_buffer buffer;
519 struct mad_decoder decoder;
522 buffer.start = start;
523 buffer.end = &start[length];
524 buffer.last_frame = NULL;
525 buffer.size = length;
526 buffer.target_buffer = NULL;
527 buffer.target_samples = 0;
528 buffer.current_sample = 0;
529 buffer.first_call=true;
530 buffer.sample_rate=0;
531 buffer.lost_sync_counter=0;
533 tX_debug("tx_audiofile::mad_decode() - start %08x, length %i", (int) buffer.start, buffer.size);
534 /* configure input, output, and error functions */
536 mad_decoder_init(&decoder, &buffer, tX_mad_input, NULL, NULL, tX_mad_output, tX_mad_error, NULL);
537 result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
540 this->mem=buffer.target_buffer;
541 this->no_samples=buffer.target_samples;
543 if (buffer.target_buffer) free(buffer.target_buffer);
546 /* release the decoder */
547 mad_decoder_finish(&decoder);
549 sample_rate=buffer.sample_rate;
555 /* AARG - OGG loading is not threadsafe !*/
556 size_t tX_ogg_file_size;
557 long tX_ogg_file_read;
559 #ifdef USE_VORBIS_INPUT
561 size_t (*read_func) (void *, size_t, size_t, FILE *);
562 int (*seek_func) (void *, long, int);
563 int (*close_func) (FILE *);
564 long (*tell_func) (FILE *);
567 int ogg_seek(void *ptr, long offset, int whence) {
568 /* ogg shall not seek ! */
573 size_t ogg_read(void *ptr, size_t size, size_t nmemb, FILE *stream) {
575 ret_val=fread(ptr, size, nmemb, stream);
577 tX_ogg_file_read+=ret_val*size;
578 ld_set_progress((double) tX_ogg_file_read/(double) tX_ogg_file_size);
583 #define VORBIS_BUFF_SIZE 4096 /*recommended*/
585 tX_audio_error tx_audiofile::load_vorbis() {
586 tX_debug("tx_audiofile::load_vorbis()");
588 /* VORBIS Callbacks */
589 ov_callbacks org_callbacks;
590 /* evil casting - to make g++ shut up */
591 tX_ov_callbacks *callbacks=(tX_ov_callbacks *) &org_callbacks;
594 char pcmout[VORBIS_BUFF_SIZE];
597 int current_section=0;
599 struct stat stat_dat;
601 callbacks->read_func=ogg_read;
602 callbacks->seek_func=ogg_seek;
603 callbacks->close_func=fclose;
604 callbacks->tell_func=ftell;
606 file=fopen(filename, "r");
608 return TX_AUDIO_ERR_WAV_NOTFOUND;
611 if (fstat(fileno(file), &stat_dat) == -1 || stat_dat.st_size == 0) {
612 return TX_AUDIO_ERR_MAD_STAT;
615 tX_ogg_file_size=stat_dat.st_size;
618 int res=ov_open_callbacks((void *) file, &vf, NULL, 0, org_callbacks);
622 return TX_AUDIO_ERR_VORBIS_OPEN;
625 vorbis_info *vi=ov_info(&vf,-1);
626 sample_rate=vi->rate;
628 unsigned int channels=vi->channels;
629 unsigned int samples_read=0;
630 unsigned int mono_samples;
634 while((!eof) && (!current_section)) {
635 #ifdef BIG_ENDIAN_MACHINE
640 long ret=ov_read(&vf,pcmout,VORBIS_BUFF_SIZE,ENDIANP,2,1,¤t_section);
643 } else if (ret < 0) {
644 /* ignore stream errors */
648 new_data=(int16_t *) realloc(data, bytes/channels);
650 if (data) free(data);
651 return TX_AUDIO_ERR_ALLOC;
\r
655 int16_t *src=(int16_t *) &pcmout;
660 for (i=0; i<mono_samples; i++) {
661 data[samples_read+i]=src[i];
667 for (i=0; i<mono_samples; i++) {
668 double l_value, r_value;
671 data[samples_read+i]=(int16_t) ((l_value+r_value)/2.0);
676 mono_samples=(ret/2)/channels;
677 for (i=0; i<mono_samples; i++) {
680 for (unsigned int c=0; c<channels; c++) {
681 value+=(double) src[i*channels+c];
683 value/=(double) channels;
684 data[samples_read+i]=(int16_t) value;
687 samples_read+=mono_samples;
693 mem=(int16_t *) data;
694 no_samples=samples_read;
699 return TX_AUDIO_ERR_VORBIS_NODATA;
702 return TX_AUDIO_SUCCESS;
706 #ifdef USE_AUDIOFILE_INPUT
707 #define TX_AF_SAMPLES_PER_BLOCK 2048
709 tX_audio_error tx_audiofile::load_af() {
710 tX_debug("tx_audiofile::load_af()");
712 AFfilehandle af_file;
713 AFframecount all_frames, frames_read=0, current_frames=1;
716 af_file = afOpenFile(filename, "r", NULL);
717 if (af_file==AF_NULL_FILEHANDLE) {
718 return TX_AUDIO_ERR_AF_OPEN;
721 all_frames=afGetFrameCount(af_file, AF_DEFAULT_TRACK);
722 sample_rate=(unsigned int) afGetRate(af_file, AF_DEFAULT_TRACK);
723 afSetVirtualChannels(af_file, AF_DEFAULT_TRACK, 1);
724 afSetVirtualSampleFormat(af_file, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16); // 2 == 16 Bit?
725 #ifdef BIG_ENDIAN_MACHINE
726 afSetVirtualByteOrder(af_file, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
728 afSetVirtualByteOrder(af_file, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
731 while (current_frames) {
734 new_data=(int16_t*) realloc(data, (frames_read+TX_AF_SAMPLES_PER_BLOCK)*2);
736 if (data) free(data);
737 afCloseFile(af_file);
738 return TX_AUDIO_ERR_ALLOC;
741 current_frames=afReadFrames(af_file,AF_DEFAULT_TRACK,(void *) &data[frames_read],TX_AF_SAMPLES_PER_BLOCK);
742 frames_read+=current_frames;
743 ld_set_progress(((double) frames_read)/((double) all_frames));
745 afCloseFile(af_file);
748 if (data) free(data);
749 return TX_AUDIO_ERR_AF_NODATA;
752 /* shorten to the actually read size of samples */
753 if (!realloc(data, frames_read*2)) {
754 if (data) free(data);
755 return TX_AUDIO_ERR_ALLOC;
759 no_samples=frames_read;
761 return TX_AUDIO_SUCCESS;