2 terminatorX - realtime audio scratching software
3 Copyright (C) 1999-2002 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 tx_audiofile :: tx_audiofile()
74 mem_type=TX_AUDIO_UNDEFINED;
75 file_type=TX_FILE_UNDEFINED;
83 void tx_audiofile :: figure_file_type()
87 ext=strrchr(filename, (int) '.');
94 if (!strcasecmp("wav", ext)) file_type=TX_FILE_WAV;
95 else if (!strncasecmp("mp", ext, 2)) file_type=TX_FILE_MPG123;
96 else if (!strncasecmp("ogg", ext, 2)) file_type=TX_FILE_OGG123;
101 tX_audio_error tx_audiofile :: load(char *p_file_name)
103 tX_audio_error load_err=TX_AUDIO_ERR_NOT_SUPPORTED;
105 strcpy(filename, p_file_name);
111 #ifdef USE_AUDIOFILE_INPUT
112 if ((load_err) && (file_type!=TX_FILE_MPG123) && (file_type!=TX_FILE_OGG123)) {
117 #ifdef USE_BUILTIN_WAV
118 if ((load_err) && (file_type==TX_FILE_WAV)) {
120 // if (load_err==TX_AUDIO_SUCCESS) return(load_err);
125 if ((load_err) && (file_type==TX_FILE_MPG123)) {
127 //if (load_err==TX_AUDIO_SUCCESS) return(load_err);
131 #ifdef USE_MPG123_INPUT
132 if ((load_err) && (file_type==TX_FILE_MPG123)) {
133 load_err=load_mpg123();
138 #ifdef USE_VORBIS_INPUT
139 if ((load_err) && (file_type==TX_FILE_OGG123)) {
140 load_err=load_vorbis();
141 //if (load_err==TX_AUDIO_SUCCESS) return(load_err);
145 #ifdef USE_OGG123_INPUT
146 if ((load_err) && (file_type==TX_FILE_OGG123)) {
147 load_err=load_ogg123();
159 tX_debug("tx_audiofile::load() Set samplerate to %i for file %s.", sample_rate, filename);
164 tx_audiofile :: ~tx_audiofile() {
166 case TX_AUDIO_MMAP: break;
167 case TX_AUDIO_LOAD: {
174 if (mem_type==TX_AUDIO_MMAP) {
182 tX_audio_error tx_audiofile :: load_piped()
188 unsigned char buffer[SOX_BLOCKSIZE];
191 /* Irritating the user... */
192 ld_set_progress(0.5);
193 mem_type=TX_AUDIO_LOAD;
196 bytes = fread(buffer, 1, SOX_BLOCKSIZE, file);
201 int16_t *new_data=(int16_t *) realloc(data, allbytes);
202 //printf("All: %i, Bytes: %i, new: %08x, old: %08x\n", allbytes, bytes, new_data, data);
205 pclose(file); file=NULL;
206 if (data) free(data);
208 return TX_AUDIO_ERR_ALLOC;
212 ptr=(unsigned char *) data;
213 memcpy((void *) &ptr[prev_bytes],(void *) buffer, bytes);
217 pclose(file); file=NULL;
220 // If we get here we read zero Bytes...
221 if (data) free(data);
222 return TX_AUDIO_ERR_PIPE_READ;
225 no_samples=allbytes/sizeof(int16_t);
228 /* Irritating the user just a little more ;)*/
229 ld_set_progress(1.0);
231 return TX_AUDIO_SUCCESS;
237 tX_audio_error tx_audiofile :: load_sox() {
238 tX_debug("tx_audiofile::load_sox()");
240 char command[PATH_MAX*2];
242 sprintf(command, SOX_STR, filename);
243 file = popen(command, "r");
245 if (!file) return TX_AUDIO_ERR_SOX;
252 #ifdef USE_MPG123_INPUT
253 tX_audio_error tx_audiofile :: load_mpg123() {
254 tX_debug("tx_audiofile::load_mpg123()");
256 char command[PATH_MAX*2];
258 sprintf(command, MPG123_STR, filename);
259 file = popen(command, "r");
261 if (!file) return TX_AUDIO_ERR_MPG123;
267 #ifdef USE_OGG123_INPUT
268 tX_audio_error tx_audiofile :: load_ogg123() {
269 tX_debug("tx_audiofile::load_ogg123()");
271 char command[PATH_MAX*2];
273 sprintf(command, OGG123_STR, filename);
274 file = popen(command, "r");
276 if (!file) return TX_AUDIO_ERR_OGG123;
282 #ifdef USE_BUILTIN_WAV
283 #define min(a,b) ((a) < (b) ? (a) : (b))
284 tX_audio_error tx_audiofile :: load_wav() {
285 tX_debug("tx_audiofile::load_wav()");
293 mem_type=TX_AUDIO_LOAD;
295 if (!init_wav_read(filename, &wav_in))
297 return(TX_AUDIO_ERR_WAV_NOTFOUND);
300 if (wav_in.depth != 16)
302 return(TX_AUDIO_ERR_NOT_16BIT);
305 if (wav_in.chans != 1)
307 return(TX_AUDIO_ERR_NOT_MONO);
310 sample_rate=wav_in.srate;
313 data = (int16_t *) malloc (memsize);
317 return(TX_AUDIO_ERR_ALLOC);
321 #ifdef ENABLE_DEBUG_OUTPUT
323 unsigned char *debug_p=(unsigned char *) p;
325 while (wav_in.len>allbytes)
327 bytes = fread(p, 1, min(1024, wav_in.len-allbytes), wav_in.handle);
329 #ifdef ENABLE_DEBUG_OUTPUT
330 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]); }
335 return (TX_AUDIO_ERR_WAV_READ);
338 #ifdef BIG_ENDIAN_MACHINE
339 swapbuffer(p, bytes/sizeof(int16_t));
340 # ifdef ENABLE_DEBUG_OUTPUT
341 if (output) { tX_debug("tX_audiofile::load_wav() swapped %i Bytes [%04x %04x %04x %04x %04x %04x ..]",
342 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]); }
346 #ifdef ENABLE_DEBUG_OUTPUT
352 ld_set_progress((float) allbytes/(float)wav_in.len);
354 p+=(ssize_t) bytes/sizeof(int16_t);
357 wav_close(wav_in.handle);
360 no_samples=memsize/sizeof(int16_t);
362 return (TX_AUDIO_SUCCESS);
367 tX_audio_error tx_audiofile::load_mad() {
368 tX_debug("tx_audiofile::load_mad()");
370 struct stat stat_dat;
375 fd=open(filename, O_RDONLY);
376 if (!fd) return TX_AUDIO_ERR_MAD_OPEN;
378 if (fstat(fd, &stat_dat) == -1 ||
379 stat_dat.st_size == 0) {
380 return TX_AUDIO_ERR_MAD_STAT;
383 mp3_file = mmap(0, stat_dat.st_size, PROT_READ, MAP_SHARED, fd, 0);
385 if (mp3_file == MAP_FAILED) {
386 return TX_AUDIO_ERR_MAD_MMAP;
389 res=mad_decode((const unsigned char *) mp3_file, stat_dat.st_size);
392 return TX_AUDIO_ERR_MAD_DECODE;
395 mem_type=TX_AUDIO_LOAD;
397 if (munmap(mp3_file, stat_dat.st_size) == -1) {
398 return TX_AUDIO_ERR_MAD_MUNMAP;
401 return TX_AUDIO_SUCCESS;
404 #define TX_MAD_BLOCKSIZE 8096
407 const unsigned char *start;
408 const unsigned char *end;
409 const unsigned char *last_frame;
412 int16_t *target_buffer;
413 unsigned int target_samples;
414 unsigned int current_sample;
415 unsigned int sample_rate;
416 unsigned int lost_sync_counter;
419 const unsigned char *last_current=NULL;
421 static enum mad_flow tX_mad_input(void *data, struct mad_stream *stream) {
422 tX_mad_buffer *buffer = (tX_mad_buffer *) data;
426 if (buffer->first_call) {
427 bs=min(TX_MAD_BLOCKSIZE, buffer->size);
428 mad_stream_buffer(stream, buffer->start, bs);
429 buffer->first_call=false;
430 return MAD_FLOW_CONTINUE;
432 if (!stream->next_frame) return MAD_FLOW_STOP;
434 pos=stream->next_frame-buffer->start;
435 bs=min(TX_MAD_BLOCKSIZE, buffer->size-pos);
436 //tX_debug("last: %08x, new %08x, bs: %i, pos: %i", buffer->last_frame, stream->next_frame, bs, pos);
438 mad_stream_buffer(stream, stream->next_frame, bs);
439 if (stream->next_frame==buffer->last_frame) {
440 //tX_debug("tX_mad_input(): No new frame? Stopping.");
441 return MAD_FLOW_STOP;
443 ld_set_progress((float) pos/(float) buffer->size);
444 buffer->last_frame=stream->next_frame;
446 return MAD_FLOW_CONTINUE;
450 static enum mad_flow tX_mad_error(void *data, struct mad_stream *stream, struct mad_frame *frame) {
451 tX_mad_buffer *buffer = (tX_mad_buffer *) data;
452 if (MAD_RECOVERABLE(stream->error)) {
453 if ((stream->error==MAD_ERROR_LOSTSYNC) && (buffer->lost_sync_counter<3)) {
454 /* Ignore at least two sync errors to not annoy people
457 buffer->lost_sync_counter++;
458 return MAD_FLOW_CONTINUE;
460 tX_warning("mad reported stream error (%i) '%s'.", stream->error, mad_stream_errorstr(stream));
461 return MAD_FLOW_CONTINUE;
463 tX_error("mad reported fatal stream error (%i) '%s'.", stream->error, mad_stream_errorstr(stream));
464 return MAD_FLOW_STOP;
467 /* From minimad.c of mad */
468 static inline signed int scale(mad_fixed_t sample) {
469 //#ifdef BIG_ENDIAN_MACHINE
470 // swap32_inline(&sample);
473 sample += (1L << (MAD_F_FRACBITS - 16));
476 if (sample >= MAD_F_ONE)
477 sample = MAD_F_ONE - 1;
478 else if (sample < -MAD_F_ONE)
482 return sample >> (MAD_F_FRACBITS + 1 - 16);
485 static enum mad_flow tX_mad_output(void *data, struct mad_header const *header, struct mad_pcm *pcm) {
486 tX_mad_buffer *buffer=(tX_mad_buffer *) data;
487 unsigned int nchannels, nsamples;
488 mad_fixed_t const *left_ch, *right_ch;
490 nchannels = pcm->channels;
491 nsamples = pcm->length;
492 left_ch = pcm->samples[0];
493 right_ch = pcm->samples[1];
494 buffer->sample_rate = pcm->samplerate;
496 buffer->target_samples+=nsamples;
498 buffer->target_buffer=(int16_t *) realloc(buffer->target_buffer, buffer->target_samples<<1);
499 if (!buffer->target_buffer) {
500 tX_error("tX_mad_output(): Failed allocating sample memory!\n");
501 return MAD_FLOW_STOP;
508 sample=scale(*left_ch++);
510 double sample_l=(double) (*left_ch++);
511 double sample_r=(double) (*right_ch++);
512 double res=(sample_l+sample_r)/2.0;
513 mad_fixed_t mad_res=(mad_fixed_t) res;
515 sample=scale(mad_res);
518 buffer->target_buffer[buffer->current_sample]=sample;
519 buffer->current_sample++;
522 return MAD_FLOW_CONTINUE;
525 int tx_audiofile::mad_decode(unsigned char const *start, unsigned long length) {
526 tX_mad_buffer buffer;
527 struct mad_decoder decoder;
530 buffer.start = start;
531 buffer.end = &start[length];
532 buffer.last_frame = NULL;
533 buffer.size = length;
534 buffer.target_buffer = NULL;
535 buffer.target_samples = 0;
536 buffer.current_sample = 0;
537 buffer.first_call=true;
538 buffer.sample_rate=0;
539 buffer.lost_sync_counter=0;
541 tX_debug("tx_audiofile::mad_decode() - start %08x, length %i", buffer.start, buffer.size);
542 /* configure input, output, and error functions */
544 mad_decoder_init(&decoder, &buffer, tX_mad_input, NULL, NULL, tX_mad_output, tX_mad_error, NULL);
545 result = mad_decoder_run(&decoder, MAD_DECODER_MODE_SYNC);
548 this->mem=buffer.target_buffer;
549 this->no_samples=buffer.target_samples;
551 if (buffer.target_buffer) free(buffer.target_buffer);
554 /* release the decoder */
555 mad_decoder_finish(&decoder);
557 sample_rate=buffer.sample_rate;
563 /* AARG - OGG loading is not threadsafe !*/
564 size_t tX_ogg_file_size;
565 long tX_ogg_file_read;
567 #ifdef USE_VORBIS_INPUT
569 size_t (*read_func) (void *, size_t, size_t, FILE *);
570 int (*seek_func) (void *, long, int);
571 int (*close_func) (FILE *);
572 long (*tell_func) (FILE *);
575 int ogg_seek(void *ptr, long offset, int whence) {
576 /* ogg shall not seek ! */
581 size_t ogg_read(void *ptr, size_t size, size_t nmemb, FILE *stream) {
583 ret_val=fread(ptr, size, nmemb, stream);
585 tX_ogg_file_read+=ret_val*size;
586 ld_set_progress((double) tX_ogg_file_read/(double) tX_ogg_file_size);
591 #define VORBIS_BUFF_SIZE 4096 /*recommended*/
593 tX_audio_error tx_audiofile::load_vorbis() {
594 tX_debug("tx_audiofile::load_vorbis()");
596 /* VORBIS Callbacks */
597 ov_callbacks org_callbacks;
598 /* evil casting - to make g++ shut up */
599 tX_ov_callbacks *callbacks=(tX_ov_callbacks *) &org_callbacks;
602 char pcmout[VORBIS_BUFF_SIZE];
605 int current_section=0;
607 struct stat stat_dat;
609 callbacks->read_func=ogg_read;
610 callbacks->seek_func=ogg_seek;
611 callbacks->close_func=fclose;
612 callbacks->tell_func=ftell;
614 file=fopen(filename, "r");
616 return TX_AUDIO_ERR_WAV_NOTFOUND;
619 if (fstat(fileno(file), &stat_dat) == -1 || stat_dat.st_size == 0) {
620 return TX_AUDIO_ERR_MAD_STAT;
623 tX_ogg_file_size=stat_dat.st_size;
626 int res=ov_open_callbacks((void *) file, &vf, NULL, 0, org_callbacks);
630 return TX_AUDIO_ERR_VORBIS_OPEN;
633 vorbis_info *vi=ov_info(&vf,-1);
634 sample_rate=vi->rate;
636 unsigned int channels=vi->channels;
637 unsigned int samples_read=0;
638 unsigned int mono_samples;
642 while((!eof) && (!current_section)) {
643 #ifdef BIG_ENDIAN_MACHINE
648 long ret=ov_read(&vf,pcmout,VORBIS_BUFF_SIZE,ENDIANP,2,1,¤t_section);
651 } else if (ret < 0) {
652 /* ignore stream errors */
656 new_data=(int16_t *) realloc(data, bytes/channels);
658 if (data) free(data);
659 return TX_AUDIO_ERR_ALLOC;
\r
663 int16_t *src=(int16_t *) &pcmout;
668 for (i=0; i<mono_samples; i++) {
669 data[samples_read+i]=src[i];
675 for (i=0; i<mono_samples; i++) {
676 double l_value, r_value;
679 data[samples_read+i]=(int16_t) ((l_value+r_value)/2.0);
684 mono_samples=(ret/2)/channels;
685 for (i=0; i<mono_samples; i++) {
688 for (unsigned int c=0; c<channels; c++) {
689 value+=(double) src[i*channels+c];
691 value/=(double) channels;
692 data[samples_read+i]=(int16_t) value;
695 samples_read+=mono_samples;
701 mem=(int16_t *) data;
702 no_samples=samples_read;
707 return TX_AUDIO_ERR_VORBIS_NODATA;
710 return TX_AUDIO_SUCCESS;
714 #ifdef USE_AUDIOFILE_INPUT
715 #define TX_AF_SAMPLES_PER_BLOCK 2048
717 tX_audio_error tx_audiofile::load_af() {
718 tX_debug("tx_audiofile::load_af()");
720 AFfilehandle af_file;
721 AFframecount all_frames, frames_read=0, current_frames=1;
724 af_file = afOpenFile(filename, "r", NULL);
725 if (af_file==AF_NULL_FILEHANDLE) {
726 return TX_AUDIO_ERR_AF_OPEN;
729 all_frames=afGetFrameCount(af_file, AF_DEFAULT_TRACK);
730 sample_rate=(unsigned int) afGetRate(af_file, AF_DEFAULT_TRACK);
731 afSetVirtualChannels(af_file, AF_DEFAULT_TRACK, 1);
732 afSetVirtualSampleFormat(af_file, AF_DEFAULT_TRACK, AF_SAMPFMT_TWOSCOMP, 16); // 2 == 16 Bit?
733 #ifdef BIG_ENDIAN_MACHINE
734 afSetVirtualByteOrder(af_file, AF_DEFAULT_TRACK, AF_BYTEORDER_BIGENDIAN);
736 afSetVirtualByteOrder(af_file, AF_DEFAULT_TRACK, AF_BYTEORDER_LITTLEENDIAN);
739 while (current_frames) {
742 new_data=(int16_t*) realloc(data, (frames_read+TX_AF_SAMPLES_PER_BLOCK)*2);
744 if (data) free(data);
745 afCloseFile(af_file);
746 return TX_AUDIO_ERR_ALLOC;
749 current_frames=afReadFrames(af_file,AF_DEFAULT_TRACK,(void *) &data[frames_read],TX_AF_SAMPLES_PER_BLOCK);
750 frames_read+=current_frames;
751 ld_set_progress(((double) frames_read)/((double) all_frames));
753 afCloseFile(af_file);
756 if (data) free(data);
757 return TX_AUDIO_ERR_AF_NODATA;
760 /* shorten to the actually read size of samples */
761 if (!realloc(data, frames_read*2)) {
762 if (data) free(data);
763 return TX_AUDIO_ERR_ALLOC;
767 no_samples=frames_read;
769 return TX_AUDIO_SUCCESS;