Beispiel #1
0
Wave *create_wave(const char *fname) {
    Wave *w = (Wave *) calloc(1,sizeof(Wave));
    SF_INFO *winfo;
    SNDFILE *wfile = NULL;
    winfo = (SF_INFO *) calloc(1, sizeof(SF_INFO));
    wfile = sf_open(fname, SFM_READ, winfo);
    w->samples = winfo->frames;
    w->rate = winfo->samplerate;
    w->d = (double *) calloc(w->samples+1, sizeof(double));
    sf_count_t n;
    if (winfo->channels == 1) {
        n = sf_readf_double(wfile, w->d, w->samples);
    }
    else { /* average over channels */
        double *multi = calloc((w->samples+1)*winfo->channels, sizeof(double));
        n = sf_readf_double(wfile, multi, w->samples * winfo->channels);
        int i, nframe;
        double mix;
        for (nframe = 0; nframe < w->samples; nframe++) {
            mix = 0.0;
            for (i = 0; i < winfo->channels; i++)
                mix += multi[nframe * winfo->channels + i];
            w->d[nframe] = mix / winfo->channels;
        }
        free(multi);
    }
    if (n != w->samples)
        fprintf(stderr,"Error reading \"%s\"\n\t"
                "\t%d samples read of\n\t%d reported size\n",
                fname, (int) n, w->samples);
    sf_close(wfile);
    return w;
}
Beispiel #2
0
//TODO dont read after end of file
bool DAC::playSoundFiles(double *outputBuffer,unsigned int nFrames,int channels, double streamTime, double windowsize)
{
	double BUFFER[nFrames*channels];
	memset(BUFFER,0,nFrames*channels*sizeof(double));
	for (std::set<soundFileSt*>::iterator it=this->playing_files.begin(); it!=this->playing_files.end(); ++it){
		if ((*it)->sf_info.channels == channels){ //it was already checked in sndfile:play but...
			if((*it)->timeoffset <= streamTime){ //already set
				unsigned int read = sf_readf_double((*it)->sndfile,BUFFER,nFrames);
				//if read < nFrames delete
				//std::cout << (*it)->filename << std::endl;
				for(int i=0; i< nFrames*channels; i++){
					outputBuffer[i] += BUFFER[i]*(*it)->level;
				}
			}else{
				if((*it)->timeoffset < streamTime + windowsize){ //set it if in window
					int frames = (streamTime + windowsize - (*it)->timeoffset) * (*it)->sf_info.samplerate;
					int res = sf_seek((*it)->sndfile, 0, SEEK_SET) ;
					if (res == -1)
						return false;
					unsigned int read = sf_readf_double((*it)->sndfile,BUFFER,frames);
					for(int i = (nFrames - frames)*channels,j=0; i< nFrames*channels; i++,j++){
						outputBuffer[i] += BUFFER[j]*(*it)->level;
					}
				}
			}
		}
	}
	return true;
}
Beispiel #3
0
static void
copy_data_fp (SNDFILE *outfile, SNDFILE *infile, int channels)
{	static double	data [BUFFER_LEN], max ;
	int		frames, readcount, k ;

	frames = BUFFER_LEN / channels ;
	readcount = frames ;

	sf_command (infile, SFC_CALC_SIGNAL_MAX, &max, sizeof (max)) ;

	if (max < 1.0)
	{	while (readcount > 0)
		{	readcount = sf_readf_double (infile, data, frames) ;
			sf_writef_double (outfile, data, readcount) ;
			} ;
		}
	else
	{	sf_command (infile, SFC_SET_NORM_DOUBLE, NULL, SF_FALSE) ;

		while (readcount > 0)
		{	readcount = sf_readf_double (infile, data, frames) ;
			for (k = 0 ; k < readcount * channels ; k++)
				data [k] /= max ;
			sf_writef_double (outfile, data, readcount) ;
			} ;
		} ;

	return ;
} /* copy_data_fp */
Beispiel #4
0
static void ra_sound_read_double(RA_SOUND *snd, RA_BUFFER *buf, sf_count_t frames) {
    static double temp[1024];
    int temp_len = 1024;
    double *data = (double*)buf->data;
    double mix_sum;

    // Get info struct
    SF_INFO *info;
    Data_Get_Struct(snd->info, SF_INFO, info);

    // Up/Downmix based on channel matching
    sf_count_t read = 0, r, amount;
    int i, k;
    if(buf->channels == info->channels) { // Simply read data without mix
        read = sf_readf_double(snd->snd, data, frames);
    } else if(buf->channels == 1) { // Downmix to mono
        sf_count_t max = temp_len / info->channels;
        int channels;

        while(read < frames) {
            // Calculate # of frames to read
            amount = frames - read;
            if(amount > max) amount = max;

            r = sf_readf_double(snd->snd, temp, amount);
            if(r == 0) break;

            // Mix channels together by averaging all channels and store to buffer
            for(i = 0; i < r; i++) {
                mix_sum = 0;
                for(k = 0; k < info->channels; k++) mix_sum += temp[i * info->channels + k];
                data[read] = mix_sum/info->channels;
                read++;
            }
        }
    } else if(info->channels == 1) { // Upmix from mono by copying channel
        while(read < frames) {
            // Calculate # of frames to read
            amount = frames - read;
            if(amount > temp_len) amount = temp_len;

            r = sf_readf_double(snd->snd, temp, amount);
            if(r == 0) break;

            // Write every frame channel times to the buffer
            for(i = 0; i < r; i++) {
                for(k = 0; k < buf->channels; k++) {
                    data[read * buf->channels + k] = temp[i];
                }
                read++;
            }
        }
    } else {
        rb_raise(eRubyAudioError, "unsupported mix from %d to %d", buf->channels, info->channels);
    }

    buf->real_size = read;
}
Beispiel #5
0
void childProcessWorkFunction(const char * inputfilename, const char * outputfilename , double scale)
{
	int i = 0;	
	double buffer[arraySize];  //buffer for storing data
	    SNDFILE * inputfile, *outputfile;  // file pointers to reference files
	    SF_INFO sf_info;   // sound file data structure describing file properties
	    size_t numread;  // stores the number of frames read
	    size_t numframes; // numnber of frames to read;

	    inputfile = sf_open(inputfilename, SFM_READ, &sf_info);  //Open file for reading

	    if(inputfile == NULL)
	    {
	    	perror("Could not open file");
	    	error(1);
	    }

	    outputfile = sf_open(outputfilename,SFM_WRITE,&sf_info);

	    numframes = arraySize/sf_info.channels;  //Find number of frames, buffersize/channels
	    numread = numframes;
	    while(numread == numframes)
	    {
	       numread = sf_readf_double(inputfile, buffer, numframes);  //read from the files
	       
	       for(i=0; i < numread * sf_info.channels ; i++){
			buffer[i] *= scale;
		}

	       sf_writef_double(outputfile, buffer, numread);  //Write to the file
	    }
	    sf_close(inputfile);
	    sf_close(outputfile);
}
Beispiel #6
0
int main()
{
	double buffer[arraySize];  //buffer for storing data
    SNDFILE * inputfile, outputfile;  // file pointers to reference files
    SF_INFO sf_info;   // sound file data structure describing file properties
    size_t numread;  // stores the number of frames read
    size_t numframes; // number of frames to read;

    inputfile = sf_open("in.wav", SFM_READ, &sf_info);  //Open file for reading
    if(inputfile == NULL)
    {
    	perror("Could not open file");
    	error(1);
    }
    outputfile = sf_open("out.wav",SFM_WRITE,&sf_info);

    numframes = arraySize/sf_info.channels;  //Find number of frames, buffersize/channels
    numread = numframes;
    while(numread == numframes)
    {
       numread = sf_readf_double(inputfile, buffer, numframes);  //read from the files
       sf_writef_double(outputfile, buffer, numread);  //Write to the file
    }
    sf_close(inputfile);
    sf_close(outputfile);
}
Beispiel #7
0
int sp_ftbl_loadfile(sp_data *sp, sp_ftbl **ft, const char *filename)
{
    *ft = malloc(sizeof(sp_ftbl));
    sp_ftbl *ftp = *ft;
    SF_INFO info;
    memset(&info, 0, sizeof(SF_INFO));
    info.format = 0;
    SNDFILE *snd = sf_open(filename, SFM_READ, &info);
    if(snd == NULL) {
        return SP_NOT_OK;
    }
    size_t size = info.frames * info.channels;

    ftp->tbl = malloc(sizeof(SPFLOAT) * (size + 1));

    sp_ftbl_init(sp, ftp, size);

#ifdef USE_DOUBLE
    sf_readf_double(snd, ftp->tbl, ftp->size);
#else
    sf_readf_float(snd, ftp->tbl, ftp->size);
#endif
    sf_close(snd);
    return SP_OK;
}
Beispiel #8
0
void plot_file_process_run(ShortTimeProcess &process)
{
  std::string input_file = getAudioPath();
  input_file += "/example16000.wav";
  SF_INFO sf_info_in;
  SNDFILE *snd_file_in  = sf_open(input_file.c_str(), SFM_READ, &sf_info_in);


  EXPECT_FALSE(snd_file_in == NULL);
  if (snd_file_in == NULL)
    return;

  int nframes = 1024;
  int out_n_frames = nframes + process.getMaxLatency();
  int nchannels = sf_info_in.channels;
  int sampling_rate = sf_info_in.samplerate;

  EXPECT_EQ(1,nchannels);

  double data[nframes * nchannels];
  double out_data[out_n_frames * nchannels + process.getMaxLatency()];

  std::vector<double*> in_channels, out_channels;
  in_channels.push_back(data);
  out_channels.push_back(out_data);

  int read_frames;
  while ( (read_frames = sf_readf_double(snd_file_in, data, nframes) ) > 0)
  {
    process.process(in_channels, read_frames, out_channels, out_n_frames);
    usleep(1000000.0F * read_frames / sampling_rate );
  }

}
Beispiel #9
0
  int AudioFileReader::readFramesIntoBuffer() {
    assert(m_readBuffer!=NULL);
    assert((m_sfinfo.channels==1) || (m_sfinfo.channels==2));
    int nbRead = sf_readf_double(m_sndfile,m_readBuffer,m_bufferSize);
    if (m_sfinfo.channels == 2) {
      for (int i=0;i<nbRead;++i)
        m_readBuffer[i] = 0.5 * (m_readBuffer[2*i] + m_readBuffer[2*i+1]);
    }
    if (m_filter) {
      // resample
      if (nbRead) {
        nbRead = smarc_resample(m_filter,m_state,m_readBuffer,nbRead,m_resampleBuffer,m_resampleBufferSize);
        memcpy(m_readBuffer,m_resampleBuffer,nbRead*sizeof(double));
      } else {
        nbRead = smarc_resample_flush(m_filter,m_state,m_readBuffer,m_resampleBufferSize);
      }
    }

    if (m_frameLeft > 0 ) {
      m_frameLeft -= nbRead;
      if (m_frameLeft <= 0) {
        return 0;
      }
    }
    return nbRead;
  }
