Beispiel #1
0
int		
main (void)
{	static	short	buffer [BUFFER_SIZE] ;
	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	int			k, filetype ;	
	char		*filename = "headerless.wav" ;

	printf ("    header-less test : ") ;
	fflush (stdout) ;

	for (k = 0 ; k < BUFFER_SIZE ; k++)
		buffer [k] = k ;

	filetype = SF_FORMAT_WAV | SF_FORMAT_PCM_16 ;
	
	sfinfo.samplerate  = 32000 ;
	sfinfo.frames     = 123456789 ; /* Wrong length. Library should correct this on sf_close. */
	sfinfo.channels    = 1 ;
	sfinfo.format 	   = filetype ;

	if (! (file = sf_open (filename, SFM_WRITE, &sfinfo)))
	{	printf ("Line %d: sf_open_write failed with error : ", __LINE__) ;
		fflush (stdout) ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;

	if ((k = sf_write_short (file, buffer, BUFFER_SIZE)) != BUFFER_SIZE)
	{	printf ("Line %d: sf_write_short failed with short write (%d => %d).\n", __LINE__, BUFFER_SIZE, k) ;
		fflush (stdout) ;
		sf_perror (file) ;
		exit (1) ;
		} ;

	sf_close (file) ;
	
	memset (buffer, 0, sizeof (buffer)) ;

	/* Read as RAW but get the bit width and endian-ness correct. */
	sfinfo.format = filetype = SF_ENDIAN_LITTLE | SF_FORMAT_RAW | SF_FORMAT_PCM_16 ;

	if (! (file = sf_open (filename, SFM_READ, &sfinfo)))
	{	printf ("Line %d: sf_open_read failed with error : ", __LINE__) ;
		fflush (stdout) ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;

	if (sfinfo.format != filetype)
	{	printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, filetype, sfinfo.format) ;
		exit (1) ;
		} ;
	
	if (sfinfo.frames < BUFFER_SIZE)
	{	printf ("Line %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, BUFFER_SIZE, SF_COUNT_TO_LONG (sfinfo.frames)) ;
		exit (1) ;
		} ;
	
	if (sfinfo.channels != 1)
	{	printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ;
		exit (1) ;
		} ;

	check_log_buffer_or_die (file) ;
	
	if ((k = sf_read_short (file, buffer, BUFFER_SIZE)) != BUFFER_SIZE)
	{	printf ("Line %d: short read (%d).\n", __LINE__, k) ;
		exit (1) ;
		} ;

	for (k = 0 ; k < BUFFER_SIZE - 22 ; k++)
		if (buffer [k + 22] != k)
		{	printf ("Line %d: Incorrect sample (#%d : 0x%x => 0x%x).\n", __LINE__, k, k, buffer [k]) ;
			exit (1) ;
			} ;

	printf ("ok\n") ;
	unlink (filename) ;

	return 0;
} /* main */
Beispiel #2
0
int main()
{
char *filename = "44k.wav";
 SF_INFO sfinfo;
  SNDFILE *f;
  f = sf_open(filename,SFM_READ, &sfinfo);
 printf("\nCHECK RATE %d \n",sfinfo.samplerate);
printf("\nCHECK CHANNELS %d \n",sfinfo.channels);
printf("\nNumber of frames %ld \n",sfinfo.frames);

int j; 


snd_pcm_t *pcm_handle;
char *pcm_name;
unsigned int err;
//pcm_name = "default";
pcm_name = "plughw:0,0";
snd_pcm_hw_params_t *hwparams;
unsigned int rate = sfinfo.samplerate;


unsigned int channels = sfinfo.channels;
unsigned int exact_rate;


 snd_pcm_uframes_t frames, offset;
 snd_pcm_sframes_t commitres, avail,size=170;
 const snd_pcm_channel_area_t *areas;
 unsigned char *ptr[2];
 
snd_pcm_format_t stream = SND_PCM_FORMAT_S16_LE;


err=snd_pcm_open(&pcm_handle,pcm_name,SND_PCM_STREAM_PLAYBACK,0);
         
         if(err<0)       
                 {       
                         perror("\nCannot open PCM device\n");
                         exit(0);
           	}


if(snd_pcm_hw_params_malloc(&hwparams)<0)
	{
		perror("\nMemory cannot be allocated\n");
		exit(0);
	}


if(snd_pcm_hw_params_any(pcm_handle,hwparams)<0)
	{
		perror("\nUnable to set any HW configuration to device\n");
		exit(0);
	}

exact_rate = rate;

if(snd_pcm_hw_params_set_rate_near(pcm_handle,  hwparams,  &exact_rate, 0)<0)
	{
		printf("\nUnable to set rate %u instead rate used is %u \n",rate,exact_rate);
	}
rate = exact_rate;
printf("\nExact rate is %u \n",rate);


if(snd_pcm_hw_params_set_channels(pcm_handle,  hwparams,  channels),0)
	{
		perror("\nUnable to set channels\n");
		exit(0);
	}
if(snd_pcm_hw_params_set_format(pcm_handle,  hwparams,  stream)<0)
	{
		perror("\nUnable to set format\n");
		exit(0);
	}

if(snd_pcm_hw_params_set_access(pcm_handle,  hwparams,  SND_PCM_ACCESS_MMAP_INTERLEAVED)<0)
	{
		perror("\nUnable to set access\n");
		exit(0);
	}



snd_pcm_sframes_t period_size;

snd_pcm_hw_params_get_period_size(hwparams, &period_size,0);
	
printf("\nPeriod size is %ld \n",period_size);



err = snd_pcm_hw_params(pcm_handle,hwparams);
if(err<0)
	{
		perror("\nHW params cannot be set\n");
		exit(0);
	}


snd_pcm_hw_params_get_period_size(hwparams,&period_size,0);
printf("\nObtained Period size = %ld \n",period_size);

size = period_size;

snd_pcm_hw_params_get_buffer_size(hwparams,&frames);
printf("\nObtained buffer size is %ld \n",frames);


int ret = open(filename,O_RDONLY);
if(ret<0)
	{
		perror("\nFile cannot be opened\n");
		exit(0);
	}



int k=0;
int i;

while(1)
	{
	k++;
	if(k==2)
		{
			err = snd_pcm_start(pcm_handle);
			if(err<0)
				{
					perror("\nError starting PCM device\n");
					exit(1);
				}
		}
 
		
	avail = snd_pcm_avail_update(pcm_handle);
		if(avail<frames)
			{
				err = snd_pcm_prepare(pcm_handle);
				if(err<0)
					{
						perror("\nNo frames available\n");
						exit(0);
					}
		}
//	printf("\nFrames available %ld\n",avail);

	
	size=period_size;


	while(size>0)
		{
			

			frames = size;

			err = snd_pcm_mmap_begin(pcm_handle,  &areas,  &offset,  &frames);
						
			 if(err<0)
				{
					perror("\nMMAP cannot assign areas\n");
					exit(0);
				}
			

			for(i=0;i<1;i++)
			{
			ptr[i] = (unsigned char *)areas[i].addr + areas[i].first/8 + offset*(areas[i].step/8) ;
		//	printf("\nCheck\n");


				if(ptr[i]==NULL)
					{
						perror("\nPointer cannot point to memory\n");
						exit(0);
					}

			}


			for(i=0;i<1;i++)
			if(read(ret, ptr[i], frames*4)>0)
				{
					
				
				}
			else 
				{
					perror("\nFile cannot be opened\n");
					exit(0);
				}

				      commitres = snd_pcm_mmap_commit(pcm_handle,  offset,  frames);
 
                                         if(commitres<0)
                                                 {
                                                         err = snd_pcm_prepare(pcm_handle);
 
                                                         if(err<0)
                                                                 {
                                                                 perror("\nFrames cannot be committed\n");
                                                                exit(0);
                                                                }
						
						}

				else size-=frames;
			snd_pcm_wait(pcm_handle,1000);


		}//END OF "while(size>0)" LOOP

		}//END OF OUTER WHILE LOOP

}
Beispiel #3
0
int main(int argc, char *argv[]) {

    if(alcIsExtensionPresent(NULL, "ALC_SOFT_loopback") == ALC_FALSE) {
        fputs("Your OpenAL implementation doesn't support the "
              "\"ALC_SOFT_loopback\" extension, required for this test. "
              "Sorry.\n", stderr);
        exit(EXIT_FAILURE);
    }
    ALCint alc_major, alc_minor;
    alcGetIntegerv(NULL, ALC_MAJOR_VERSION, 1, &alc_major);
    alcGetIntegerv(NULL, ALC_MINOR_VERSION, 1, &alc_minor);
    if(alc_major<1 || (alc_major==1 && alc_minor<1))
        fputs("Warning : ALC_SOFT_loopback has been written against "
              "the OpenAL 1.1 specification.\n", stderr);

#define HELPER(X) X = alcGetProcAddress(NULL, #X)
    HELPER(alcLoopbackOpenDeviceSOFT);
    HELPER(alcIsRenderFormatSupportedSOFT);
    HELPER(alcRenderSamplesSOFT);
#undef  HELPER
#define HELPER(X) X = alcGetEnumValue(NULL, #X)
    HELPER(ALC_BYTE_SOFT);
    HELPER(ALC_UNSIGNED_BYTE_SOFT);
    HELPER(ALC_SHORT_SOFT);
    HELPER(ALC_UNSIGNED_SHORT_SOFT);
    HELPER(ALC_INT_SOFT);
    HELPER(ALC_UNSIGNED_INT_SOFT);
    HELPER(ALC_FLOAT_SOFT);
    HELPER(ALC_MONO_SOFT);
    HELPER(ALC_STEREO_SOFT);
    HELPER(ALC_QUAD_SOFT);
    HELPER(ALC_5POINT1_SOFT);
    HELPER(ALC_6POINT1_SOFT);
    HELPER(ALC_7POINT1_SOFT);
    HELPER(ALC_FORMAT_CHANNELS_SOFT);
    HELPER(ALC_FORMAT_TYPE_SOFT);
#undef  HELPER

    ALCdevice *loopback_device = alcLoopbackOpenDeviceSOFT(NULL);
    if(!loopback_device) {
        fputs("Could not open loopback device.\n", stderr);
        exit(EXIT_FAILURE);
    }
    if(alcIsRenderFormatSupportedSOFT(loopback_device, 
            22050, ALC_STEREO_SOFT, ALC_SHORT_SOFT) == ALC_FALSE) 
    {
        fputs("The loopback device does not support the "
              "required render format.\n", stderr);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }

    ALCint attrlist[11] = {
        ALC_MONO_SOURCES, 0,
        ALC_STEREO_SOURCES, 255,
        ALC_FREQUENCY, 22050,
        ALC_FORMAT_CHANNELS_SOFT, ALC_STEREO_SOFT,
        ALC_FORMAT_TYPE_SOFT, ALC_SHORT_SOFT,
        0
    };
    ALCcontext *ctx = alcCreateContext(loopback_device, attrlist);
    alcMakeContextCurrent(ctx);
    alGetError(); /* Clear the error state */

    if(argc<=1) {
        fprintf(stderr, "Usage : %s <small_oggfile>\n", argv[0]);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }

    SF_INFO sndinfo;
    SNDFILE *snd = sf_open(argv[1], SFM_READ, &sndinfo);
    if(!snd) {
        fprintf(stderr, "Failed to open \"%s\" : %s\n", 
                argv[1], sf_strerror(snd));
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }
    if(sndinfo.channels != 2) {
        fprintf(stderr, "The source sound file has %d channels "
                "(exactly 2 are required).\n", sndinfo.channels);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }
    short *data = malloc(sndinfo.frames*2*sizeof(short));
    printf("Reading from '%s'...\n", argv[1]);
    sf_readf_short(snd, data, sndinfo.frames);
    sf_close(snd);

    ALuint audio_buffer;
    alGenBuffers(1, &audio_buffer);
    alBufferData(audio_buffer, AL_FORMAT_STEREO16, data,
            sndinfo.frames*2*sizeof(short), sndinfo.samplerate);
    free(data);

    ALuint audio_source;
    alGenSources(1, &audio_source);
    alSourcei(audio_source, AL_BUFFER, audio_buffer);

    unsigned num_frames = sndinfo.frames;
    ALCshort *rendered_samples = malloc(num_frames*2*sizeof(ALCshort));
    sndinfo.samplerate = 22050;
    sndinfo.channels = 2;
    sndinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS | SF_ENDIAN_FILE;
    snd = sf_open("rendered.ogg", SFM_WRITE, &sndinfo);

    alSourcePlay(audio_source);

    puts("Rendering frames...");
    unsigned chunk_size = 4096, off;
    for(off=0 ; off<(num_frames-chunk_size)*2 ; off+=2*chunk_size)
        alcRenderSamplesSOFT(loopback_device, rendered_samples+off, chunk_size);

    puts("Writing to 'rendered.ogg'...");
    sf_write_short(snd, rendered_samples, off-s);
    sf_close(snd);
    free(rendered_samples);

    alDeleteSources(1, &audio_source);
    alDeleteBuffers(1, &audio_buffer);
    alcCloseDevice(loopback_device);
    alcMakeContextCurrent(NULL);
    alcDestroyContext(ctx);

    exit(EXIT_SUCCESS);
}
static void
macosx_play (int argc, char *argv [])
{	MacOSXAudioData 	audio_data ;
	OSStatus	err ;
	UInt32		count, buffer_size ;
	int 		k ;

	audio_data.fake_stereo = 0 ;
	audio_data.device = kAudioDeviceUnknown ;

	/*  get the default output device for the HAL */
	count = sizeof (AudioDeviceID) ;
	if ((err = AudioHardwareGetProperty (kAudioHardwarePropertyDefaultOutputDevice,
				&count, (void *) &(audio_data.device))) != noErr)
	{	printf ("AudioHardwareGetProperty (kAudioDevicePropertyDefaultOutputDevice) failed.\n") ;
		return ;
		} ;

	/*  get the buffersize that the default device uses for IO */
	count = sizeof (UInt32) ;
	if ((err = AudioDeviceGetProperty (audio_data.device, 0, false, kAudioDevicePropertyBufferSize,
				&count, &buffer_size)) != noErr)
	{	printf ("AudioDeviceGetProperty (kAudioDevicePropertyBufferSize) failed.\n") ;
		return ;
		} ;

	/*  get a description of the data format used by the default device */
	count = sizeof (AudioStreamBasicDescription) ;
	if ((err = AudioDeviceGetProperty (audio_data.device, 0, false, kAudioDevicePropertyStreamFormat,
				&count, &(audio_data.format))) != noErr)
	{	printf ("AudioDeviceGetProperty (kAudioDevicePropertyStreamFormat) failed.\n") ;
		return ;
		} ;

	/* Base setup completed. Now play files. */
	for (k = 1 ; k < argc ; k++)
	{	printf ("Playing %s\n", argv [k]) ;
		if (! (audio_data.sndfile = sf_open (argv [k], SFM_READ, &(audio_data.sfinfo))))
		{	puts (sf_strerror (NULL)) ;
			continue ;
			} ;

		if (audio_data.sfinfo.channels < 1 || audio_data.sfinfo.channels > 2)
		{	printf ("Error : channels = %d.\n", audio_data.sfinfo.channels) ;
			continue ;
			} ;

		audio_data.format.mSampleRate = audio_data.sfinfo.samplerate ;

		if (audio_data.sfinfo.channels == 1)
		{	audio_data.format.mChannelsPerFrame = 2 ;
			audio_data.fake_stereo = 1 ;
			}
		else
		audio_data.format.mChannelsPerFrame = audio_data.sfinfo.channels ;

		if ((err = AudioDeviceSetProperty (audio_data.device, NULL, 0, false, kAudioDevicePropertyStreamFormat,
					sizeof (AudioStreamBasicDescription), &(audio_data.format))) != noErr)
		{	printf ("AudioDeviceSetProperty (kAudioDevicePropertyStreamFormat) failed.\n") ;
			return ;
			} ;

		/*  we want linear pcm */
		if (audio_data.format.mFormatID != kAudioFormatLinearPCM)
			return ;

		/* Fire off the device. */
		if ((err = AudioDeviceAddIOProc (audio_data.device, macosx_audio_out_callback,
				(void *) &audio_data)) != noErr)
		{	printf ("AudioDeviceAddIOProc failed.\n") ;
			return ;
			} ;

		err = AudioDeviceStart (audio_data.device, macosx_audio_out_callback) ;
		if	(err != noErr)
			return ;

		audio_data.done_playing = SF_FALSE ;

		while (audio_data.done_playing == SF_FALSE)
			usleep (10 * 1000) ; /* 10 000 milliseconds. */

		if ((err = AudioDeviceStop (audio_data.device, macosx_audio_out_callback)) != noErr)
		{	printf ("AudioDeviceStop failed.\n") ;
			return ;
			} ;

		err = AudioDeviceRemoveIOProc (audio_data.device, macosx_audio_out_callback) ;
		if (err != noErr)
		{	printf ("AudioDeviceRemoveIOProc failed.\n") ;
			return ;
			} ;

		sf_close (audio_data.sndfile) ;
		} ;

	return ;
} /* macosx_play */
static void
solaris_play (int argc, char *argv [])
{	static short 	buffer [BUFFER_LEN] ;
	audio_info_t	audio_info ;
	SNDFILE			*sndfile ;
	SF_INFO			sfinfo ;
	unsigned long	delay_time ;
	long			k, start_count, output_count, write_count, read_count ;
	int				audio_fd, error, done ;

	for (k = 1 ; k < argc ; k++)
	{	printf ("Playing %s\n", argv [k]) ;
		if (! (sndfile = sf_open (argv [k], SFM_READ, &sfinfo)))
		{	puts (sf_strerror (NULL)) ;
			continue ;
			} ;

		if (sfinfo.channels < 1 || sfinfo.channels > 2)
		{	printf ("Error : channels = %d.\n", sfinfo.channels) ;
			continue ;
			} ;

		/* open the audio device - write only, non-blocking */
		if ((audio_fd = open ("/dev/audio", O_WRONLY | O_NONBLOCK)) < 0)
		{	perror ("open (/dev/audio) failed") ;
			return ;
			} ;

		/*	Retrive standard values. */
		AUDIO_INITINFO (&audio_info) ;

		audio_info.play.sample_rate = sfinfo.samplerate ;
		audio_info.play.channels = sfinfo.channels ;
		audio_info.play.precision = 16 ;
		audio_info.play.encoding = AUDIO_ENCODING_LINEAR ;
		audio_info.play.gain = AUDIO_MAX_GAIN ;
		audio_info.play.balance = AUDIO_MID_BALANCE ;

		if ((error = ioctl (audio_fd, AUDIO_SETINFO, &audio_info)))
		{	perror ("ioctl (AUDIO_SETINFO) failed") ;
			return ;
			} ;

		/* Delay time equal to 1/4 of a buffer in microseconds. */
		delay_time = (BUFFER_LEN * 1000000) / (audio_info.play.sample_rate * 4) ;

		done = 0 ;
		while (! done)
		{	read_count = sf_read_short (sndfile, buffer, BUFFER_LEN) ;
			if (read_count < BUFFER_LEN)
			{	memset (&(buffer [read_count]), 0, (BUFFER_LEN - read_count) * sizeof (short)) ;
				/* Tell the main application to terminate. */
				done = SF_TRUE ;
				} ;

			start_count = 0 ;
			output_count = BUFFER_LEN * sizeof (short) ;

			while (output_count > 0)
			{	/* write as much data as possible */
				write_count = write (audio_fd, &(buffer [start_count]), output_count) ;
				if (write_count > 0)
				{	output_count -= write_count ;
					start_count += write_count ;
					}
				else
				{	/*	Give the audio output time to catch up. */
					usleep (delay_time) ;
					} ;
				} ; /* while (outpur_count > 0) */
			} ; /* while (! done) */

		close (audio_fd) ;
		} ;

	return ;
} /* solaris_play */
int prSFOpenWrite(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot *a, *b;
	char filename[PATH_MAX];
	SNDFILE *file;
	SF_INFO info;
	PyrSlot *headerSlot;
	PyrSlot *formatSlot;
	int error;


	a = g->sp - 1;
	b = g->sp;

	headerSlot = (slotRawObject(a)->slots + 1);
	formatSlot = (slotRawObject(a)->slots + 2);


	if (!isKindOfSlot(headerSlot, class_string)) return errWrongType;
	if (!isKindOfSlot(formatSlot, class_string)) return errWrongType;

	if (!isKindOfSlot(b, class_string)) return errWrongType;
	if (slotRawObject(b)->size > PATH_MAX - 1) return errFailed;

	memcpy(filename, slotRawString(b)->s, slotRawObject(b)->size);
	filename[slotRawString(b)->size] = 0;

#ifdef SC_WIN32
	char* headerFormat = (char *)malloc(slotRawObject(headerSlot)->size);
#else
	char headerFormat[slotRawString(headerSlot)->size];
#endif
	memcpy(headerFormat, slotRawString(headerSlot)->s, slotRawObject(headerSlot)->size);
	headerFormat[slotRawString(headerSlot)->size] = 0;

#ifdef SC_WIN32
	char* sampleFormat = (char *)malloc(slotRawString(formatSlot)->size);
#else
	char sampleFormat[slotRawString(formatSlot)->size];
#endif
	memcpy(sampleFormat, slotRawString(formatSlot)->s, slotRawObject(formatSlot)->size);
	sampleFormat[slotRawString(formatSlot)->size] = 0;

	error = sndfileFormatInfoFromStrings(&info, headerFormat, sampleFormat);
	if(error) {
#ifdef SC_WIN32
		free(sampleFormat);
		free(headerFormat);
#endif
		return errFailed;
	}

	if(error) 	return errFailed;
	//slotIntVal(slotRawObject(a)->slots + 3, &info.frames);
	slotIntVal(slotRawObject(a)->slots + 4, &info.channels);
	slotIntVal(slotRawObject(a)->slots + 5, &info.samplerate);

	file = sf_open(filename, SFM_WRITE, &info);
	sf_command(file, SFC_SET_CLIPPING, NULL, SF_TRUE);

	if (file) {
		SetPtr(slotRawObject(a)->slots+0, file);
		SetTrue(a);
	} else {
		SetNil(a);
		SetFalse(a);
	}

	return errNone;
}
Beispiel #7
0
int main(int argc, char **argv) {

  SNDFILE *soundfile = NULL;
  SF_INFO info;

  SNDFILE *soundfile_out = NULL;
  SF_INFO info_out;

  float integrator=0.0;
  float error_signal=0.0;
  float out=0.0;

  int i,j,k;
  int count;
  int error;

  int ttyfd=-1;
  struct termios oldtio,newtio;

  unsigned char outbyte;

  SRC_STATE *samplerate;
  SRC_DATA resample_data;
  SRC_STATE *samplerate_out;
  SRC_DATA resample_data_out;

  info.format=0;

  int quiet = 0;
  char device[128];
  char outfile[1024];
  char infile[1024];
  char output[1024];
  int rate = 48000;

  strcpy(device, "/dev/ttyS0");
  strcpy(output, device);

  int opt;
  while ((opt = getopt(argc, argv, "qd:r:w:")) != -1) {
    switch(opt) {
      case 'd':
        strcpy(device, optarg);
        strcpy(output, device);
        break;
      case 'r':
        rate = atoi(optarg);
        break;
      case 'w':
        strcpy(outfile, optarg);
        strcpy(output, outfile);
        break;
      case 'q':
        quiet = 1;
        break;
    }
  }

  if (optind >= argc) {
    fprintf(stderr, "Usage:\t%s [-q] [-r sample_rate] [-d device | -w out.wav] in.wav\n", argv[0]);
    return 1;
  } else strcpy(infile, argv[optind]);

  if (!quiet)
    fprintf(stderr,"Playing:\t%s\nOutput:\t\t%s\nSample rate:\t%d\n", infile, output, rate);

  soundfile=sf_open(infile,SFM_READ,&info);

  info_out.samplerate=rate;
  info_out.channels=1;
  info_out.format=SF_FORMAT_PCM_16|SF_FORMAT_WAV;

  if (strlen(outfile) > 1) {
    soundfile_out=sf_open(outfile,SFM_WRITE,&info_out);

    if ((soundfile==NULL) || (soundfile_out==NULL)) {
      fprintf(stderr,"Couldn't open that file. Sorry.\n");
      return 1;
    }
  } else { // we're not writing an output file, try serial I/O
    // blocking I/O blocks forever on open(), dunno why.
    ttyfd = open(device, O_RDWR|O_NOCTTY|O_NONBLOCK);
    if (ttyfd <0) {perror(device); exit(-1); }
    tcgetattr(ttyfd,&oldtio); /* save current serial port settings */
    bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */

    cfmakeraw(&newtio);
    if (0!=cfsetospeed(&newtio,SERIAL_BAUDRATE)) { perror(device); exit(-1); }
    if (0!=tcflush(ttyfd, TCIFLUSH)) { perror(device); exit(-1); }
    if (0!=tcsetattr(ttyfd,TCSANOW,&newtio)) { perror(device); exit(-1); }
  }

  samplerate=src_new(SRC_LINEAR,1,&error);

  if (error) {
    fprintf(stderr,"Samplerate error. Sorry.\n");
    return 1;
  }

  samplerate_out=src_new(SRC_SINC_FASTEST,1,&error);

  if (error) {
    fprintf(stderr,"Samplerate error. Sorry.\n");
    return 1;
  }

  resample_data.data_in=(float *)malloc((int)(SOUND_BUFFER_LEN*info.samplerate*info.channels)*sizeof(float));
  resample_data.data_out=(float *)malloc(2*(int)(SOUND_BUFFER_LEN*BAUDRATE)*sizeof(float));
  resample_data.src_ratio=((float)BAUDRATE)/(float)info.samplerate;
  resample_data.end_of_input=0;

  resample_data.output_frames=(int)2*BAUDRATE*SOUND_BUFFER_LEN;

  resample_data_out.data_in=(float *)malloc(2*BAUDRATE*sizeof(float));
  resample_data_out.data_out=(float *)malloc(2*(int)(SOUND_BUFFER_LEN*rate)*sizeof(float));
  resample_data_out.src_ratio=((float)rate)/((float)BAUDRATE);
  resample_data_out.end_of_input=0;
  resample_data_out.output_frames=(int)(2*rate*SOUND_BUFFER_LEN);

  k=0;

  while ((count=sf_readf_float(soundfile,resample_data.data_in,(int)(SOUND_BUFFER_LEN*info.samplerate)))) {

    // make mono
    for (j=0; j<count; j++) {
      resample_data.data_in[j]=resample_data.data_in[j*info.channels];
      for (i=1; i<info.channels; i++) {
        resample_data.data_in[j]+=resample_data.data_in[j*info.channels+i];
      }
      resample_data.data_in[j]/=(float)info.channels;
    }

    resample_data.input_frames=count;

    // following has a bug...
    if (count<(int)(SOUND_BUFFER_LEN*info.samplerate)) {
      resample_data.end_of_input=1;
      resample_data_out.end_of_input=1;
    }

    src_process(samplerate,&resample_data);

    // Now we have our input signal converted to the serial baudrate.  All that's left is sigma-delta modulate
    // and write to the serial port

    outbyte=0;
    for (j=0; j<resample_data.output_frames_gen; j++) {

      error_signal=resample_data.data_out[j]-out;

      integrator+=error_signal;

      switch (k%10) {
      case 0:
        outbyte=0;
        out=-1.0; //start bit
        break;
      case 9:
        out=1.0; //stop bit
        if (ttyfd>=0) {
          while ( 1!=write(ttyfd,&outbyte,1)) { /* What's a spinloop among friends? */ ; }
        }
        break;
      default:
        out=(integrator>0) ? 1.0 : -1.0;
        if (out>0.0) outbyte |= 1<<((k%10)-1);
      }

      resample_data_out.data_in[j]=out;

      k++;
    }

    if (soundfile_out) {
      resample_data_out.input_frames=resample_data.output_frames_gen;
      src_process(samplerate_out,&resample_data_out);

      i=sf_write_float(soundfile_out,
        resample_data_out.data_out,
        resample_data_out.output_frames_gen);

    }

  }

  sf_close(soundfile);
  if (soundfile_out) sf_close(soundfile_out);

  // restore serial port settings
  if (ttyfd>=0) {
    tcsetattr(ttyfd,TCSANOW,&oldtio);
  }

  return 0;
}
Beispiel #8
0
/* pass_on()
 * Is the work loop of the logger. Selects on the pipe to the to_erl
 * program erlang. If input arrives from to_erl it is passed on to
 * erlang.
 */
static void pass_on(pid_t childpid)
{
    int len;
    fd_set readfds;
    fd_set writefds;
    fd_set* writefds_ptr;
    struct timeval timeout;
    time_t last_activity;
    char buf[BUFSIZ];
    char log_alive_buffer[ALIVE_BUFFSIZ+1];
    int lognum;
    int rfd, wfd=0, lfd=0;
    int maxfd;
    int ready;
    int got_some = 0; /* from to_erl */
    
    /* Open the to_erl pipe for reading.
     * We can't open the writing side because nobody is reading and 
     * we'd either hang or get an error.
     */
    if ((rfd = sf_open(fifo2, O_RDONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
	ERRNO_ERR1(LOG_ERR,"Could not open FIFO '%s' for reading.", fifo2);
	exit(1);
    }
    
#ifdef DEBUG
    status("run_erl: %s opened for reading\n", fifo2);
#endif
    
    /* Open the log file */
    
    lognum = find_next_log_num();
    lfd = open_log(lognum, O_RDWR|O_APPEND|O_CREAT|O_SYNC);
    
    /* Enter the work loop */
    
    while (1) {
	int exit_status;
	maxfd = MAX(rfd, mfd);
	maxfd = MAX(wfd, maxfd);
	FD_ZERO(&readfds);
	FD_SET(rfd, &readfds);
	FD_SET(mfd, &readfds);
	FD_ZERO(&writefds);
	if (outbuf_size() == 0) {
	    writefds_ptr = NULL;
	} else {
	    FD_SET(wfd, &writefds);
	    writefds_ptr = &writefds;
	}
	time(&last_activity);
	timeout.tv_sec  = log_alive_minutes*60; /* don't assume old BSD bug */
	timeout.tv_usec = 0;
	ready = select(maxfd + 1, &readfds, writefds_ptr, NULL, &timeout);
	if (ready < 0) {
	    if (errno == EINTR) {
		if (waitpid(childpid, &exit_status, WNOHANG) == childpid) {
		    /*
		     * The Erlang emulator has terminated. Give us some more
		     * time to write out any pending data before we terminate too.
		     */
		    alarm(5);
		}
		FD_ZERO(&readfds);
		FD_ZERO(&writefds);
	    } else {
		/* Some error occured */
		ERRNO_ERR0(LOG_ERR,"Error in select.");
		exit(1);
	    }
	} else {
	    time_t now;

	    if (waitpid(childpid, &exit_status, WNOHANG) == childpid) {
		alarm(5);
		FD_ZERO(&readfds);
		FD_ZERO(&writefds);
	    }

	    /* Check how long time we've been inactive */
	    time(&now);
	    if(!ready || now - last_activity > log_activity_minutes*60) {
		/* Either a time out: 15 minutes without action, */
		/* or something is coming in right now, but it's a long time */
		/* since last time, so let's write a time stamp this message */
		struct tm *tmptr;
		if (log_alive_in_gmt) {
		    tmptr = gmtime(&now);
		} else {
		    tmptr = localtime(&now);
		}
		if (!strftime(log_alive_buffer, ALIVE_BUFFSIZ, log_alive_format,
			      tmptr)) {
		    strn_cpy(log_alive_buffer, sizeof(log_alive_buffer),
			     "(could not format time in 256 positions "
			     "with current format string.)");
		}
		log_alive_buffer[ALIVE_BUFFSIZ] = '\0';

		sn_printf(buf, sizeof(buf), "\n===== %s%s\n", 
			  ready?"":"ALIVE ", log_alive_buffer);
		write_to_log(&lfd, &lognum, buf, strlen(buf));
	    }
	}

	/*
	 * Write any pending output first.
	 */
	if (FD_ISSET(wfd, &writefds)) {
	    int written;
	    char* buf = outbuf_first();

	    len = outbuf_size();
	    written = sf_write(wfd, buf, len);
	    if (written < 0 && errno == EAGAIN) {
		/*
		 * Nothing was written - this is really strange because
		 * select() told us we could write. Ignore.
		 */
	    } else if (written < 0) {
		/*
		 * A write error. Assume that to_erl has terminated.
		 */
		clear_outbuf();
		sf_close(wfd);
		wfd = 0;
	    } else {
		/* Delete the written part (or all) from the buffer. */
		outbuf_delete(written);
	    }
	}
	
	/*
	 * Read master pty and write to FIFO.
	 */
	if (FD_ISSET(mfd, &readfds)) {
#ifdef DEBUG
	    status("Pty master read; ");
#endif
	    if ((len = sf_read(mfd, buf, BUFSIZ)) <= 0) {
		sf_close(rfd);
		if(wfd) sf_close(wfd);
		sf_close(mfd);
		unlink(fifo1);
		unlink(fifo2);
		if (len < 0) {
		    if(errno == EIO)
			ERROR0(LOG_ERR,"Erlang closed the connection.");
		    else
			ERRNO_ERR0(LOG_ERR,"Error in reading from terminal");
		    exit(1);
		}
		exit(0);
	    }

	    write_to_log(&lfd, &lognum, buf, len);

	    /*
	     * Save in the output queue.
	     */

	    if (wfd) {
		outbuf_append(buf, len);
	    }
	}	    

	/*
	 * Read from FIFO, write to master pty
	 */
	if (FD_ISSET(rfd, &readfds)) {
#ifdef DEBUG
	    status("FIFO read; ");
#endif
	    if ((len = sf_read(rfd, buf, BUFSIZ)) < 0) {
		sf_close(rfd);
		if(wfd) sf_close(wfd);
		sf_close(mfd);
		unlink(fifo1);
		unlink(fifo2);
		ERRNO_ERR0(LOG_ERR,"Error in reading from FIFO.");
		exit(1);
	    }

	    if(!len) {
		/* to_erl closed its end of the pipe */
		sf_close(rfd);
		rfd = sf_open(fifo2, O_RDONLY|DONT_BLOCK_PLEASE, 0);
		if (rfd < 0) {
		    ERRNO_ERR1(LOG_ERR,"Could not open FIFO '%s' for reading.", fifo2);
		    exit(1);
		}
		got_some = 0; /* reset for next session */
	    }
	    else { 
		if(!wfd) {
		    /* Try to open the write pipe to to_erl. Now that we got some data
		     * from to_erl, to_erl should already be reading this pipe - open
		     * should succeed. But in case of error, we just ignore it.
		     */
		    if ((wfd = sf_open(fifo1, O_WRONLY|DONT_BLOCK_PLEASE, 0)) < 0) {
			status("Client expected on FIFO %s, but can't open (len=%d)\n",
			       fifo1, len);
			sf_close(rfd);
			rfd = sf_open(fifo2, O_RDONLY|DONT_BLOCK_PLEASE, 0);
			if (rfd < 0) {
			    ERRNO_ERR1(LOG_ERR,"Could not open FIFO '%s' for reading.", fifo2);
			    exit(1);
			}
			wfd = 0;
		    } 
		    else {
#ifdef DEBUG
			status("run_erl: %s opened for writing\n", fifo1);
#endif
		    }
		}

		if (!got_some && wfd && buf[0] == '\022') {
		    char wbuf[30];
		    int wlen = sn_printf(wbuf,sizeof(wbuf),"[run_erl v%u-%u]\n",
					 RUN_ERL_HI_VER, RUN_ERL_LO_VER);
		    outbuf_append(wbuf,wlen);
		}
		got_some = 1;


		/* Write the message */
#ifdef DEBUG
		status("Pty master write; ");
#endif
		len = extract_ctrl_seq(buf, len);

		if(len==1 && buf[0] == '\003') {
		    kill(childpid,SIGINT);
		} 
		else if (len>0 && write_all(mfd, buf, len) != len) {
		    ERRNO_ERR0(LOG_ERR,"Error in writing to terminal.");
		    sf_close(rfd);
		    if(wfd) sf_close(wfd);
		    sf_close(mfd);
		    exit(1);
		}
	    }
#ifdef DEBUG
	    status("OK\n");
#endif
	}
    }
} /* pass_on() */
Beispiel #9
0
static int open_pty_master(char **ptyslave, int *sfdp)
{
  int mfd;

/* Use the posix_openpt if working, as this guarantees creation of the 
   slave device properly. */
#if defined(HAVE_WORKING_POSIX_OPENPT) || (defined(__sun) && defined(__SVR4))
#  ifdef HAVE_WORKING_POSIX_OPENPT
  if ((mfd = posix_openpt(O_RDWR)) >= 0) {
#  elif defined(__sun) && defined(__SVR4)
  mfd = sf_open("/dev/ptmx", O_RDWR, 0);

  if (mfd >= 0) {
#  endif
      if ((*ptyslave = ptsname(mfd)) != NULL &&
	  grantpt(mfd) == 0 && 
	  unlockpt(mfd) == 0) {

	  return mfd;
      }
      sf_close(mfd);
  }
  /* fallback to openpty if it exist */
#endif

#if defined(HAVE_OPENPTY)
#  ifdef PATH_MAX
#    define SLAVE_SIZE PATH_MAX
#  else
#    define SLAVE_SIZE 1024
#  endif
  {
      static char slave[SLAVE_SIZE];
#  undef SLAVE_SIZE
      if (openpty(&mfd, sfdp, slave, NULL, NULL) == 0) {
	  *ptyslave = slave;
	  return mfd;
      }
  }

#elif !defined(HAVE_WORKING_POSIX_OPENPT)
  /*
   * The traditional way to find ptys. We only try it if neither
   * posix_openpt or openpty() are available.
   */
  char *major, *minor;

  static char majorchars[] = "pqrstuvwxyzabcdePQRSTUVWXYZABCDE";
  static char minorchars[] = "0123456789abcdefghijklmnopqrstuv"
			     "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_+";

  /* In the old time the names where /dex/ptyXY where */
  /* X is in "pqrs" and Y in "0123456789abcdef" but FreeBSD */
  /* and some Linux version has extended this. */

  /* This code could probebly be improved alot. For example look at */
  /* http://www.xcf.berkeley.edu/~ali/K0D/UNIX/PTY/code/pty.c.html */
  /* http://www.xcf.berkeley.edu/~ali/K0D/UNIX/PTY/code/upty.h.html */

  {
    /* New style devpts or devfs /dev/pty/{m,s}{0,1....} */

    static char ptyname[] = "/dev/pty/mX";

    for (minor = minorchars; *minor; minor++) {
      ptyname[10] = *minor;

      if ((mfd = sf_open(ptyname, O_RDWR, 0)) >= 0) {
	ptyname[9] = 's';
	*ptyslave = ptyname;
	return mfd;
      }
    }
  }

  {
    /* Unix98 style /dev/ptym/ptyXY and /dev/pty/ttyXY */

    static char ptyname[] = "/dev/ptym/ptyXY";
    static char ttyname[] = "/dev/pty/ttyXY";

    for (major = majorchars; *major; major++) {
      ptyname[13] = *major;
      for (minor = minorchars; *minor; minor++) {
	ptyname[14] = *minor;
	if ((mfd = sf_open(ptyname, O_RDWR, 0)) >= 0) {
	  ttyname[12] = *major;
	  ttyname[13] = *minor;
	  *ptyslave = ttyname;
	  return mfd;
	}
      }
    }
  }

  {
    /* Old style /dev/ptyXY */

    static char ptyname[] = "/dev/ptyXY";

    for (major = majorchars; *major; major++) {
      ptyname[8] = *major;
      for (minor = minorchars; *minor; minor++) {
	ptyname[9] = *minor;
	if ((mfd = sf_open(ptyname, O_RDWR, 0)) >= 0) {
	  ptyname[5] = 't';
	  *ptyslave = ptyname;
	  return mfd;
	}
      }
    }
  }
#endif /* !HAVE_OPENPTY */
  return -1;
}

static int open_pty_slave(char *name)
{
  int sfd;
  struct termios tty_rmode;

  if ((sfd = sf_open(name, O_RDWR, 0)) < 0) {
    return -1;
  }

#if defined(__sun) && defined(__SVR4)
  /* Load the necessary STREAMS modules for Solaris */
  if ((ioctl(sfd, I_FIND, "ldterm")) < 0) {
    ERROR0(LOG_ERR, "Failed to find ldterm STREAMS module");
    return -1;
  }
  if (ioctl(sfd, I_PUSH, "ptem") < 0) {
    ERROR0(LOG_ERR, "Failed to push ptem STREAMS module");
    return -1;
  }
  if (ioctl(sfd, I_PUSH, "ldterm") < 0) {
    ERROR0(LOG_ERR, "Failed to push ldterm STREAMS module");
    return -1;
  }
  if (ioctl(sfd, I_PUSH, "ttcompat") < 0) {
    ERROR0(LOG_ERR, "Failed to push ttcompat STREAMS module");
    return -1;
  }
#endif

  if (getenv("RUN_ERL_DISABLE_FLOWCNTRL")) {
    if (tcgetattr(sfd, &tty_rmode) < 0) {
      fprintf(stderr, "Cannot get terminal's current mode\n");
      exit(-1);
    }

    tty_rmode.c_iflag &= ~IXOFF;
    if (tcsetattr(sfd, TCSANOW, &tty_rmode) < 0) {
      fprintf(stderr, "Cannot disable terminal's flow control on input\n");
      exit(-1);
    }

    tty_rmode.c_iflag &= ~IXON;
    if (tcsetattr(sfd, TCSANOW, &tty_rmode) < 0) {
      fprintf(stderr, "Cannot disable terminal's flow control on output\n");
      exit(-1);
    }
  }

#ifdef DEBUG
  if (tcgetattr(sfd, &tty_rmode) < 0) {
    fprintf(stderr, "Cannot get terminals current mode\n");
    exit(-1);
  }
  show_terminal_settings(&tty_rmode);
#endif

  return sfd;
}
int
main (int argc, char *argv [])
{	SNDFILE	*infile, *outfile = NULL ;
	SF_INFO sfinfo ;

	int normalize = 1 ;
	sf_count_t	count ;
	double		src_ratio = -1.0, gain = 1.0 ;
	int			new_sample_rate = -1, k, converter, max_speed = SF_FALSE ;

	if (argc == 2 && strcmp (argv [1], "--version") == 0)
	{	char buffer [64], *cptr ;

		if ((cptr = strrchr (argv [0], '/')) != NULL)
			argv [0] = cptr + 1 ;
		if ((cptr = strrchr (argv [0], '\\')) != NULL)
			argv [0] = cptr + 1 ;

		sf_command (NULL, SFC_GET_LIB_VERSION, buffer, sizeof (buffer)) ;

		printf ("%s (%s,%s)\n", argv [0], src_get_version (), buffer) ;
		exit (0) ;
		} ;

	if (argc != 5 && argc != 7 && argc != 8)
		usage_exit (argv [0]) ;

	/* Set default converter. */
	converter = DEFAULT_CONVERTER ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (strcmp (argv [k], "--max-speed") == 0)
			max_speed = SF_TRUE ;
		else if (strcmp (argv [k], "--no-normalize") == 0)
			normalize = 0 ;
		else if (strcmp (argv [k], "-to") == 0)
		{	k ++ ;
			new_sample_rate = atoi (argv [k]) ;
			}
		else if (strcmp (argv [k], "-by") == 0)
		{	k ++ ;
			src_ratio = atof (argv [k]) ;
			}
		else if (strcmp (argv [k], "-c") == 0)
		{	k ++ ;
			converter = atoi (argv [k]) ;
			}
		else
			usage_exit (argv [0]) ;
		} ;

	if (new_sample_rate <= 0 && src_ratio <= 0.0)
		usage_exit (argv [0]) ;

	if (src_get_name (converter) == NULL)
	{	printf ("Error : bad converter number.\n") ;
		usage_exit (argv [0]) ;
		} ;

	if (strcmp (argv [argc - 2], argv [argc - 1]) == 0)
	{	printf ("Error : input and output file names are the same.\n") ;
		exit (1) ;
		} ;

	if ((infile = sf_open (argv [argc - 2], SFM_READ, &sfinfo)) == NULL)
	{	printf ("Error : Not able to open input file '%s'\n", argv [argc - 2]) ;
		exit (1) ;
		} ;

	printf ("Input File    : %s\n", argv [argc - 2]) ;
	printf ("Sample Rate   : %d\n", sfinfo.samplerate) ;
	printf ("Input Frames  : %ld\n\n", (long) sfinfo.frames) ;

	if (new_sample_rate > 0)
	{	src_ratio = (1.0 * new_sample_rate) / sfinfo.samplerate ;
		sfinfo.samplerate = new_sample_rate ;
		}
	else if (src_is_valid_ratio (src_ratio))
		sfinfo.samplerate = (int) floor (sfinfo.samplerate * src_ratio) ;
	else
	{	printf ("Not able to determine new sample rate. Exiting.\n") ;
		sf_close (infile) ;
		exit (1) ;
		} ;

	if (fabs (src_ratio - 1.0) < 1e-20)
	{	printf ("Target samplerate and input samplerate are the same. Exiting.\n") ;
		sf_close (infile) ;
		exit (0) ;
		} ;

	printf ("SRC Ratio     : %f\n", src_ratio) ;
	printf ("Converter     : %s\n\n", src_get_name (converter)) ;

	if (src_is_valid_ratio (src_ratio) == 0)
	{	printf ("Error : Sample rate change out of valid range.\n") ;
		sf_close (infile) ;
		exit (1) ;
		} ;

	/* Delete the output file length to zero if already exists. */
	remove (argv [argc - 1]) ;

	printf ("Output file   : %s\n", argv [argc - 1]) ;
	printf ("Sample Rate   : %d\n", sfinfo.samplerate) ;

	do
	{	sf_close (outfile) ;

		if ((outfile = sf_open (argv [argc - 1], SFM_WRITE, &sfinfo)) == NULL)
		{	printf ("Error : Not able to open output file '%s'\n", argv [argc - 1]) ;
			sf_close (infile) ;
			exit (1) ;
			} ;

		if (max_speed)
		{	/* This is mainly for the comparison program tests/src-evaluate.c */
			sf_command (outfile, SFC_SET_ADD_PEAK_CHUNK, NULL, SF_FALSE) ;
			}
		else
		{	/* Update the file header after every write. */
			sf_command (outfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) ;
			} ;

		sf_command (outfile, SFC_SET_CLIPPING, NULL, SF_TRUE) ;

		count = sample_rate_convert (infile, outfile, converter, src_ratio, sfinfo.channels, &gain, normalize) ;
		}
	while (count < 0) ;

	printf ("Output Frames : %ld\n\n", (long) count) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Beispiel #11
0
int main(int argc, char **argv)
{
  int childpid;
  int sfd = -1;
  int fd;
  char *p, *ptyslave=NULL;
  int i = 1;
  int off_argv;
  int calculated_pipename = 0;
  int highest_pipe_num = 0;

  program_name = argv[0];

  if(argc<4) {
    usage(argv[0]);
    exit(1);
  }

  init_outbuf();

  if (!strcmp(argv[1],"-daemon")) {
      daemon_init();
      ++i;
  }

  off_argv = i;
  strn_cpy(pipename, sizeof(pipename), argv[i++]);
  strn_cpy(log_dir, sizeof(log_dir), argv[i]);
  strn_cpy(statusfile, sizeof(statusfile), log_dir);
  strn_cat(statusfile, sizeof(statusfile), STATUSFILENAME);

#ifdef DEBUG
  status("%s: pid is : %d\n", argv[0], getpid());
#endif

  /* Get values for LOG file handling from the environment */
  if ((p = getenv("RUN_ERL_LOG_ALIVE_MINUTES"))) {
      log_alive_minutes = atoi(p);
      if (!log_alive_minutes) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ALIVE_MINUTES is 1 "
		 "(current value is %s)",p);
      }
      log_activity_minutes = log_alive_minutes / 3;
      if (!log_activity_minutes) {
	  ++log_activity_minutes;
      }
  }
  if ((p = getenv("RUN_ERL_LOG_ACTIVITY_MINUTES"))) {
     log_activity_minutes = atoi(p);
      if (!log_activity_minutes) {
	  ERROR1(LOG_ERR,"Minimum value for RUN_ERL_LOG_ACTIVITY_MINUTES is 1 "
		 "(current value is %s)",p);
      }
  } 
  if ((p = getenv("RUN_ERL_LOG_ALIVE_FORMAT"))) {
      if (strlen(p) > ALIVE_BUFFSIZ) {
	  ERROR1(LOG_ERR, "RUN_ERL_LOG_ALIVE_FORMAT can contain a maximum of "
		 "%d characters", ALIVE_BUFFSIZ);
      }
      strn_cpy(log_alive_format, sizeof(log_alive_format), p);
  } else {
      strn_cpy(log_alive_format, sizeof(log_alive_format), DEFAULT_LOG_ALIVE_FORMAT);
  }
  if ((p = getenv("RUN_ERL_LOG_ALIVE_IN_UTC")) && strcmp(p,"0")) {
      ++log_alive_in_gmt;
  }
  if ((p = getenv("RUN_ERL_LOG_GENERATIONS"))) {
    log_generations = atoi(p);
    if (log_generations < LOG_MIN_GENERATIONS)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_GENERATIONS is %d", LOG_MIN_GENERATIONS);
    if (log_generations > LOG_MAX_GENERATIONS)
      ERROR1(LOG_ERR,"Maximum RUN_ERL_LOG_GENERATIONS is %d", LOG_MAX_GENERATIONS);
  }

  if ((p = getenv("RUN_ERL_LOG_MAXSIZE"))) {
    log_maxsize = atoi(p);
    if (log_maxsize < LOG_MIN_MAXSIZE)
      ERROR1(LOG_ERR,"Minimum RUN_ERL_LOG_MAXSIZE is %d", LOG_MIN_MAXSIZE);
  }

  /*
   * Create FIFOs and open them 
   */

  if(*pipename && pipename[strlen(pipename)-1] == '/') {
    /* The user wishes us to find a unique pipe name in the specified */
    /* directory */
    DIR *dirp;
    struct dirent *direntp;

    calculated_pipename = 1;
    dirp = opendir(pipename);
    if(!dirp) {
      ERRNO_ERR1(LOG_ERR,"Can't access pipe directory '%s'.", pipename);
      exit(1);
    }

    /* Check the directory for existing pipes */
    
    while((direntp=readdir(dirp)) != NULL) {
      if(strncmp(direntp->d_name,PIPE_STUBNAME,PIPE_STUBLEN)==0) {
	int num = atoi(direntp->d_name+PIPE_STUBLEN+1);
	if(num > highest_pipe_num)
	  highest_pipe_num = num;
      }
    }	
    closedir(dirp);
    strn_catf(pipename, sizeof(pipename), "%s.%d",
	      PIPE_STUBNAME, highest_pipe_num+1);
  } /* if */

  for(;;) {
      /* write FIFO - is read FIFO for `to_erl' program */
      strn_cpy(fifo1, sizeof(fifo1), pipename);
      strn_cat(fifo1, sizeof(fifo1), ".r");
      if (create_fifo(fifo1, PERM) < 0) {
	  ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for writing.", fifo1);
	  exit(1);
      }
      
      /* read FIFO - is write FIFO for `to_erl' program */
      strn_cpy(fifo2, sizeof(fifo2), pipename);
      strn_cat(fifo2, sizeof(fifo2), ".w");
      
      /* Check that nobody is running run_erl already */
      if ((fd = sf_open(fifo2, O_WRONLY|DONT_BLOCK_PLEASE, 0)) >= 0) {
	  /* Open as client succeeded -- run_erl is already running! */
	  sf_close(fd);
	  if (calculated_pipename) {
	      ++highest_pipe_num;
	      strn_catf(pipename, sizeof(pipename), "%s.%d",
			PIPE_STUBNAME, highest_pipe_num+1);
	      continue;
	  } 
	  fprintf(stderr, "Erlang already running on pipe %s.\n", pipename);
	  exit(1);
      }
      if (create_fifo(fifo2, PERM) < 0) { 
	  ERRNO_ERR1(LOG_ERR,"Cannot create FIFO %s for reading.", fifo2);
	  exit(1);
      }
      break;
  }

  /*
   * Open master pseudo-terminal
   */

  if ((mfd = open_pty_master(&ptyslave, &sfd)) < 0) {
    ERRNO_ERR0(LOG_ERR,"Could not open pty master");
    exit(1);
  }

  /* 
   * Now create a child process
   */

  if ((childpid = fork()) < 0) {
    ERRNO_ERR0(LOG_ERR,"Cannot fork");
    exit(1);
  }
  if (childpid == 0) {
    /* Child */
    sf_close(mfd);
    /* disassociate from control terminal */
#ifdef USE_SETPGRP_NOARGS       /* SysV */
    setpgrp();
#elif defined(USE_SETPGRP)       /* BSD */
    setpgrp(0,getpid());
#else                           /* POSIX */
    setsid();
#endif
    /* Open the slave pty */
    if (sfd < 0) {
	/* not allocated by open_pty_master */
	if ((sfd = open_pty_slave(ptyslave)) < 0) {
	    ERRNO_ERR1(LOG_ERR,"Could not open pty slave '%s'", ptyslave);
	    exit(1);
	}
	/* But sfd may be one of the stdio fd's now, and we should be unmodern and not use dup2... */
	/* easiest to dup it up... */
	while (sfd < 3) {
	    sfd = dup(sfd);
	}
    }
#if defined(HAVE_OPENPTY) && defined(TIOCSCTTY)
    else {
	/* sfd is from open_pty_master 
	 * openpty -> fork -> login_tty (forkpty)
	 * 
	 * It would be preferable to implement a portable 
	 * forkpty instead of open_pty_master / open_pty_slave
	 */
	/* login_tty(sfd);  <- FAIL */
	ioctl(sfd, TIOCSCTTY, (char *)NULL);
    }
#endif

#ifndef NO_SYSLOG
    /* Before fiddling with file descriptors we make sure syslog is turned off
       or "closed". In the single case where we might want it again, 
       we will open it again instead. Would not want syslog to
       go to some other fd... */
    if (run_daemon) {
	closelog();
    }
#endif

    /* Close stdio */
    sf_close(0);
    sf_close(1);
    sf_close(2);

    if (dup(sfd) != 0 || dup(sfd) != 1 || dup(sfd) != 2) {
      status("Cannot dup\n");
    }
    sf_close(sfd);
    exec_shell(argv+off_argv); /* exec_shell expects argv[2] to be */
                        /* the command name, so we have to */
                        /* adjust. */
  } else {
    /* Parent */
    /* Ignore the SIGPIPE signal, write() will return errno=EPIPE */
    struct sigaction sig_act;
    sigemptyset(&sig_act.sa_mask);
    sig_act.sa_flags = 0;
    sig_act.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &sig_act, (struct sigaction *)NULL);

    sigemptyset(&sig_act.sa_mask);
    sig_act.sa_flags = SA_NOCLDSTOP;
    sig_act.sa_handler = catch_sigchild;
    sigaction(SIGCHLD, &sig_act, (struct sigaction *)NULL);

    /*
     * read and write: enter the workloop
     */

    pass_on(childpid);
  }
  return 0;
} /* main() */
Beispiel #12
0
int
main (int argc, char * argv [])
{	char 		*progname, *infilename, *outfilename ;
	SNDFILE	 	*infile = NULL, *outfile = NULL ;
	SF_INFO	 	sfinfo ;
	int			k, outfilemajor, outfileminor = 0, infileminor ;
	int			override_sample_rate = 0 ; /* assume no sample rate override. */

	progname = strrchr (argv [0], '/') ;
	progname = progname ? progname + 1 : argv [0] ;

	if (argc < 3 || argc > 5)
	{	print_usage (progname) ;
		return 1 ;
		} ;

	infilename = argv [argc-2] ;
	outfilename = argv [argc-1] ;

	if (strcmp (infilename, outfilename) == 0)
	{	printf ("Error : Input and output filenames are the same.\n\n") ;
		print_usage (progname) ;
		return 1 ;
		} ;

	if (strlen (infilename) > 1 && infilename [0] == '-')
	{	printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
		print_usage (progname) ;
		return 1 ;
		} ;

	if (outfilename [0] == '-')
	{	printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
		print_usage (progname) ;
		return 1 ;
		} ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (! strcmp (argv [k], "-pcms8"))
		{	outfileminor = SF_FORMAT_PCM_S8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcmu8"))
		{	outfileminor = SF_FORMAT_PCM_U8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm16"))
		{	outfileminor = SF_FORMAT_PCM_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm24"))
		{	outfileminor = SF_FORMAT_PCM_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm32"))
		{	outfileminor = SF_FORMAT_PCM_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-float32"))
		{	outfileminor = SF_FORMAT_FLOAT ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ulaw"))
		{	outfileminor = SF_FORMAT_ULAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alaw"))
		{	outfileminor = SF_FORMAT_ALAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ima-adpcm"))
		{	outfileminor = SF_FORMAT_IMA_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ms-adpcm"))
		{	outfileminor = SF_FORMAT_MS_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-gsm610"))
		{	outfileminor = SF_FORMAT_GSM610 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw12"))
		{	outfileminor = SF_FORMAT_DWVW_12 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw16"))
		{	outfileminor = SF_FORMAT_DWVW_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw24"))
		{	outfileminor = SF_FORMAT_DWVW_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-vorbis"))
		{	outfileminor = SF_FORMAT_VORBIS ;
			continue ;
			} ;

		if (strstr (argv [k], "-override-sample-rate=") == argv [k])
		{	const char *ptr ;

			ptr = argv [k] + strlen ("-override-sample-rate=") ;
			override_sample_rate = atoi (ptr) ;
			continue ;
			} ;

		printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
		exit (1) ;
		} ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	if ((infile = sf_open (infilename, SFM_READ, &sfinfo)) == NULL)
	{	printf ("Not able to open input file %s.\n", infilename) ;
		puts (sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Update sample rate if forced to something else. */
	if (override_sample_rate)
		sfinfo.samplerate = override_sample_rate ;

	infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)
	{	printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
		return 1 ;
		} ;

	outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;

	if (outfileminor == 0)
		outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if (outfileminor != 0)
		sfinfo.format = outfilemajor | outfileminor ;
	else
		sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;

	if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_PCM_16 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
					break ;

			case SF_FORMAT_PCM_S8 :
			case SF_FORMAT_PCM_U8 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
					break ;
			} ;

	if (sf_format_check (&sfinfo) == 0)
	{	printf ("Error : output file format is invalid (0x%08X).\n", sfinfo.format) ;
		return 1 ;
		} ;

	/* Open the output file. */
	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Copy the metadata */
	copy_metadata (outfile, infile, sfinfo.channels) ;

	if ((outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))
		sfe_copy_data_fp (outfile, infile, sfinfo.channels) ;
	else
		sfe_copy_data_int (outfile, infile, sfinfo.channels) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Beispiel #13
0
bool TransientExtractor::remove_transients( const char *outfilename, std::vector< uint > rmindexs )
{
    TransLoc tl;
    int tranLen, gapLen, postgapLen, overlap, pad = allowableGap / 4, tstart, mingapLen;
    //float prenoise, postnoise, noise;
    //int count, noiselen = allowableGap; 

    Treesynth ts;
    Tree * ts_tree = NULL; // gets deleted from inside treesynth
    int levels;
    SAMPLE * syn;

    SAMPLE * buffer = NULL;

    // Read original file
    AudioSrcFile * orig = new AudioSrcFile;
    orig->open( filename.c_str(), 0, 0, FALSE );
    uint size = orig->info().frames;
    SAMPLE * working = new SAMPLE[size];
    orig->mtick( working, size );

    // Open output file
    SF_INFO sf_info_write = orig->info();
    sf_info_write.channels = 1;
    SNDFILE * out = sf_open( outfilename, SFM_WRITE, &sf_info_write );

    // "bitmap" of transients
    bool * bmp = new bool[size];
    for( int b = 0; b < size; b++ ) 
        bmp[b] = false;
    for( int t = 0; t < transients.size(); t++ )
    {
        tl = transients[t]; 
        for( int b = estart + tl.start; b < estart + tl.end; b++ )
            bmp[b] = true;
    }

    for( int r = 0; r < rmindexs.size(); r++ )
    {
        tl = transients[rmindexs[r]];
        tstart = tl.start - pad; 
        if( tstart < 0 ) tstart = 0;
        tranLen = tl.end - tstart;
        mingapLen = tranLen/4; 
        
        // inefficiently find size of nearest preceding transient-free zone
        int e = estart + tstart;
        gapLen = 0;
        while( gapLen < 2 * tranLen && e > 0 )
        {
            e--;
            if( !bmp[e] )
                gapLen++;
            else if( gapLen <= mingapLen )
                gapLen = 0;
            else
                break;
        }

        // and nearest _next_ free zone
        int f = estart + tl.end;
        postgapLen = 0;
        while( postgapLen < 2 * tranLen && f < size-1 )
        {
            f++;
            if( !bmp[f] )
                postgapLen++;
            else if( postgapLen <= mingapLen )
                postgapLen = 0;
            else 
                break;
        }

        // find final gap length
        bool pre = false, post = false;
        if( postgapLen <= mingapLen )
        {
            pre = true;
        }
        else if( gapLen <= mingapLen )
        {
            post = true;
            gapLen = postgapLen;
        }
        else
            gapLen = postgapLen < gapLen ? postgapLen : gapLen;
        
        
        fprintf( stderr, "%s %s %i %i %i\n", pre ? "true" : "false", post ? "true" : "false", gapLen, 2*tranLen, mingapLen ); 

        if( gapLen <= 0 )
            continue;

        // add non-trans zones
        SAFE_DELETE_ARRAY( buffer );
        buffer = new SAMPLE[gapLen];
        for( int g = 0; g < gapLen; g++ )
        {
            if( pre )
                buffer[g] = working[e + g];
            else if( post )
                buffer[g] = working[f - postgapLen + g];
            else
                buffer[g] = (working[e + g] + working[f - postgapLen + g]) * 0.7;
        }

        levels = lg( gapLen );
        gapLen = ::pow(2, levels);
        overlap = gapLen / 2;

        // zero out transient
        memset( working + estart + tstart, 0, tranLen * sizeof( SAMPLE ) );

        // treesynth
        SAFE_DELETE( ts_tree );
        ts_tree = new Tree;
        ts_tree->initialize( levels );
        //memcpy( ts_tree->values(), working + e, gapLen * sizeof( SAMPLE ) );
        memcpy( ts_tree->values(), buffer, gapLen * sizeof( SAMPLE ) );
        ts.tree = ts_tree;
        ts.initialize();
        ts.percentage = 0.8;
        ts.randflip = true;
        ts.stoplevel = 10; // if that's too big, it will stop at the last level automatically

        bool done = false;
        int index = estart + tstart - overlap; 
        if( index < 0 ) index = 0;
        
        if( !ts.setup() ) return false;

        while( !done )
        {
            fprintf( stderr, "a tree " );   
            ts.synth();
            syn = ts.outputSignal();

            // overlap add synthesized signal into working buffer
            for( int i = 0; i < gapLen; i++ )
            {
                if( index + i < size )
                {
                    if( index + i < estart + tstart || index + i >= estart + tl.end )
                        working[index + i] *= 0.5; 
                    working[index + i] += 0.5 * syn[i];
    
                    //working[index + i] += syn[i];
                    //working[index + i] = 0.5 * working[index + i] + 0.5 * syn[i];
                }
                else
                    break;
            }

            index += (gapLen - overlap);
            if( index >= estart + tl.end )
                done = true;
        }
        
        // noise floor?
        /*prenoise = postnoise = noise = 0;
        count = 0;
        int n;
        for( n = estart + tstart <= noiselen ? 0 : estart + tstart - noiselen; 
             n < estart + tstart; 
             n++, count++ )
        {
            prenoise += fabs(working[n]);
        }
        prenoise /= (count > 0 ? count : 1);
        for( n = estart + tl.end, count = 0; 
             n < size && n < estart + tl.end + noiselen; 
             n++, count++ )
        {
            postnoise += fabs(working[n]);
        }
        postnoise /= (count > 0 ? count : 1);
        for( n = estart + tstart, count = 0; n < estart + tl.end; n++, count++ )
        {
            noise += fabs(working[n]);
        }
        noise /= (count > 0 ? count : 1);
        float slope = (postnoise - prenoise)/tranLen;
        if( noise != 0 ) slope /= noise;
        for( n = tstart; n < tl.end; n++ )
        {
            working[estart + n] *= ( slope * n + prenoise );
        }*/

        // sigh of relief
        fprintf( stderr, "\n\n" );
    }

    // Write out working
    sf_count_t write = sf_write_float( out, working, size );

    // Close stuff
    sf_close( out );
    SAFE_DELETE_ARRAY( working ); 
    SAFE_DELETE_ARRAY( buffer );

    return true;
}
Beispiel #14
0
SC_DLLEXPORT_C void World_NonRealTimeSynthesis(struct World *world, WorldOptions *inOptions)
{
	if (inOptions->mLoadGraphDefs) {
		World_LoadGraphDefs(world);
	}
	int bufLength = world->mBufLength;
	int fileBufFrames = inOptions->mPreferredHardwareBufferFrameSize;
	if (fileBufFrames <= 0) fileBufFrames = 8192;
	int bufMultiple = (fileBufFrames + bufLength - 1) / bufLength;
	fileBufFrames = bufMultiple * bufLength;

	// batch process non real time audio
	if (!inOptions->mNonRealTimeOutputFilename)
		throw std::runtime_error("Non real time output filename is NULL.\n");

	SF_INFO inputFileInfo, outputFileInfo;
	float *inputFileBuf = 0;
	float *outputFileBuf = 0;
	int numInputChannels = 0;
	int numOutputChannels;

	outputFileInfo.samplerate = inOptions->mPreferredSampleRate;
	numOutputChannels = outputFileInfo.channels = world->mNumOutputs;
	sndfileFormatInfoFromStrings(&outputFileInfo,
		inOptions->mNonRealTimeOutputHeaderFormat, inOptions->mNonRealTimeOutputSampleFormat);

	world->hw->mNRTOutputFile = sf_open(inOptions->mNonRealTimeOutputFilename, SFM_WRITE, &outputFileInfo);
	sf_command(world->hw->mNRTOutputFile, SFC_SET_CLIPPING, NULL, SF_TRUE);

	if (!world->hw->mNRTOutputFile)
		throw std::runtime_error("Couldn't open non real time output file.\n");

	outputFileBuf = (float*)calloc(1, world->mNumOutputs * fileBufFrames * sizeof(float));

	if (inOptions->mNonRealTimeInputFilename) {
		world->hw->mNRTInputFile = sf_open(inOptions->mNonRealTimeInputFilename, SFM_READ, &inputFileInfo);
		if (!world->hw->mNRTInputFile)
			throw std::runtime_error("Couldn't open non real time input file.\n");

		inputFileBuf = (float*)calloc(1, inputFileInfo.channels * fileBufFrames * sizeof(float));

		if (world->mNumInputs != (uint32)inputFileInfo.channels)
			scprintf("WARNING: input file channels didn't match number of inputs specified in options.\n");

		numInputChannels = world->mNumInputs = inputFileInfo.channels; // force it.

		if (inputFileInfo.samplerate != (int)inOptions->mPreferredSampleRate)
			scprintf("WARNING: input file sample rate does not equal output sample rate.\n");

	} else {
		world->hw->mNRTInputFile = 0;
	}

	FILE *cmdFile;
	if (inOptions->mNonRealTimeCmdFilename) {
#ifdef _WIN32
		cmdFile = fopen(inOptions->mNonRealTimeCmdFilename, "rb");
#else
		cmdFile = fopen(inOptions->mNonRealTimeCmdFilename, "r");
#endif
	} else cmdFile = stdin;
	if (!cmdFile)
		throw std::runtime_error("Couldn't open non real time command file.\n");

	char msgbuf[8192];
	OSC_Packet packet;
	memset(&packet, 0, sizeof(packet));
	packet.mData = msgbuf;
	packet.mIsBundle = true;
	packet.mReplyAddr.mReplyFunc = null_reply_func;

	int64 schedTime;
	if (nextOSCPacket(cmdFile, &packet, schedTime))
		throw std::runtime_error("command file empty.\n");
	int64 prevTime = schedTime;

	World_SetSampleRate(world, inOptions->mPreferredSampleRate);
	World_Start(world);

	int64 oscTime = 0;
        double oscToSeconds = 1. / pow(2.,32.);
	double oscToSamples = inOptions->mPreferredSampleRate * oscToSeconds;
	int64 oscInc = (int64)((double)bufLength / oscToSamples);

	if(inOptions->mVerbosity >= 0) {
        printf("start time %g\n", schedTime * oscToSeconds);
	}

	bool run = true;
	int inBufStep = numInputChannels * bufLength;
	int outBufStep = numOutputChannels * bufLength;
	float* inputBuses    = world->mAudioBus + world->mNumOutputs * bufLength;
	float* outputBuses   = world->mAudioBus;
	int32* inputTouched  = world->mAudioBusTouched + world->mNumOutputs;
	int32* outputTouched = world->mAudioBusTouched;
	for (; run;) {
		int bufFramesCalculated = 0;
		float* inBufPos = inputFileBuf;
		float* outBufPos = outputFileBuf;

		if (world->hw->mNRTInputFile) {
			int framesRead = sf_readf_float(world->hw->mNRTInputFile, inputFileBuf, fileBufFrames);
			if (framesRead < fileBufFrames) {
				memset(inputFileBuf + framesRead * numInputChannels, 0,
					(fileBufFrames - framesRead) * numInputChannels * sizeof(float));
			}
		}

		for (int i=0; i<bufMultiple && run; ++i) {
			int bufCounter = world->mBufCounter;

			// deinterleave input to input buses
			if (inputFileBuf) {
				float *inBus = inputBuses;
				for (int j=0; j<numInputChannels; ++j, inBus += bufLength) {
					float *inFileBufPtr = inBufPos + j;
					for (int k=0; k<bufLength; ++k) {
						inBus[k] = *inFileBufPtr;
						inFileBufPtr += numInputChannels;
					}
					inputTouched[j] = bufCounter;
				}
			}

			// execute ready commands
			int64 nextTime = oscTime + oscInc;

			while (schedTime <= nextTime) {
				float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5;
				float diffTimeFloor = floor(diffTime);
				world->mSampleOffset = (int)diffTimeFloor;
				world->mSubsampleOffset = diffTime - diffTimeFloor;

				if (world->mSampleOffset < 0) world->mSampleOffset = 0;
				else if (world->mSampleOffset >= bufLength) world->mSampleOffset = bufLength-1;


				PerformOSCBundle(world, &packet);
				if (nextOSCPacket(cmdFile, &packet, schedTime)) { run = false; break; }
				if(inOptions->mVerbosity >= 0) {
					printf("nextOSCPacket %g\n", schedTime * oscToSeconds);
				}
				if (schedTime < prevTime) {
					scprintf("ERROR: Packet time stamps out-of-order.\n");
					run = false;
					goto Bail;
				}
				prevTime = schedTime;
			}

			World_Run(world);

			// interleave output to output buffer
			float *outBus = outputBuses;
			for (int j=0; j<numOutputChannels; ++j, outBus += bufLength) {
				float *outFileBufPtr = outBufPos + j;
				if (outputTouched[j] == bufCounter) {
					for (int k=0; k<bufLength; ++k) {
						*outFileBufPtr = outBus[k];
						outFileBufPtr += numOutputChannels;
					}
				} else {
					for (int k=0; k<bufLength; ++k) {
						*outFileBufPtr = 0.f;
						outFileBufPtr += numOutputChannels;
					}
				}
			}
			bufFramesCalculated += bufLength;
			inBufPos += inBufStep;
			outBufPos += outBufStep;
			world->mBufCounter++;
			oscTime = nextTime;
		}

Bail:
		// write output
		sf_writef_float(world->hw->mNRTOutputFile, outputFileBuf, bufFramesCalculated);
	}

	if (cmdFile != stdin) fclose(cmdFile);
	sf_close(world->hw->mNRTOutputFile);
	world->hw->mNRTOutputFile = 0;

	if (world->hw->mNRTInputFile) {
		sf_close(world->hw->mNRTInputFile);
		world->hw->mNRTInputFile = 0;
	}

	World_Cleanup(world);
}
Beispiel #15
0
bool
wf_ff_peakgen(const char* infilename, const char* peak_filename)
{
    WfDecoder f = {{0,}};

    if(!ad_open(&f, infilename)) return false;

    SNDFILE* outfile;
    SF_INFO sfinfo = {
        .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16,
        .channels = f.info.channels,
        .samplerate = f.info.sample_rate,
    };

    gchar* basename = g_path_get_basename(peak_filename);
    gchar* tmp_path = g_build_filename("/tmp", basename, NULL);
    g_free(basename);

    if(!(outfile = sf_open(tmp_path, SFM_WRITE, &sfinfo))) {
        printf ("Not able to open output file %s.\n", tmp_path);
        puts(sf_strerror(NULL));
        return false;
    }

    int total_frames_written = 0;
    WfPeakSample total[sfinfo.channels];
    memset(total, 0, sizeof(WfPeakSample) * sfinfo.channels);

    int n = 8;
    int read_len = WF_PEAK_RATIO * n;
    float* sf_data = g_malloc(sizeof(float) * read_len);

    int16_t data[f.info.channels][read_len];
    WfBuf16 buf = {
        .buf = {
            data[0], data[1]
        },
        .size = n * WF_PEAK_RATIO
    };

    int readcount;
    int total_readcount = 0;
    do {
        readcount = ad_read_short(&f, &buf);
        total_readcount += readcount;
        int remaining = readcount;

        WfPeakSample peak[sfinfo.channels];

        int j = 0;
        for(; j<n; j++) {
            WfPeakSample w[sfinfo.channels];

            memset(peak, 0, sizeof(WfPeakSample) * sfinfo.channels);

            int k;
            for (k = 0; k < MIN(remaining, WF_PEAK_RATIO); k+=sfinfo.channels) {
                int c;
                for(c=0; c<sfinfo.channels; c++) {
                    int16_t val = buf.buf[c][WF_PEAK_RATIO * j + k];
                    peak[c] = (WfPeakSample) {
                        MAX(peak[c].positive, val),
                            MIN(peak[c].negative, MAX(val, -32767)), // TODO value of SHRT_MAX messes up the rendering - why?
                    };
                }
            };
            remaining -= WF_PEAK_RATIO;
            int c;
            for(c=0; c<sfinfo.channels; c++) {
                w[c] = peak[c];
                total[c] = (WfPeakSample) {
                    MAX(total[c].positive, w[c].positive),
                        MIN(total[c].negative, w[c].negative),
                };
            }
            total_frames_written += sf_writef_short (outfile, (short*)w, WF_PEAK_VALUES_PER_SAMPLE);
        }
    } while (readcount > 0);


#if 0
    if(f.info.channels > 1) dbg(0, "max=%i,%i min=%i,%i", total[0].positive, total[1].positive, total[0].negative, total[1].negative);
    else dbg(0, "max=%i min=%i", total[0].positive, total[0].negative);
#endif

#ifdef DEBUG
    if(g_str_has_suffix(infilename, ".mp3")) {
        dbg(1, "mp3");
        f.info.frames = total_readcount; // update the estimate with the real frame count.
    }
#else
    if(total_frames_written / WF_PEAK_VALUES_PER_SAMPLE != f.info.frames / WF_PEAK_RATIO) {
        gwarn("unexpected number of frames: %i != %Lu", total_frames_written  / WF_PEAK_VALUES_PER_SAMPLE, f.info.frames / WF_PEAK_RATIO);
    }
#endif

    ad_close(&f);
    sf_close (outfile);
    g_free(sf_data);

    int renamed = !rename(tmp_path, peak_filename);
    g_free(tmp_path);
    if(!renamed) return false;

    return true;
}
Beispiel #16
0
int main(int argc, char **argv)
{
   SNDFILE *srcfile, *dstfile;
   SF_INFO srcinfo, dstinfo;
   SF_FORMAT_INFO formatinfo;
   char *extension;
   void **handle;
   int channels;
   int srclen, dstlen;
   float *src, *srci;
   float *dst, *dsti;
   double ratio = 0.0;
   double srcrate;
   double dstrate = 0.0;
   struct timeval tv0, tv1;
   double deltat;
   int numformats;
   int pos, bufferpos, outcount;
   int i, c;

   if (argc != 5)
      usage(argv[0]);

   if (!strcmp(argv[1], "-by")) {
      ratio = atof(argv[2]);
      if (ratio <= 0.0) {
         fprintf(stderr, "Ratio of %f is illegal\n", ratio);
         usage(argv[0]);
      }
   }
   else if (!strcmp(argv[1], "-to")) {
      dstrate = atof(argv[2]);
      if (dstrate < 10.0 || dstrate > 100000.0) {
         fprintf(stderr, "Sample rate of %f is illegal\n", dstrate);
         usage(argv[0]);
      }
   }
   else
      usage(argv[0]);

   memset(&srcinfo, 0, sizeof(srcinfo));
   memset(&dstinfo, 0, sizeof(dstinfo));
   srcfile = sf_open(argv[3], SFM_READ, &srcinfo);
   if (!srcfile) {
      fprintf(stderr, "%s", sf_strerror(NULL));
      exit(-1);
   }

   srcrate = srcinfo.samplerate;
   if (dstrate == 0.0)
      dstrate = srcrate * ratio;
   else
      ratio = dstrate / srcrate;

   channels = srcinfo.channels;

   /* figure out format of destination file */

   extension = strstr(argv[4], ".");
   if (extension) {
      extension++;
      sf_command(NULL, SFC_GET_FORMAT_MAJOR_COUNT,
                 &numformats, sizeof(numformats));
      for(i=0; i<numformats; i++) {
         memset(&formatinfo, 0, sizeof(formatinfo));
         formatinfo.format = i;
         sf_command(NULL, SFC_GET_FORMAT_MAJOR,
                    &formatinfo, sizeof(formatinfo));
         if (!strcmp(formatinfo.extension, extension)) {
            printf("Using %s for output format.\n", formatinfo.name);
            dstinfo.format = formatinfo.format |
               (srcinfo.format & SF_FORMAT_SUBMASK);
            break;
         }            
      }
   }

   if (!dstinfo.format) {
      if (extension)
         printf("Warning: output format (%s) not recognized, "
                "using same as input format.\n",
                extension);
      dstinfo.format = srcinfo.format;
   }

   dstinfo.samplerate = (int)(dstrate + 0.5);
   dstinfo.channels = channels;

   dstfile = sf_open(argv[4], SFM_WRITE, &dstinfo);
   if (!dstfile) {
      fprintf(stderr, "%s", sf_strerror(NULL));
      exit(-1);
   }

   printf("Source: %s (%d frames, %.2f Hz)\n",
          argv[3], (int)srcinfo.frames, srcrate);
   printf("Destination: %s (%.2f Hz, ratio=%.5f)\n", argv[4],
          dstrate, ratio);

   srclen = 4096;
   dstlen = (srclen * ratio + 1000);
   srci = (float *)malloc(srclen * channels * sizeof(float));
   dsti = (float *)malloc(dstlen * channels * sizeof(float));
   src = (float *)malloc(srclen * sizeof(float));
   dst = (float *)malloc(dstlen * sizeof(float));

   handle = (void **)malloc(channels * sizeof(void *));
   for(c=0; c<channels; c++)
      handle[c] = resample_open(1, ratio, ratio);

   gettimeofday(&tv0, NULL);

   pos = 0;
   bufferpos = 0;
   outcount = 0;
   while(pos < srcinfo.frames) {
      int block = MIN(srclen-bufferpos, srcinfo.frames-pos);
      int lastFlag = (pos+block == srcinfo.frames);
      int inUsed, inUsed2=0, out=0, out2=0;

      sf_readf_float(srcfile, &srci[bufferpos*channels], block);
      block += bufferpos;

      for(c=0; c<channels; c++) {
         for(i=0; i<block; i++)
            src[i] = srci[i*channels+c];

         inUsed = 0;
         out = resample_process(handle[c], ratio, src, block, lastFlag,
                                &inUsed, dst, dstlen);
         if (c==0) {
            inUsed2 = inUsed;
            out2 = out;
         }
         else {
            if (inUsed2 != inUsed || out2 != out) {
               fprintf(stderr, "Fatal error: channels out of sync!\n");
               exit(-1);
            }
         }

         for(i=0; i<out; i++)
            dsti[i*channels+c] = dst[i];
      }

      sf_writef_float(dstfile, dsti, out);

      bufferpos = block - inUsed;
      for(i=0; i<bufferpos*channels; i++)
         srci[i] = srci[i+(inUsed*channels)];
      pos += inUsed;
      outcount += out;
   }

   sf_close(srcfile);
   sf_close(dstfile);

   gettimeofday(&tv1, NULL);
   deltat =
      (tv1.tv_sec + tv1.tv_usec * 0.000001) -
      (tv0.tv_sec + tv0.tv_usec * 0.000001);

   printf("Elapsed time: %.3f seconds\n", deltat);
   printf("%d frames written to output file\n", outcount);

   free(src);
   free(srci);
   free(dst);
   free(dsti);

   exit(0);
}
Beispiel #17
0
main(int argc, char **argv){
    snd_pcm_t *handle;
    snd_pcm_hw_params_t *params;
    snd_pcm_uframes_t frames;
    //the libsamplerate stuff
    SRC_DATA datastr;//holds the data(inpu and output),input frames used, output frames generated 
    SRC_STATE *statestr;//holds the state
    int error;
    //the lbsndfile stuff, one keeps the header the other the data
    SF_INFO sfinf;//has all the info like total frames,samplerate, channels, mode
    SNDFILE *input = NULL;
    //buffers used in computation to pass to the playback function
    float *buffin = NULL;//float into the converter
    float *filein = NULL;
    float *flangebuffout = NULL;//float to traverse the array for getting flange effects
    float *flangebase = NULL;//float to fix the array for initialising the flange effects
    float *buffout = NULL;//float out of the converter
    short *final = NULL;//final array to write to snd card

    float fldelmax = 256;
    float flfreq = 1;
    float flgain = .5;
    int fltime = 0;


    int pcm, readcount, pcmrc, blah;//pcm is used for error checking the alsa stuff, pcmrc is used in the main loop
    float *eofin;//to point to the end of the file's raw data
    int tmp;//used to hold information that is printed in stdio
    int i = 0;//index for initialising the output DAC
   // float fldelmax, flgain, flfreq;
    // pointer for the file input
    if (argc != 3){
        printf("Usage requires music file and src ratio, please try again\n\n");
        return 0;
    }
    char *inputname = argv[1];
    //int *filein = argv[1];

    input = sf_open(inputname, SFM_READ, &sfinf);
    if (input == NULL){
        printf("could not open file sorry \n\n");
        return 0;
    }
    fprintf(stderr, "Channels : %d\n", sfinf.channels);
    fprintf(stderr, "Sample rate; %d\n", sfinf.samplerate);
    fprintf(stderr, "Sections: %d\n", sfinf.sections);
    fprintf(stderr, "Format: %d\n", sfinf.format);
   // fprintf(stderr, "Frame Count: %d\n", sfinf.frames);
    //fprintf(stderr, "size: %d\n", sizeof(short));
   //open sndcard
   if ((filein = malloc(sizeof(float)*sfinf.channels*sfinf.frames)) == NULL)
   {
       printf("MAN YOU OUT OF MEM");
       return 0;
   }
   blah = sf_readf_float(input, filein, sfinf.frames);
   buffin = filein;
   eofin = filein + (sfinf.frames)*sfinf.channels;




    if (pcm =snd_pcm_open(&handle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0)< 0){
        printf("Error: CANNOT OPEN PCM DEVICE\n");
    }

    //allocate default parameters
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(handle, params);
    //set parameters
    if (pcm = snd_pcm_hw_params_set_access(handle, params, SND_PCM_ACCESS_RW_INTERLEAVED)< 0){
        printf("Cannot set interleaved mode\n");
    }

    if (pcm = snd_pcm_hw_params_set_format(handle, params, SND_PCM_FORMAT_S16_LE)< 0){
        printf("CANNOT SET FORMAT\n");
    }
    if (pcm = snd_pcm_hw_params_set_channels(handle, params, sfinf.channels)< 0){
        printf("CANNOT SET CHANNELS \n");
    }
    if (pcm = snd_pcm_hw_params_set_rate(handle, params, sfinf.samplerate, 0)< 0){
        printf("CANNOT SET SAMPLERATES \n");
    }
    if (pcm = snd_pcm_hw_params_set_periods(handle, params,1024, 0) < 0){
        printf("CANNOT SET PERIOD TO 128");
    }

    //write parameters
    if (pcm = snd_pcm_hw_params(handle, params)< 0){
        printf("CANNOT SET HARDWARE PARAMETERS\n");
    }
    printf("PCm NAME: %s\n", snd_pcm_name(handle));
    printf("PCM state: %s \n", snd_pcm_state_name(snd_pcm_state(handle)));
    snd_pcm_hw_params_get_channels(params, &tmp);
    printf("channels: %i\n", tmp);
    snd_pcm_hw_params_get_rate(params, &tmp, 0);
    printf("rate: %d \n", tmp);
    //find size of period on hardware
    snd_pcm_hw_params_get_period_size(params, &frames, 0);
    fprintf(stderr, "# frames in a period: %d\n", frames);
  
    //buffers on buffers (buffout for float output from sample rate conversion), (final for short array to write to pcm) and flangebse for the flanger stuff
    
    buffout = malloc(frames*sfinf.channels * sizeof(float));//frames
    final = malloc(frames*sfinf.channels * sizeof(short));//frames
Beispiel #18
0
/* initialize patch
 * INPUT
 *   file_patch : filename
 *   plen : # of data in patch (wav)
 *   nwin : index of window
 * OUTPUT (extern values)
 *   pat[] : power of pat
 *   npat : # of data in pat[] ( = plen/2 +1 )
 *   p0 : maximun of power
 *   if0 : freq point of maximum
 */
void
init_patch (char *file_patch, int plen, int nwin)
{
  extern int patch_flg;
  extern double *pat;
  extern int npat; /* # of data in pat[]  */
  extern double p0; /* maximum power  */
  extern double if0; /* freq point of maximum  */
  
  int i;


  /* prepare patch  */
  if (file_patch == NULL)
    {
      patch_flg = 0;
      return;
    }
  else
    {
      /* allocate pat[]  */
      pat = (double *)malloc (sizeof (double) * (plen/2+1));
      if (pat == NULL)
	{
	  fprintf(stderr, "cannot allocate pat[%d]\n", (plen/2+1));
	  patch_flg = 0;
	  return;
	}

      double *x = NULL;
      double *xx = NULL;
      x  = (double *)malloc (sizeof (double) * plen);
      xx = (double *)malloc (sizeof (double) * plen);
      if (x == NULL || xx == NULL)
	{
	  fprintf(stderr, "cannot allocate x[%d]\n", plen);
	  patch_flg = 0;
	  return;
	}

      /* spectrum data for FFT */ 
      double *y = NULL;
      y = (double *)malloc (sizeof (double) * plen);
      if (y == NULL)
	{
	  fprintf(stderr, "cannot allocate y[%d]\n", plen);
	  patch_flg = 0;
	  free (x);
	  free (xx);
	  return;
	}

      /* open patch file  */
      SNDFILE *sf = NULL;
      SF_INFO sfinfo;
      sf = sf_open (file_patch, SFM_READ, &sfinfo);
      if (sf == NULL)
	{
	  fprintf (stderr, "Can't open patch file %s : %s\n",
		   file_patch, strerror (errno));
	  exit (1);
	}

      /* read patch wav  */
      if (sndfile_read (sf, sfinfo, x, xx, plen) != plen)
	{
	  fprintf (stderr, "No Patch Data!\n");
	  patch_flg = 0;
	  free (x);
	  free (xx);
	  free (y);
	  return;
	}
      if (sfinfo.channels == 2)
	{
	  for (i = 0; i < plen; i ++)
	    {
	      x[i] = 0.5 * (x[i] + xx[i]);
	    }
	}

      /* calc power of patch  */
      double den;
      den = init_den (plen, nwin);

#ifdef FFTW2
      rfftw_plan plan;
      plan = rfftw_create_plan (plen, FFTW_REAL_TO_COMPLEX, FFTW_ESTIMATE);
#else
      fftw_plan plan;
      plan = fftw_plan_r2r_1d (plen, x, y, FFTW_R2HC, FFTW_ESTIMATE);
#endif /* FFTW2 */

      power_spectrum_fftw (plen, x, y, pat, den, nwin, plan);
      fftw_destroy_plan (plan);

      free (x);
      free (xx);
      free (y);
      sf_close (sf);

      /* search maximum  */
      p0 = 0.0;
      if0 = -1;
      for (i=0; i<plen/2; i++)
	{
	  if (pat[i] > p0)
	    {
	      p0 = pat[i];
	      if0 = i;
	    }
	}
      if (if0 == -1)
	patch_flg = 0;

      npat = plen/2;
      patch_flg = 1;
    }
}
Beispiel #19
0
/********************************************
 ** BUILD STIMULUS WAV. This function builds the stimulus from the two
 ** wav files in the .stim file. This function takes in two full path
 ** exemplars and builds a temp wav file with the two exemlars separated
 ** by a pause.
 ********************************************/
int buildtempfile(char * stimexma,char * stimexmb)
{
long unsigned int outframes;
SNDFILE *sfina=NULL, *sfinb=NULL, *sfout=NULL;
SF_INFO sfin_infoa, sfin_infob, sfout_info;
sf_count_t incounta, incountb, fcheck;
short *inbuffb, *inbuffa, *obuff;
int samp=0, j, k;

/*open each motif*/
   sfin_infoa.format=0;
   sfin_infob.format=0;
   if(!(sfina = sf_open(stimexma,SFM_READ,&sfin_infoa))){
     fprintf(stderr,"error opening input file %s\n",stimexma);
     return -1;}
   if(!(sfinb = sf_open(stimexmb,SFM_READ,&sfin_infob))){
     fprintf(stderr,"error opening input file %s\n",stimexmb);
     return -1;}

   /*read in the file */
   inbuffa = (short *) malloc(sizeof(int) * sfin_infoa.frames);
   incounta = sf_readf_short(sfina, inbuffa, sfin_infoa.frames);
   sf_close(sfina);
   
   inbuffb = (short *) malloc(sizeof(int) * sfin_infob.frames);
   incountb = sf_readf_short(sfinb, inbuffb, sfin_infob.frames);
   sf_close(sfinb);

   if(DEBUG==1){fprintf(stderr, "samples in: %lu \n", (long unsigned int)incounta);}
   outframes = (long unsigned int)sample_reps*((long unsigned
			   int)incounta + pause_secs) + (long unsigned int)incountb;
   if(DEBUG==1){fprintf(stderr, "outframes is: %lu\n", (long unsigned int)outframes);}

 obuff = (short *) malloc(sizeof(int)*outframes);
   for (k=0;k<sample_reps;k++){	
	   for (j=0;j<incounta;j++){
	     obuff[samp++] = inbuffa[j];}
	   for (j=0;j<pause_secs;j++){
	     obuff[samp++];}
   }
	   for (j=0;j<incountb;j++){
	      obuff[samp++] = inbuffb[j];}

   free(inbuffa);
   free(inbuffb); /*free the inbuffs*/
 
 sfout_info.frames = outframes;
  
 /*this works as long as the files have been verified*/
 sfout_info.channels = sfin_infoa.channels;
 sfout_info.samplerate = sfin_infoa.samplerate;
 sfout_info.format = sfin_infoa.format;
 if(DEBUG==1){fprintf(stderr,"output file format:%x \tchannels: %d \tsamplerate: %d\n",sfout_info.format, sfout_info.channels, sfout_info.samplerate);}
 
 /*write the ouput file*/ 
 sprintf(outsfname,"%smotseq_tmp_box%d.wav", STIMPATH, box_id);
 if(!(sfout = sf_open(outsfname,SFM_WRITE,&sfout_info))){
   fprintf(stderr,"error opening output file '%s'\n",outsfname);
   return -1;
 }
 
 fcheck=sf_writef_short(sfout, obuff, outframes);
 if(fcheck!=outframes){
   fprintf(stderr,"UH OH!:I could only write %lu out of %lu frames!\n", (long unsigned int)fcheck, (long unsigned int)outframes);
   return -1;
 }
 else
   if(DEBUG==1){fprintf(stderr,"outframes: %lu \tfcheck: %lu \tduration: %g secs\n",
			(long unsigned int)outframes,(long unsigned int)fcheck,(double)outframes/sfout_info.samplerate);}
 sf_close(sfout);
 free(obuff);
 return 1;
}
Beispiel #20
0
void
openAudioInDevice (dsd_opts * opts)
{
  // get info of device/file
  struct stat stat_buf;
  if (stat(opts->audio_in_dev, &stat_buf) != 0) {
    printf("Error, couldn't open %s\n", opts->audio_in_dev);
    exit(1);
  }
  if(S_ISREG(stat_buf.st_mode)) { // is this a regular file? then process with libsndfile.
    opts->audio_in_type = 1;
    opts->audio_in_file_info = calloc(1, sizeof(SF_INFO));
    opts->audio_in_file_info->channels = 1;
    opts->audio_in_file = sf_open(opts->audio_in_dev, SFM_READ, opts->audio_in_file_info);
    if(opts->audio_in_file == NULL) {
        printf ("Error, couldn't open file %s\n", opts->audio_in_dev);
        exit(1);
    }
  }
  else { // this is a device, use old handling
  opts->audio_in_type = 0;
#ifdef SOLARIS
    sample_info_t aset, aget;
    int rgain;
  
    rgain = 64;
  
    if (opts->split == 1)
      {
        opts->audio_in_fd = open (opts->audio_in_dev, O_RDONLY);
      }
    else
      {
        opts->audio_in_fd = open (opts->audio_in_dev, O_RDWR);
      }
    if (opts->audio_in_fd == -1)
      {
        printf ("Error, couldn't open %s\n", opts->audio_in_dev);
        exit(1);
      }
  
    // get current
    ioctl (opts->audio_in_fd, AUDIO_GETINFO, &aset);
  
    aset.record.sample_rate = 48000;
    aset.play.sample_rate = 48000;
    aset.record.channels = 1;
    aset.play.channels = 1;
    aset.record.precision = 16;
    aset.play.precision = 16;
    aset.record.encoding = AUDIO_ENCODING_LINEAR;
    aset.play.encoding = AUDIO_ENCODING_LINEAR;
    aset.record.port = AUDIO_LINE_IN;
    aset.record.gain = rgain;
  
    if (ioctl (opts->audio_in_fd, AUDIO_SETINFO, &aset) == -1)
      {
        printf ("Error setting sample device parameters\n");
        exit (1);
      }
#endif

#if defined(BSD) && !defined(__APPLE__)
    int fmt;
  
    if (opts->split == 1)
      {
        opts->audio_in_fd = open (opts->audio_in_dev, O_RDONLY);
      }
    else
      {
        opts->audio_in_fd = open (opts->audio_in_dev, O_RDWR);
      }
  
    if (opts->audio_in_fd == -1)
      {
        printf ("Error, couldn't open %s\n", opts->audio_in_dev);
        opts->audio_out = 0;
      }
  
    fmt = 0;
    if (ioctl (opts->audio_in_fd, SNDCTL_DSP_RESET) < 0)
      {
        printf ("ioctl reset error \n");
      }
    fmt = 48000;
    if (ioctl (opts->audio_in_fd, SNDCTL_DSP_SPEED, &fmt) < 0)
      {
        printf ("ioctl speed error \n");
      }
    fmt = 0;
    if (ioctl (opts->audio_in_fd, SNDCTL_DSP_STEREO, &fmt) < 0)
      {
        printf ("ioctl stereo error \n");
      }
    fmt = AFMT_S16_LE;
    if (ioctl (opts->audio_in_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
      {
        printf ("ioctl setfmt error \n");
      }
#endif
  }
  if (opts->split == 1)
    {
      printf ("Audio In Device: %s\n", opts->audio_in_dev);
    }
  else
    {
      printf ("Audio In/Out Device: %s\n", opts->audio_in_dev);
    }
}
Beispiel #21
0
int
main (void)
{   /* This is a buffer of double precision floating point values
    ** which will hold our data while we process it.
    */
    static double *data = NULL;

    /* A SNDFILE is very much like a FILE in the Standard C library. The
    ** sf_open function return an SNDFILE* pointer when they sucessfully
	** open the specified file.
    */
    SNDFILE      *infile, *outfile ;

    /* A pointer to an SF_INFO stutct is passed to sf_open.
    ** On read, the library fills this struct with information about the file.
    ** On write, the struct must be filled in before calling sf_open.
    */
    SF_INFO		sfinfo ;
    int			readcount,i ;
    sf_count_t 		buffer_length;
    const char	*infilename = "input.wav" ;
    const char	*outfilename = "output.wav" ;

    /* Here's where we open the input file. We pass sf_open the file name and
    ** a pointer to an SF_INFO struct.
    ** On successful open, sf_open returns a SNDFILE* pointer which is used
    ** for all subsequent operations on that file.
    ** If an error occurs during sf_open, the function returns a NULL pointer.
	**
	** If you are trying to open a raw headerless file you will need to set the
	** format and channels fields of sfinfo before calling sf_open(). For
	** instance to open a raw 16 bit stereo PCM file you would need the following
	** two lines:
	**
	**		sfinfo.format   = SF_FORMAT_RAW | SF_FORMAT_PCM_16 ;
	**		sfinfo.channels = 2 ;
    */
    if (! (infile = sf_open (infilename, SFM_READ, &sfinfo)))
    {   /* Open failed so print an error message. */
        printf ("Not able to open input file %s.\n", infilename) ;
        /* Print the error message from libsndfile. */
        puts (sf_strerror (NULL)) ;
        return  1 ;
    } ;

    printf("samplerate: %d\n",sfinfo.samplerate);
    buffer_length = sfinfo.frames;

    data = (double*)malloc(sizeof(double)*buffer_length);
    if(data == NULL)
    {
        printf("malloc failed!\n");
        return 1;
    }

    if (sfinfo.channels > MAX_CHANNELS)
    {   printf ("Not able to process more than %d channels\n", MAX_CHANNELS) ;
        return  1 ;
        } ;
    /* Open the output file. */
    if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)))
    {   printf ("Not able to open output file %s.\n", outfilename) ;
        puts (sf_strerror (NULL)) ;
        return  1 ;
        } ;

    /* While there are.frames in the input file, read them, process
    ** them and write them to the output file.
    */
    readcount = sf_read_double (infile, data, buffer_length);

    for(i=0;i<100;++i) {
       sf_write_double (outfile, data, readcount) ;
    }

    /* Close input and output files. */
    sf_close (infile) ;
    sf_close (outfile) ;
    free(data);

    return 0 ;
} /* main */
Beispiel #22
0
static void
permission_test (const char *filename, int typemajor)
{
#if (OS_IS_WIN32)
	/* Avoid compiler warnings. */
	filename = filename ;
	typemajor = typemajor ;

	/* Can't run this test on Win32 so return. */
	return ;
#else

	FILE		*textfile ;
	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	const char	*errorstr ;
	int			frames ;

	if (getuid () == 0)
	{	/* If running as root bypass this test.
		** Root is allowed to open a readonly file for write.
		*/
		return ;
		} ;

	print_test_name ("permission_test", filename) ;

	if ((textfile = fopen (filename, "w")) == NULL)
	{	printf ("\n\nLine %d : not able to open text file for write.\n", __LINE__) ;
		exit (1) ;
		} ;

	fprintf (textfile, "This is a read only file.\n") ;
	fclose (textfile) ;

	if (chmod (filename, S_IRUSR | S_IRGRP))
	{	printf ("\n\nLine %d : chmod failed", __LINE__) ;
		fflush (stdout) ;
		perror ("") ;
		exit (1) ;
		} ;

	sfinfo.samplerate = 44100 ;
	sfinfo.format = (typemajor | SF_FORMAT_PCM_16) ;
	sfinfo.channels = 1 ;
	sfinfo.frames = 0 ;

	frames = BUFFER_LEN / sfinfo.channels ;

	if ((file = sf_open (filename, SFM_WRITE, &sfinfo)) != NULL)
	{	printf ("\n\nLine %d : Error, file should not have opened.\n", __LINE__ - 1) ;
		exit (1) ;
		} ;

	errorstr = sf_strerror (file) ;

	if (strstr (errorstr, "ermission denied") == NULL)
	{	printf ("\n\nLine %d : Error bad error string : %s.\n", __LINE__ - 1, errorstr) ;
		exit (1) ;
		} ;

	if (chmod (filename, S_IWUSR | S_IWGRP))
	{	printf ("\n\nLine %d : chmod failed", __LINE__) ;
		fflush (stdout) ;
		perror ("") ;
		exit (1) ;
		} ;

	unlink (filename) ;

	puts ("ok") ;

#endif
} /* permission_test */
static void
win32_play (int argc, char *argv [])
{	Win32_Audio_Data	audio_data ;

	WAVEFORMATEX wf ;
	int	k, error ;

	audio_data.sndfile = NULL ;
	audio_data.hwave = 0 ;

	for (k = 1 ; k < argc ; k++)
	{	printf ("Playing %s\n", argv [k]) ;

		if (! (audio_data.sndfile = sf_open (argv [k], SFM_READ, &(audio_data.sfinfo))))
		{	puts (sf_strerror (NULL)) ;
			continue ;
			} ;

		audio_data.remaining = audio_data.sfinfo.frames * audio_data.sfinfo.channels ;
		audio_data.current = 0 ;

		InitializeCriticalSection (&audio_data.mutex) ;
		audio_data.Event = CreateEvent (0, FALSE, FALSE, 0) ;

		wf.nChannels = audio_data.sfinfo.channels ;
		wf.wFormatTag = WAVE_FORMAT_PCM ;
		wf.cbSize = 0 ;
		wf.wBitsPerSample = 16 ;

		wf.nSamplesPerSec = audio_data.sfinfo.samplerate ;

		wf.nBlockAlign = audio_data.sfinfo.channels * sizeof (short) ;

		wf.nAvgBytesPerSec = wf.nBlockAlign * wf.nSamplesPerSec ;

		error = waveOutOpen (&(audio_data.hwave), WAVE_MAPPER, &wf, (DWORD_PTR) win32_audio_out_callback,
							(DWORD_PTR) &audio_data, CALLBACK_FUNCTION) ;
		if (error)
		{	puts ("waveOutOpen failed.") ;
			audio_data.hwave = 0 ;
			continue ;
			} ;

		audio_data.whdr [0].lpData = (char*) audio_data.buffer ;
		audio_data.whdr [1].lpData = ((char*) audio_data.buffer) + sizeof (audio_data.buffer) / 2 ;

		audio_data.whdr [0].dwBufferLength = sizeof (audio_data.buffer) / 2 ;
		audio_data.whdr [1].dwBufferLength = sizeof (audio_data.buffer) / 2 ;

		audio_data.whdr [0].dwFlags = 0 ;
		audio_data.whdr [1].dwFlags = 0 ;

		/* length of each audio buffer in samples */
		audio_data.bufferlen = sizeof (audio_data.buffer) / 2 / sizeof (short) ;

		/* Prepare the WAVEHDRs */
		if ((error = waveOutPrepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR))))
		{	printf ("waveOutPrepareHeader [0] failed : %08X\n", error) ;
			waveOutClose (audio_data.hwave) ;
			continue ;
			} ;

		if ((error = waveOutPrepareHeader (audio_data.hwave, &(audio_data.whdr [1]), sizeof (WAVEHDR))))
		{	printf ("waveOutPrepareHeader [1] failed : %08X\n", error) ;
			waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR)) ;
			waveOutClose (audio_data.hwave) ;
			continue ;
			} ;

		/* Fill up both buffers with audio data */
		audio_data.BuffersInUse = 0 ;
		win32_play_data (&audio_data) ;
		win32_play_data (&audio_data) ;

		/* loop until both buffers are released */
		while (audio_data.BuffersInUse > 0)
		{
			/* wait for buffer to be released */
			WaitForSingleObject (audio_data.Event, INFINITE) ;

			/* refill the buffer if there is more data to play */
			win32_play_data (&audio_data) ;
			} ;

		waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [0]), sizeof (WAVEHDR)) ;
		waveOutUnprepareHeader (audio_data.hwave, &(audio_data.whdr [1]), sizeof (WAVEHDR)) ;

		waveOutClose (audio_data.hwave) ;
		audio_data.hwave = 0 ;

		DeleteCriticalSection (&audio_data.mutex) ;

		sf_close (audio_data.sndfile) ;
		} ;

} /* win32_play */
Beispiel #24
0
Datei: test.c Projekt: EQ4/noise
int record_and_write(struct nz_node * recorder_node, const char * filename, double time_seconds) {
    DSL_DECLS;
    MAKE_LONG_CONSTANT(recorder_len, nz_frame_rate * time_seconds);
    CONNECT(recorder_node, 1, recorder_len, 0);

    // Trigger the computation
    struct nz_obj * sample = nz_port_pull(&recorder_node->node_outputs[0]);
    printf("Writing %lu frames to %s", nz_vector_get_size(sample), filename);

    SF_INFO fdata = {
        .frames = nz_vector_get_size(sample),
        .samplerate = nz_frame_rate,
        .channels = 1,
        .format = SF_FORMAT_WAV | SF_FORMAT_PCM_16,
        .sections = 1,
        .seekable = 0,
    };

    SNDFILE * f = sf_open(filename, SFM_WRITE, &fdata);
    sf_write_double(f, NZ_CAST(double *, sample), nz_vector_get_size(sample));
    sf_write_sync(f);
    sf_close(f);
    return 0;
}

int main(void) {
    DSL_DECLS;
    // Timebase
    // (frames / chunk) / (frames / second) * (beats / minute) / (seconds / minute) 
    // = (frames * second * beats * minute) / (chunk * frames * minute * second) 
    // = (beats / chunk)

    BLOCK(timebase, accumulator);
    MAKE_DOUBLE_CONSTANT(delta_t, nz_chunk_size / nz_frame_rate * 280 / 60.);
    CONNECT(_blk, 0, _cons, 0);

    BLOCK(time_tee, tee, 4);
    CONNECT(time_tee, 0, _pipe, 0);

    // Debug
    BLOCK(debug_time, debug, "time", 0);
    CONNECT(_blk, 0, _pipe, 0);

    BLOCK(time_wye, wye, 2);
    CONNECT(time_wye, 1, _pipe, 0);

    // Melody
    // TODO: Come up with a better way of specifying these
    double unison[] = {None, None, None, 65, 75, None, 72, 67, 67, 68, None, 65, 70, 72, 70, 65, 65, None, None, 65, 75, None, 72, 67, 67, 68, 65, 72, 75, None, 72, 77};
    size_t unison_len = sizeof(unison) / sizeof(*unison);

    struct nz_obj * melody_obj = make_double_vector(unison,  unison_len);
    BLOCK(melody, constant, melody_obj);

    // Sequencer
    BLOCK(seq, sequencer);
    CONNECT(_blk, 0, time_tee, 1);
    CONNECT(_blk, 1, melody, 0);

    // Debug
    BLOCK(debug_seq, debug, "seq", 0);
    CONNECT(_blk, 0, seq, 0);

    BLOCK(lpf, lpf);
    CONNECT(_blk, 0, _pipe, 0);
    MAKE_CONSTANT(lpf_alpha, nz_double_type, double, 2);
    CONNECT(_blk, 1, _cons, 0);

    // Debug
    BLOCK(debug_lpf, debug, "lpf", 0);
    CONNECT(_blk, 0, _pipe, 0);

    // Math
    BLOCK(n2f, math, NZ_MATH_NOTE_TO_FREQ);
    CONNECT(_blk, 0, _pipe, 0);

    // Instrument
    BLOCK(wave, wave);
    CONNECT(_blk, 0, _pipe, 0);
    MAKE_CONSTANT(wtype, nz_long_type, long, NZ_WAVE_SAW);
    CONNECT(_blk, 1, _cons, 0);

    // --- Percussion ---

    // -- Snare --
    BLOCK(snare_imp, impulse);

    BLOCK(snare_lpf, clpf);
    CONNECT(_blk, 0, snare_imp, 0);
    MAKE_DOUBLE_CONSTANT(snare_tau, 8.5);
    CONNECT(_blk, 1, _cons, 0);

    BLOCK(snare_wav, white);

    BLOCK(snare_mix, cmixer, 1);
    CONNECT(_blk, 0, snare_wav, 0);
    CONNECT(_blk, 1, snare_lpf, 0);

    BLOCK(snare_rec, recorder);
    CONNECT(_blk, 0, _pipe, 0);
    MAKE_LONG_CONSTANT(snare_len, nz_frame_rate * 0.5);
    CONNECT(_blk, 1, _cons, 0);
    //nz_record_and_write(snare_rec, "snare.wav", 0.5);

    // -- Kick --
    BLOCK(kick_imp, impulse);

    MAKE_DOUBLE_CONSTANT(kick_tau, 8.5);
    BLOCK(kick_lpf, clpf);
    CONNECT(_blk, 0, kick_imp, 0);
    CONNECT(_blk, 1, kick_tau, 0);

    BLOCK(kick_wav, wave);
    MAKE_DOUBLE_CONSTANT(kick_freq, 80);
    CONNECT(_blk, 0, _cons, 0);
    MAKE_LONG_CONSTANT(kick_wtype, NZ_WAVE_SINE);
    CONNECT(_blk, 1, _cons, 0);

    BLOCK(kick_mix, cmixer, 1);
    CONNECT(_blk, 0, kick_wav, 0);
    CONNECT(_blk, 1, kick_lpf, 0);

    BLOCK(kick_rec, recorder);
    CONNECT(_blk, 0, _pipe, 0);
    MAKE_LONG_CONSTANT(kick_len, nz_frame_rate * 0.5);
    CONNECT(_blk, 1, _cons, 0);

    // Kick & Snare sampling
    long snare_pat[] = {NZ_SAMPLER_COMMAND_PLAY, NZ_SAMPLER_COMMAND_PLAY, NZ_SAMPLER_COMMAND_STOP, NZ_SAMPLER_COMMAND_STOP};
    long kick_pat[]  = {NZ_SAMPLER_COMMAND_STOP, NZ_SAMPLER_COMMAND_STOP, NZ_SAMPLER_COMMAND_PLAY, NZ_SAMPLER_COMMAND_PLAY};

    struct nz_node * snare = make_drum(snare_rec, snare_pat, 4, time_tee, 2);
    struct nz_node * kick = make_drum(kick_rec, kick_pat, 4, time_tee, 3);

    // Mixer
    BLOCK(mixer, mixer, 3);

    MAKE_DOUBLE_CONSTANT(wave_vol, 0.40);
    MAKE_DOUBLE_CONSTANT(snare_vol, 0.80);
    MAKE_DOUBLE_CONSTANT(kick_vol, 2.0);

    CONNECT(mixer, 0, wave, 0);
    CONNECT(mixer, 1, wave_vol, 0);
    CONNECT(mixer, 2, snare, 0);
    CONNECT(mixer, 3, snare_vol, 0);
    CONNECT(mixer, 4, kick, 0);
    CONNECT(mixer, 5, kick_vol, 0);

    CONNECT(time_wye, 0, mixer, 0);
    
    // Debug
    BLOCK(debug_ch, debug, "ch", 0);
    CONNECT(_blk, 0, _pipe, 0);

    // Compressor
    BLOCK(compressor, compressor);
    CONNECT(_blk, 0, _pipe, 0);

    // Recorder
    BLOCK(recorder, recorder);
    CONNECT(_blk, 0, _pipe, 0);

    nz_debug_print_graph(recorder);
    nz_debug_print_dot(recorder, "unison.dot");

    // This triggers everything!
    record_and_write(recorder, "unison.wav", 10);


    /*
    // Soundcard 
    printf("Initing soundcard\n");
    struct nz_node * soundcard = soundcard_get();
    node_connect(soundcard, 0, time_wye, 0);
    printf("soundcard inited\n");

    debug_print_graph(soundcard);
    soundcard_run();

    node_destroy(delta_t);
    node_destroy(melody);
    node_destroy(mixer);
    node_destroy(n2f);
    node_destroy(seq);
    node_destroy(soundcard);
    node_destroy(time_tee);
    node_destroy(time_wye);
    node_destroy(timebase);
    node_destroy(wave);
    node_destroy(wave_vol);
    node_destroy(wtype);

    printf("Successfully destroyed everything!\n");
    */

    return 0;
}
Beispiel #25
0
bool sfx_load_file(struct sfx * sfx, const char * filename)
{
  bool rv;
  char fn[1024];

  rv = false;

  if(filename != NULL)
    snprintf(fn, sizeof fn, "%s", filename);
  else
    snprintf(fn, sizeof fn, "%s/%s.wav", get_data_filename("sfx"), sfx->base_filename);

  SNDFILE * fp;
  SF_INFO info;

  info.format = 0;
  fp = sf_open(fn, SFM_READ, &info);
  if(fp != NULL)
    {
      bool done;
      int16_t * wav;
      int wavlen;

      done = false;
      wav = NULL;
      wavlen = 0;
      while(done == false)
        {
          int n;
          float buf[128];

          n = sf_read_float(fp, buf, 128);
          if(n > 0)
            {
              int16_t * tmp;

              tmp = realloc(wav, (wavlen + n) * sizeof(int16_t));
              assert(tmp != NULL);
              if(tmp != NULL)
                {
                  wav = tmp;
                  for(int i = 0; i < n; i++)
                    wav[wavlen + i] = buf[i] * 32767.0f;
                  wavlen += n;
                }
            }
          if(n < 128)
            done = true;
        }
      
      sf_close(fp);

      alGenBuffers(1, &sfx->openal_buffer);
      alBufferData(sfx->openal_buffer, AL_FORMAT_MONO16, wav, wavlen * sizeof(int16_t), 44100);
      rv = true;

      free(wav);
    }
  
  return rv;
}
Beispiel #26
0
static void DumpCUEISOWAV(void)
{
 FILE *cuep = fopen("cd.cue", "wb");

 for(int track = CDIF_GetFirstTrack(); track <= CDIF_GetLastTrack(); track++)
 {
  CDIF_Track_Format format;
  uint32 sectors;

  sectors = cdrfile_get_track_sec_count(p_cdrfile, track);
  CDIF_GetTrackFormat(track, format);

  if(format == CDIF_FORMAT_AUDIO)
  {
   char buf[256];
   sprintf(buf, "%d.wav", track);

   static SNDFILE *sfp;
   SF_INFO slinfo;
   memset(&slinfo, 0, sizeof(SF_INFO));

   fprintf(cuep, "FILE \"%s\" WAVE\n", buf);
   fprintf(cuep, " TRACK %02d AUDIO\n", track);
   fprintf(cuep, "  INDEX 01 00:00:00\n");

   slinfo.samplerate = 44100;
   slinfo.channels = 2;
   slinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;

   sfp = sf_open(buf, SFM_WRITE, &slinfo);
   for(uint32 i = 0; i < sectors; i++)
   {
    uint8 secbuf[2352];

    CDIF_ReadAudioSector((int16*)secbuf, NULL, CDIF_GetTrackStartPositionLBA(track) + i);

    sf_writef_short(sfp, (int16*)secbuf, 2352 / 4);
   }
   sf_close(sfp);
  }
  else
  {
   char buf[256];
   sprintf(buf, "%d.iso", track);
   FILE *fp = fopen(buf, "wb");

   fprintf(cuep, "FILE \"%s\" BINARY\n", buf);
   fprintf(cuep, " TRACK %02d MODE1/2048\n", track);
   fprintf(cuep, "  INDEX 01 00:00:00\n");


   for(uint32 i = 0; i < sectors; i++)
   {
    uint8 secbuf[2048];
    CDIF_ReadSector(secbuf, NULL, CDIF_GetTrackStartPositionLBA(track) + i, 1);
    fwrite(secbuf, 1, 2048, fp);
   }
   fclose(fp);
  }
 }
 fclose(cuep);
}
Beispiel #27
0
int main(int argc, char *argv[])
{
	SNDFILE *sndref = NULL;
	SNDFILE *sndtst = NULL;
	SF_INFO infosref;
	SF_INFO infostst;
	char *ref;
	char *tst;
	int pass_rms, pass_absolute, pass, accuracy;

	if (argc == 2) {
		double db;

		printf("Test sampletobits\n");
		db = sampletobits((short) atoi(argv[1]), 1);
		printf("db = %f\n", db);
		exit(0);
	}

	if (argc < 3) {
		usage();
		exit(1);
	}

	ref = argv[1];
	tst = argv[2];

	printf("opening reference %s\n", ref);

	sndref = sf_open(ref, SFM_READ, &infosref);
	if (!sndref) {
		printf("Failed to open reference file\n");
		exit(1);
	}

	printf("opening testfile %s\n", tst);
	sndtst = sf_open(tst, SFM_READ, &infostst);
	if (!sndtst) {
		printf("Failed to open test file\n");
		sf_close(sndref);
		exit(1);
	}

	printf("reference:\n\t%d frames,\n\t%d hz,\n\t%d channels\n",
		(int) infosref.frames, (int) infosref.samplerate,
		(int) infosref.channels);
	printf("testfile:\n\t%d frames,\n\t%d hz,\n\t%d channels\n",
		(int) infostst.frames, (int) infostst.samplerate,
		(int) infostst.channels);

	/* check number of channels */
	if (infosref.channels > 2 || infostst.channels > 2) {
		printf("Too many channels\n");
		goto error;
	}

	/* compare number of samples */
	if (infosref.samplerate != infostst.samplerate ||
				infosref.channels != infostst.channels) {
		printf("Cannot compare files with different charasteristics\n");
		goto error;
	}

	accuracy = DEFACCURACY;
	printf("Accuracy: %d\n", accuracy);

	/* Condition 1 rms level */
	pass_rms = calculate_rms_level(sndref, &infosref, sndtst, &infostst,
					accuracy, "out.csv");
	if (pass_rms < 0)
		goto error;

	/* Condition 2 absolute difference */
	pass_absolute = check_absolute_diff(sndref, &infosref, sndtst,
						&infostst, accuracy);
	if (pass_absolute < 0)
		goto error;

	/* Verdict */
	pass = pass_rms && pass_absolute;
	printf("Verdict: %s\n", pass ? "pass" : "fail");

	return 0;

error:
	sf_close(sndref);
	sf_close(sndtst);

	exit(1);
}
Beispiel #28
0
/* phase vocoder by complex arithmetics with fixed hops.
 *   t_i - s_i = u_i - u_{i-1} = hop
 *   where s_i and t_i are the times for two analysis FFT
 *   and u_i is the time for the synthesis FFT at step i
 * Reference: M.Puckette (1995)
 * INPUT
 *  flag_lock : 0 == no phase lock is applied
 *              1 == loose phase lock is applied
 *  rate : time-streching rate
 *  pitch_shift : in the unit of half-note
 */
void pv_complex (const char *file, const char *outfile,
		  double rate, double pitch_shift,
		  long len, long hop_syn,
		  int flag_window,
		  int flag_lock)
{
  long hop_res = (long)((double)hop_syn * pow (2.0, - pitch_shift / 12.0));
  long hop_ana = (long)((double)hop_res * rate);

  struct pv_complex *pv = pv_complex_init (len, hop_syn, flag_window);
  pv->hop_res = hop_res;
  pv->hop_ana = hop_ana;
  //pv->pitch_shift = pitch_shift;

  // open file
  SNDFILE *sf = NULL;
  SF_INFO sfinfo;
  memset (&sfinfo, 0, sizeof (sfinfo));
  sf = sf_open (file, SFM_READ, &sfinfo);
  if (sf == NULL)
    {
      fprintf (stderr, "fail to open %s\n", file);
      exit (1);
    }
  sndfile_print_info (&sfinfo);

  pv_complex_set_input (pv, sf, &sfinfo);


  ao_device *ao = NULL;
  SNDFILE *sfout = NULL;
  SF_INFO sfout_info;
  if (outfile == NULL)
    {
      ao = ao_init_16_stereo (sfinfo.samplerate, 1 /* verbose */);
      pv_complex_set_output_ao (pv, ao);
    }
  else
    {
      sfout = sndfile_open_for_write (&sfout_info,
				      outfile,
				      sfinfo.samplerate,
				      sfinfo.channels);
      if (sfout == NULL)
	{
	  fprintf (stderr, "fail to open file %s\n", outfile);
	  exit (1);
	}
      pv_complex_set_output_sf (pv, sfout, &sfout_info);
    }
  pv->flag_lock = flag_lock;

  long cur;
  for (cur = 0; cur < (long)sfinfo.frames; cur += pv->hop_ana)
    {
      long len_play = pv_complex_play_step (pv, cur);
      if (len_play < pv->hop_res)
	{
	  break;
	}
    }

  if (outfile == NULL)
    {
      ao_close (ao);
    }
  else
    {
      // frames left in l_out[] and r_out[]
      sndfile_write (sfout, sfout_info,
		     pv->l_out, pv->r_out, len);

      sf_write_sync (sfout);
      sf_close (sfout);
    }

  pv_complex_free (pv);
  sf_close (sf) ;
}
Beispiel #29
0
int main(int argc, char ** argv)
{
  const char * file = "../test.wav";
  float pitch = 1.0f;
  int repeats = 5;
  bool loop = false;

  Resonant::DSPNetwork::Item item;

  for(int i = 1; i < argc; i++) {
    if(strcmp(argv[i], "--loop") == 0)
      loop = true;
    else if(strcmp(argv[i], "--sample") == 0 && (i + 1) < argc)
      file = argv[++i];
    else if(strcmp(argv[i], "--relpitch") == 0 && (i + 1) < argc)
      pitch = atof(argv[++i]);
    else if(strcmp(argv[i], "--repeat") == 0 && (i + 1) < argc)
      repeats = atoi(argv[++i]);
    else if(strcmp(argv[i], "--targetchannel") == 0 && (i + 1) < argc)
      item.setTargetChannel(atoi(argv[++i]) - 1);
    else if(strcmp(argv[i], "--verbose") == 0)
      Radiant::enableVerboseOutput(true);
    else {
      printf("%s # Unknown argument \"%s\"\n", argv[0], argv[i]);
      return EINVAL;
    }
  }

  if(loop)
    repeats = 1;
  
  SF_INFO info;
  SNDFILE * sndf = sf_open(file, SFM_READ, & info);

  if(!sndf) {
    Radiant::error("Could not open sound file \"%s\"", file);
    return EINVAL;
  }
  
  sf_close(sndf);

  Resonant::DSPNetwork dsp;

  dsp.start();

  Radiant::BinaryData control, control2;

  item.setModule(new Resonant::ModuleSamplePlayer(0));
  item.module()->setId("sampleplayer");
  
  control.writeInt32(2);
  control.rewind();

  item.module()->processMessage("channels", & control);
  
  dsp.addModule(item);


  control.rewind();
  // Id of the receiving module
  control.writeString("sampleplayer/playsample");

  // File name
  control.writeString(file);

  // Gain
  control.writeString("gain");
  control.writeFloat32(0.745f);

  // Relative pitch
  control.writeString("relpitch");
  control.writeFloat32(pitch);

  // Infinite looping;
  control.writeString("loop");
  control.writeInt32(loop);

  if(info.channels >= 2) {

    control2 = control;

    // control2.writeString("gain");
    // control2.writeFloat32(0.03);

    control2.writeString("samplechannel");
    control2.writeInt32(1);

    control2.writeString("targetchannel");
    control2.writeInt32(1);


    control2.writeString("end");
  }

  control.writeString("end");

  Radiant::Sleep::sleepMs(500);

  float fileduration = info.frames / (44100 * pitch);

  for(int i = 0; i < repeats; i++) {
    Radiant::info("Playing sample %s (%d of %d)", file, i + 1, repeats);
    dsp.send(control);

    if(info.channels >= 2)
      dsp.send(control2);

    Radiant::Sleep::sleepS(fileduration + 1);
  }
  
  Radiant::Sleep::sleepS(loop ? fileduration * 1000 : 1);

  dsp.stop();

  return 0;
}
Beispiel #30
0
void export_cue_libsndfile(struct cue *cue, const char *cwd) {

    SNDFILE *source, *dest;
    SF_INFO srcinfo, dstinfo;
    char trackno_str[4], *dest_name, *src_path;
    uint64_t nframes;
    int64_t cnt;
    unsigned i;
    short *frames;


    asprintf(&src_path, "%s/%s", cwd, cue->filename);
    printf("Now exporting \"%s\".\n", src_path);
    source = sf_open(src_path, SFM_READ, &srcinfo);
    free(src_path);
    if(srcinfo.format & SF_FORMAT_SUBMASK != SF_FORMAT_PCM_16) {
        fprintf(stderr, "Not 16-bit format. Sorry.\n");
        sf_close(source);
        return;
    }
    memcpy(&dstinfo, &srcinfo, sizeof(SF_INFO));
    /*
    dstinfo.format = SF_FORMAT_OGG 
                   | SF_FORMAT_VORBIS 
                   | (srcinfo.format & SF_FORMAT_ENDMASK);
    */
    dstinfo.format = SF_FORMAT_AIFF 
                   | SF_FORMAT_PCM_16
                   | SF_ENDIAN_BIG;
 
    if(!sf_format_check(&dstinfo)) {
        fprintf(stderr, "Output file format is invalid :"
                " sf_format_check() returned FALSE.\n");
        sf_close(source);
        return;
    }

    unsigned blksiz;
    for(blksiz = 1<<16 ; ; blksiz>>=1) {
        frames = malloc(sizeof(short)*dstinfo.channels*blksiz);
        if(frames) break; /* Don't put in condition. It's a do...while. */
    }

    for(i=0 ; i<cue->numtracks ; ++i) {
        asprintf(&dest_name, "%s/%u - %s.aiff", 
                cwd, cue->tracks[i].trackno, 
                strchr(cue->tracks[i].title, ':') ? "__Illegal_Title__" 
                                                 : cue->tracks[i].title);
        dest = sf_open(dest_name, SFM_WRITE, &dstinfo);
        sf_set_string(dest, SF_STR_TITLE, cue->tracks[i].title);
        sf_set_string(dest, SF_STR_ARTIST, cue->tracks[i].performer);
        sf_set_string(dest, SF_STR_ALBUM, cue->title);
        sprintf(trackno_str, "%u", cue->tracks[i].trackno);
        sf_set_string(dest, SF_STR_TRACKNUMBER, trackno_str);
        /* stuff */
        nframes = srcinfo.samplerate*cue->tracks[i].index_ms/1000;
        sf_seek(source, nframes, SEEK_SET);
        if(i==cue->numtracks-1) {
            for(;;) {
                clear_console_screen();
                printf("Converting track %u/%u :\n"
                        "to %s\n"
                        "(reading to end of file)\n"
                        "From \"%s\"", 
                        i+1, cue->numtracks, dest_name, cue->filename);
                cnt = sf_readf_short(source, frames, blksiz);
                if(cnt <= 0)
                    break;
                sf_writef_short(dest, frames, cnt);
            }
        } else {
            nframes = (srcinfo.samplerate*cue->tracks[i+1].index_ms/1000)
                -nframes-srcinfo.samplerate*2;
            for(cnt=0 ; cnt<nframes ; cnt += blksiz) {
                clear_console_screen();
                printf("Converting track %u/%u :\n"
                        "to %s\n"
                        "(%lf%%)\n"
                        "From \"%s\"", 
                        i+1, cue->numtracks, dest_name,
                        100.0*(double)cnt/(double)nframes, cue->filename);
                sf_readf_short(source, frames, blksiz);
                sf_writef_short(dest, frames, blksiz);
            }
            cnt -= blksiz;
            sf_readf_short(source, frames, nframes-cnt);
            sf_writef_short(dest, frames, nframes-cnt);
        }
        sf_close(dest);
        free(dest_name);
    }
    puts("Done. Now cleaning up.");
    sf_close(source);
    free(frames);
}