int main(int argc, char *argv[])
{

   printf("Wav Read Test\n");
   SF_INFO sndInfo;
   
   SNDFILE *sndFile = sf_open(argv[1], SFM_READ, &sndInfo);

   if (sndFile == NULL) {
      fprintf(stderr, "Error reading source file '%s': %s\n", argv[1], sf_strerror(sndFile));
      return 1;
   }
   // Check format - 16bit PCM
   if (sndInfo.format != (SF_FORMAT_WAV | SF_FORMAT_PCM_16)) {
      fprintf(stderr, "Input should be 16bit Wav\n");
      sf_close(sndFile);
      return 1;
   }

   // Allocate memory
   double *waveTable = malloc(sndInfo.channels * sndInfo.frames * sizeof(double));   


   if (waveTable == NULL) {
      fprintf(stderr, "Could not allocate memory for data\n");
      sf_close(sndFile);
      return 1;
   }

   // Load data
   long numFrames = sf_readf_double(sndFile, waveTable, sndInfo.channels*sndInfo.frames);

   long i;
   for(i=0;i<sndInfo.frames;i+=10000){
	printf("Sample %d :\t%f \n",i,waveTable[i]);
   }

   // Output Info
   printf("Read %ld frames from %s, Sample rate: %d, Length: %fs\n",
      numFrames, argv[1], sndInfo.samplerate, (float)numFrames/sndInfo.samplerate);


    long size = 38+5*BLOCKSIZE+MFCC_FREQ_BANDS;
    double *FVec;

    sf_close(sndFile);
    double *wavetable=malloc(BLOCKSIZE*sizeof(double));//{0};
    for(i=0;i<numFrames;i+=BLOCKSIZE){
	wavetable=&(waveTable[i]);
	FVec = extractall(wavetable,sndInfo.frames,sndInfo.samplerate);
    }
    
    for(i=0;i<size;i++)
	printf("%f\t",FVec[i]);
    
    return 0;

}
Beispiel #11
0
void reverse(const char *infilename, const char *outfilename) {

	SNDFILE *infile, *outfile;
	SF_INFO sfinfo;
	sfinfo.format = 0;

	// open input file
	infile = sf_open(infilename, SFM_READ, &sfinfo);

	// check if input file was opened
	if (!infile)
	{
		printf("Not able to open input file %s\n", infilename);
		puts(sf_strerror (NULL));
		return;
	}

	int readcount, i = 0, frames = sfinfo.frames;

	// allocate memory
	double *data = malloc(sizeof(double)*(frames*sfinfo.channels));
	double *dataToWrite = malloc(sizeof(double)*(frames*sfinfo.channels));
	
	// check format of file
	if (sfinfo.format != 131074 && sfinfo.format != 65538 && sfinfo.format != 65539 && sfinfo.format != 1245187) {

		printf("Only .wav or .aif files are allowed\n");
		return;
	}
	
	// open outputfile
	outfile = sf_open(outfilename, SFM_WRITE, &sfinfo);

	// check if output file was opened
	if (!outfile)
	{
		printf("Not able to open output file %s.\n", outfilename);
		puts(sf_strerror(NULL));
		return;
	}

	readcount = sf_readf_double(infile, data, frames);

	// read data into output buffer from end of file to beginning 
	for (i = 0; i < frames*sfinfo.channels; i++){
		dataToWrite[i] = data[(frames*sfinfo.channels)-i];
	}

	// write output buffer to file
	sf_writef_double(outfile, dataToWrite, frames);

	// free data and close input/output files
	free(data);	
	sf_close(infile);
	sf_close(outfile);

	return;
}
Beispiel #12
0
/* TODO: documentation */
double *get_samples_from_file(const char * const filename, long frames_requested, long *frames_returned)
{
	SNDFILE	*file;
	SF_INFO	sfinfo;
	double	*buf;
	double	*ret;
	int	audio_channels;
	int	rd_cnt;
	long	frames_written;
	long	frames_to_copy;

	if (NULL == frames_returned) {
		fprintf(stderr, "frames_returned cannot be NULL\n");
		return NULL;
	}
	*frames_returned = -1;

	if (NULL == filename) {
		return NULL;
	}

	if (0 >= frames_requested) {
		return NULL;
	}

	memset(&sfinfo, 0, sizeof(sfinfo));
	if (NULL == (file = sf_open(filename, SFM_READ, &sfinfo))) {
		return NULL;
	}

	/* each frame contains a sample per audio channel */
	audio_channels = sfinfo.channels;
	ret = (double *) MALLOC_SAFELY(frames_requested * audio_channels * sizeof(double));

	/* we use a temporary buffer for pulling the samples into memory */
	buf = (double *) MALLOC_SAFELY(audio_channels * AUDIO_SAMPLE_BUFSIZE * sizeof(double));
	frames_written = 0;
	while (frames_written < frames_requested && 0 < (rd_cnt = sf_readf_double(file, buf, AUDIO_SAMPLE_BUFSIZE))) {

		/*
		 * We'll be able to copy either all of the bytes in our
		 * temporary buffer or only the ones that fit in our allocated
		 * memory, whichever is smaller.
		 */
		frames_to_copy = MIN(rd_cnt, frames_requested - frames_written);
		memcpy(ret + (frames_written * audio_channels), buf, frames_to_copy * audio_channels * sizeof(double));
		frames_written += frames_to_copy;
	}
	FREE_SAFELY(buf);

	if (0 != sf_close(file)) {
		FREE_SAFELY(ret);
		return NULL;
	}

	*frames_returned = frames_written;
	return ret;
}
Beispiel #13
0
 int Soundfile::mixFrames(double *inputFrames, int samples, double *mixedFrames)
 {
   size_t position = sf_seek(sndfile, 0, SEEK_CUR);
   sf_readf_double(sndfile, mixedFrames, samples);
   for (int i = 0; i < samples; i++) {
     mixedFrames[i] += inputFrames[i];
   }
   sf_seek(sndfile, position, SEEK_SET);
   return sf_writef_double(sndfile, mixedFrames, samples);
 }
Beispiel #14
0
Datei: snd.c Projekt: Red54/WaoN
long sndfile_read (SNDFILE *sf, SF_INFO sfinfo,
		   double * left, double * right,
		   int len)
{
  static double *buf = NULL;
  static int nbuf = 0;

  if (buf == NULL)
    {
      buf = (double *)malloc (sizeof (double) * len * sfinfo.channels);
      CHECK_MALLOC (buf, "sndfile_read");
      nbuf = len * sfinfo.channels;
    }
  if (len * sfinfo.channels > nbuf)
    {
      buf = (double *)realloc (buf, sizeof (double) * len * sfinfo.channels);
      CHECK_MALLOC (buf, "sndfile_read");
      nbuf = len * sfinfo.channels;
    }

  sf_count_t status;

  if (sfinfo.channels == 1)
    {
      status = sf_readf_double (sf, left, (sf_count_t)len);
    }
  else
    {
      status = sf_readf_double (sf, buf, (sf_count_t)len);
      int i;
      for (i = 0; i < len; i ++)
	{
	  left  [i] = buf [i * sfinfo.channels];
	  right [i] = buf [i * sfinfo.channels + 1];
	}
    }

  return ((long) status);
}
Beispiel #15
0
/*TODO: add error checking, make tests */
int sp_gen_file(sp_data *sp, sp_ftbl *ft, const char *filename)
{
    SF_INFO info;
    memset(&info, 0, sizeof(SF_INFO));
    info.format = 0;
    SNDFILE *snd = sf_open(filename, SFM_READ, &info);
#ifdef USE_DOUBLE
    sf_readf_double(snd, ft->tbl, ft->size);
#else
    sf_readf_float(snd, ft->tbl, ft->size);
#endif
    sf_close(snd);
    return SP_OK;
}
Beispiel #16
0
double *
read_sound_file_double(char *filename, index_t *n_frames, int *n_channels, double *sampling_rate) {
	SF_INFO	 	infile_info = {0};
	SNDFILE	 	*infile = sf_open(filename, SFM_READ, &infile_info);
	if (!infile) sdie(NULL, "can not open input file %s: ", filename) ;
	*n_frames = infile_info.frames;
	*n_channels = infile_info.channels;
	*sampling_rate = infile_info.samplerate;
	double *d = salloc(*n_frames**n_channels*sizeof d[0]);
	if (sf_readf_double(infile, d, *n_frames) !=  *n_frames)
		die("sf_readf_double returned insufficient frames");
	sf_close(infile);
	return d;
}
Beispiel #17
0
void readFile(char *fname, double * out, int size)
{

	SF_INFO sndInfo;

	//sndInfo.samplerate = SAMPLE_RATE;
	//sndInfo.channels = 1;
	//sndInfo.frames = BUFFER_SIZE;
	//sndInfo.format = SF_FORMAT_PCM_16 | SF_FORMAT_WAV;

	SNDFILE *inFile = sf_open(fname, SFM_READ, &sndInfo);
	sf_readf_double(inFile, out, size);


}
Beispiel #18
0
double test_true_peak(const char* filename) {
  SF_INFO file_info;
  SNDFILE* file;
  sf_count_t nr_frames_read;
  int i;

  ebur128_state* st = NULL;
  double true_peak;
  double max_true_peak = -HUGE_VAL;
  double* buffer;

  memset(&file_info, '\0', sizeof(file_info));
  file = sf_open(filename, SFM_READ, &file_info);
  if (!file) {
    fprintf(stderr, "Could not open file %s!\n", filename);
    return 0.0;
  }
  st = ebur128_init((unsigned) file_info.channels,
                    (unsigned) file_info.samplerate,
                    EBUR128_MODE_TRUE_PEAK);
  if (file_info.channels == 5) {
    ebur128_set_channel(st, 0, EBUR128_LEFT);
    ebur128_set_channel(st, 1, EBUR128_RIGHT);
    ebur128_set_channel(st, 2, EBUR128_CENTER);
    ebur128_set_channel(st, 3, EBUR128_LEFT_SURROUND);
    ebur128_set_channel(st, 4, EBUR128_RIGHT_SURROUND);
  }
  buffer = (double*) malloc(st->samplerate * st->channels * sizeof(double));
  while ((nr_frames_read = sf_readf_double(file, buffer,
                                           (sf_count_t) st->samplerate))) {
    ebur128_add_frames_double(st, buffer, (size_t) nr_frames_read);
  }

  for (i = 0; i < file_info.channels; i++) {
    ebur128_true_peak(st, (unsigned)i, &true_peak);
    if (true_peak > max_true_peak)
      max_true_peak = true_peak;
  }
  /* clean up */
  ebur128_destroy(&st);

  free(buffer);
  buffer = NULL;
  if (sf_close(file)) {
    fprintf(stderr, "Could not close input file!\n");
  }
  return 20 * log10(max_true_peak);
}
UInt32 SFB::Audio::LibsndfileDecoder::_ReadAudio(AudioBufferList *bufferList, UInt32 frameCount)
{
	sf_count_t framesRead = 0;
	switch(mReadMethod) {
		case ReadMethod::Unknown:	/* Do nothing */																				break;
		case ReadMethod::Short:		framesRead = sf_readf_short(mFile.get(), (short *)bufferList->mBuffers[0].mData, frameCount);	break;
		case ReadMethod::Int:		framesRead = sf_readf_int(mFile.get(), (int *)bufferList->mBuffers[0].mData, frameCount);		break;
		case ReadMethod::Float:		framesRead = sf_readf_float(mFile.get(), (float *)bufferList->mBuffers[0].mData, frameCount);	break;
		case ReadMethod::Double:	framesRead = sf_readf_double(mFile.get(), (double *)bufferList->mBuffers[0].mData, frameCount);	break;
	}

	bufferList->mBuffers[0].mDataByteSize = (UInt32)(framesRead * mFormat.mBytesPerFrame);
	bufferList->mBuffers[0].mNumberChannels = mFormat.mChannelsPerFrame;

	return (UInt32)framesRead;
}
static void
deinterleave_double (STATE * state)
{	int read_len ;
	int ch, k ;

	do
	{	read_len = sf_readf_double (state->infile, state->din.d, BUFFER_LEN) ;

		for (ch = 0 ; ch < state->channels ; ch ++)
		{	for (k = 0 ; k < read_len ; k++)
				state->dout.d [k] = state->din.d [k * state->channels + ch] ;
			sf_write_double (state->outfile [ch], state->dout.d, read_len) ;
			} ;
		}
	while (read_len > 0) ;

} /* deinterleave_double */
Beispiel #21
0
static void
concat_data_fp (SNDFILE *wfile, SNDFILE *rofile, int channels)
{	static double	data [BUFFER_LEN] ;
	int		frames, readcount ;

	frames = BUFFER_LEN / channels ;
	readcount = frames ;

	sf_seek (wfile, 0, SEEK_END) ;

	while (readcount > 0)
	{	readcount = sf_readf_double (rofile, data, frames) ;
		sf_writef_double (wfile, data, readcount) ;
		} ;

	return ;
} /* concat_data_fp */
Beispiel #22
0
void
test_readf_double_or_die (SNDFILE *file, int pass, double *test, sf_count_t frames, int line_num)
{	sf_count_t count ;

	if ((count = sf_readf_double (file, test, frames)) != frames)
	{	printf ("\n\nLine %d", line_num) ;
		if (pass > 0)
			printf (" (pass %d)", pass) ;
		printf (" : sf_readf_double failed with short readf (%ld => %ld).\n",
						SF_COUNT_TO_LONG (frames), SF_COUNT_TO_LONG (count)) ;
		fflush (stdout) ;
		puts (sf_strerror (file)) ;
		exit (1) ;
		} ;

	return ;
} /* test_readf_double */
Beispiel #23
0
double test_global_loudness(const char* filename) {
  SF_INFO file_info;
  SNDFILE* file;
  sf_count_t nr_frames_read;

  ebur128_state* st = NULL;
  double gated_loudness;
  double* buffer;

  memset(&file_info, '\0', sizeof(file_info));
  file = sf_open(filename, SFM_READ, &file_info);
  if (!file) {
    fprintf(stderr, "Could not open file %s!\n", filename);
    return 0.0;
  }
  st = ebur128_init((unsigned) file_info.channels,
                    (unsigned) file_info.samplerate,
                    EBUR128_MODE_I);
  if (file_info.channels == 5) {
    ebur128_set_channel(st, 0, EBUR128_LEFT);
    ebur128_set_channel(st, 1, EBUR128_RIGHT);
    ebur128_set_channel(st, 2, EBUR128_CENTER);
    ebur128_set_channel(st, 3, EBUR128_LEFT_SURROUND);
    ebur128_set_channel(st, 4, EBUR128_RIGHT_SURROUND);
  }
  buffer = (double*) malloc(st->samplerate * st->channels * sizeof(double));
  while ((nr_frames_read = sf_readf_double(file, buffer,
                                           (sf_count_t) st->samplerate))) {
    ebur128_add_frames_double(st, buffer, (size_t) nr_frames_read);
  }

  ebur128_loudness_global(st, &gated_loudness);

  /* clean up */
  ebur128_destroy(&st);

  free(buffer);
  buffer = NULL;
  if (sf_close(file)) {
    fprintf(stderr, "Could not close input file!\n");
  }
  return gated_loudness;
}
Beispiel #24
0
void On_remind_me(double pTime, int pData)
//***************************************
// VMLAB notifies about a previouly sent REMIND_ME() function.
// Read the next voltage sample from the WAV file, set the analog voltage on the
// output pin, and schedule another output update based on the sampling rate of
// the input wav file.
{
   char strBuffer[MAXBUF];

   // Do nothing if the wav file is closed due to an error
   if(!VAR(File)) {
      return;
   }
   
   // Read the next voltage sample from the wav file. If an error occurs or
   // EOF is reached, then the wav file is closed, the output voltage remains
   // set to the previous value and no more output updates are scheduled.
   if(sf_readf_double(VAR(File), VAR(Sample_buffer), 1) != 1) {
      // Break with an error message if an actual I/O or decode error occurred
      if(sf_error(VAR(File))) {
         snprintf(strBuffer, MAXBUF, "Error reading \"%s.wav\" file: %s",
            GET_INSTANCE(), sf_strerror(VAR(File)));
         BREAK(strBuffer);         
      }
      
      // Close the file on either an error or a normal end-of-file
      Close_file();
      return;
   }

   // The voltage in VMLAB ranges from 0 to POWER(), while the sample that
   // libsndfile returns ranges from -1 to +1. Only the sample from the
   // first (left) channel is used here. Samples from additional channels
   // are simply discarded.
   SET_VOLTAGE(DATA, (*VAR(Sample_buffer) + 1) * 0.5 * POWER());

   // Schedule the next On_remind_me() based on the sampling rate
   REMIND_ME(1.0 / VAR(File_info).samplerate);
}
Beispiel #25
0
int main(int ac, const char* av[]) {
	SF_INFO file_info;
	SNDFILE* file;
	sf_count_t nr_frames_read;
	ebur128_state* state = NULL;
	double* buffer;
	double loudness;

	if (ac != 2) {
	    exit(1); //ERROR CODE 1: Exactly one input file is expected.   
  	}

  	state = malloc((size_t) sizeof(ebur128_state*));
  	memset(&file_info, '\0', sizeof(file_info));
  	file = sf_open(av[1], SFM_READ, &file_info);
	state = ebur128_init((unsigned) file_info.channels, (unsigned) file_info.samplerate, EBUR128_MODE_I);

	buffer = (double*) malloc(state->samplerate * state->channels * sizeof(double));

	while ((nr_frames_read = sf_readf_double(file, buffer, (sf_count_t) state->samplerate))) {
		ebur128_add_frames_double(state, buffer, (size_t) nr_frames_read);
		
	}

	ebur128_loudness_global(state, &loudness);
	fprintf(stdout, "%.2f\n", loudness);

	free(buffer);
	buffer = NULL;

	if (sf_close(file)) {
		exit(2); //ERROR CODE 2: File wasn't able to be closed.
	}

	ebur128_destroy(&state);
	free(state);
	return 0; // ERROR CODE 0: No errors!
}
unsigned AudioFileSndfile::read(void* buffer, Sound::Type type, unsigned frames)
{
    if (!_handle || !(_mode == ModeRead || _mode == ModeReadWrite)) {
        RUNTIME_ERROR("Attempt to read file not opened for reading.");
    }

    sf_count_t count;

    switch (type) {
    case Sound::Type::Float32:
        count = sf_readf_float(_handle.get(), static_cast<Sound::Float32*>(buffer), frames);
        break;
    case Sound::Type::Float64:
        count = sf_readf_double(_handle.get(), static_cast<Sound::Float64*>(buffer), frames);
        break;
    case Sound::Type::Int8:
        count = sf_read_raw(_handle.get(), buffer, frames * _info.channels);
        break;
    case Sound::Type::Int16:
        count = sf_readf_short(_handle.get(), static_cast<Sound::Int16*>(buffer), frames);
        break;
    case Sound::Type::Int32:
        count = sf_readf_int(_handle.get(), static_cast<Sound::Int32*>(buffer), frames);
        break;
    default:
        RUNTIME_ERROR("Unsupported sample type");
    }

    int errorNumber = sf_error(_handle.get());

    if (errorNumber) {
        SNDFILE_ERROR(errorNumber, "Error while reading file");
    }

    return unsigned(count);
}
static switch_status_t sndfile_file_read(switch_file_handle_t *handle, void *data, size_t *len)
{
	size_t inlen = *len;
	sndfile_context *context = handle->private_info;

	if (switch_test_flag(handle, SWITCH_FILE_DATA_RAW)) {
		*len = (size_t) sf_read_raw(context->handle, data, inlen);
	} else if (switch_test_flag(handle, SWITCH_FILE_DATA_INT)) {
		*len = (size_t) sf_readf_int(context->handle, (int *) data, inlen);
	} else if (switch_test_flag(handle, SWITCH_FILE_DATA_SHORT)) {
		*len = (size_t) sf_readf_short(context->handle, (short *) data, inlen);
	} else if (switch_test_flag(handle, SWITCH_FILE_DATA_FLOAT)) {
		*len = (size_t) sf_readf_float(context->handle, (float *) data, inlen);
	} else if (switch_test_flag(handle, SWITCH_FILE_DATA_DOUBLE)) {
		*len = (size_t) sf_readf_double(context->handle, (double *) data, inlen);
	} else {
		*len = (size_t) sf_readf_int(context->handle, (int *) data, inlen);
	}

	handle->pos += *len;
	handle->sample_count += *len;

	return *len ? SWITCH_STATUS_SUCCESS : SWITCH_STATUS_FALSE;
}
Beispiel #28
0
int main(int argc, char *argv[])
{
    char const *inname = NULL;
    char const *outname = NULL;
    char const *initstring = NULL;
    char const *preamble = NULL;
    char const *postamble = NULL;
    uint32_t length = 16384;
    sf_count_t seek = 0;
    double seek_sec = 0;
    sf_count_t step = 0;
    double step_sec = 0;
    SNDFILE *infile = NULL;
    FILE *outfile = NULL;
    int decimate = 1;
    SF_INFO sfinfo;
    double *in = NULL;
    fftw_complex *out = NULL;
    fftw_plan plan = NULL;
    int opt;

    while ((opt = getopt(argc, argv, "i:o:l:s:S:t:T:w:d:I:p:P:")) != -1)
        switch (opt)
        {
        case 'i': inname = optarg;                          break;
        case 'o': outname = optarg;                         break;
        case 'l': length = atoi(optarg);                    break;
        case 's': seek_sec = atof(optarg);                  break;
        case 'S': seek = atoll(optarg);                     break;
        case 't': step_sec = atof(optarg);                  break;
        case 'T': step = atoll(optarg);                     break;
        case 'w':
            if (strcmp(optarg, "rectangular") && strcmp(optarg, "boxcar"))
                fprintf(stderr, "only rectangular and boxcar window functions supported.\n");
            break;
        case 'd': decimate = atoi(optarg);                  break;
        case 'I': initstring = optarg;                      break;
        case 'p': preamble = optarg;                        break;
        case 'P': postamble = optarg;                       break;
        default:
            fprintf(stderr, "unknown option '%c'\n", opt);
            exit(EXIT_FAILURE);
        }

    if ((infile = sf_open(inname, SFM_READ, &sfinfo)) == NULL)
    {
        fprintf(stderr, "couldn't open input outfile '%s'\n", inname);
        exit(EXIT_FAILURE);
    }

    if (outname == NULL)
        outfile = stdout;
    else if ((outfile = fopen(outname, "wt")) == NULL)
    {
        fprintf(stderr, "couldn't open output outfile '%s'\n", outname);
        exit(EXIT_FAILURE);
    }

    if (initstring) fprintf(outfile, "%s\n", initstring);

    in = fftw_malloc(sizeof(*in) * sfinfo.channels * length);
    out = fftw_malloc(sizeof(*out) * sfinfo.channels * length);
    if (in && out)
    {
        int n[1] = { length };

        plan = fftw_plan_many_dft_r2c(1, n, sfinfo.channels,
                                    in, NULL, sfinfo.channels, 1,
                                    out, NULL, sfinfo.channels, 1,
                                    FFTW_ESTIMATE | FFTW_DESTROY_INPUT);
    }
    if (plan == NULL)
    {
        fprintf(stderr, "couldn't initialise fftw.\n");
        exit(EXIT_FAILURE);
    }

    seek += rint(seek_sec * sfinfo.samplerate);
    step += rint(step_sec * sfinfo.samplerate);

    do
    {
        int r, c;

        sf_seek(infile, (sf_count_t)rint(seek), SEEK_SET);
        r = sf_readf_double(infile, in, length) * sfinfo.channels;
        if (r <= 0)
            break;
        if (r < length * sfinfo.channels)
            step = 0;
        while (r < length * sfinfo.channels)
            in[r++] = 0.0;

        fftw_execute(plan);

        if (preamble) fprintf(outfile, "%s\n", preamble);

        for (r = 0; r * 2 < length; r += decimate)
        {
            double f = (double)r * sfinfo.samplerate / length;

            fprintf(outfile, "%lf", f);

            for (c = 0; c < sfinfo.channels; c++)
            {
                double x = 0.0;
                int i;
                for (i = 0; i < decimate; i++)
                {
                    fftw_complex *p = &out[(r + i) * sfinfo.channels + c];
                    double y = p[0][0] * p[0][0] + p[0][1] * p[0][1];
                    if (x < y)
                        x = y;
                }
                x = log10(x) / 2.0 * 20.0 - log10(length * 0.5) * 20.0;
                fprintf(outfile, " %lf", x);
            }
            fprintf(outfile, "\n");
        }

        if (postamble) fprintf(outfile, "%s\n", postamble);

        seek += step;
    } while (step > 0);

    fftw_destroy_plan(plan);
    fftw_free(in);
    fftw_free(out);
    sf_close(infile);
    if (outname != NULL)
        fclose(outfile);

    return EXIT_SUCCESS;
}
Beispiel #29
0
 int Soundfile::readFrame(double *outputFrame)
 {
   return sf_readf_double(sndfile, outputFrame, 1);
 }
static int
compare (void)
{
	double buf1 [BUFLEN], buf2 [BUFLEN] ;
	SF_INFO sfinfo1, sfinfo2 ;
	SNDFILE * sf1 = NULL, * sf2 = NULL ;
	sf_count_t len, i, nread1, nread2 ;
	int retval = 0 ;

	memset (&sfinfo1, 0, sizeof (SF_INFO)) ;
	sf1 = sf_open (filename1, SFM_READ, &sfinfo1) ;
	if (sf1 == NULL)
	{	printf ("Error opening %s.\n", filename1) ;
		retval = 1 ;
		goto out ;
		} ;

	memset (&sfinfo2, 0, sizeof (SF_INFO)) ;
	sf2 = sf_open (filename2, SFM_READ, &sfinfo2) ;
	if (sf2 == NULL)
	{	printf ("Error opening %s.\n", filename2) ;
		retval = 1 ;
		goto out ;
		} ;

	if (sfinfo1.samplerate != sfinfo2.samplerate)
	{	retval = comparison_error ("Samplerates") ;
		goto out ;
		} ;

	if (sfinfo1.channels != sfinfo2.channels)
	{	retval = comparison_error ("Number of channels") ;
		goto out ;
		} ;

	/* Calculate the framecount that will fit in our data buffers */
	len = BUFLEN / sfinfo1.channels ;

	while ( (nread1 = sf_readf_double (sf1, buf1, len)) > 0)
	{	nread2 = sf_readf_double (sf2, buf2, nread1) ;
		if (nread2 != nread1)
		{	retval = comparison_error ("PCM data lengths") ;
			goto out ;
			} ;
		for (i = 0 ; i < nread1 ; i++)
		{	if (buf1 [i] != buf2 [i])
			{	retval = comparison_error ("PCM data") ;
				goto out ;
				} ;
			} ;
		} ;

	if ( (nread2 = sf_readf_double (sf2, buf2, nread1)) != 0)
	{	retval = comparison_error ("PCM data lengths") ;
		goto out ;
		} ;

out :
	sf_close (sf1) ;
	sf_close (sf2) ;

	return retval ;
} /* compare */