Example #1
0
long soundfile_count_samples(void)
{
    sf_count_t curr = sf_seek(sndfile, 0, SEEK_SET|SFM_READ);
    sf_count_t rc   = sf_seek(sndfile, 0, SEEK_END|SFM_READ);
    sf_seek(sndfile, curr, SEEK_SET|SFM_READ);
    return rc;
}
Example #2
0
int SoundStream::allocateDataStructures() {
   int status = PV::HyPerLayer::allocateDataStructures();
   free(clayer->V);
   clayer->V = NULL;

   // Point to clayer data struct
   soundData = clayer->activity->data;
   assert(soundData!=NULL);
   //Layer must be 1 by 1 by 1
   if(getLayerLoc()->nx != 1 || getLayerLoc()->ny != 1){
      fprintf(stderr, "SoundStream::SoundStream layer must be 1 by 1 in the x and y direction\n");
      exit(EXIT_FAILURE);
   }
   if(getLayerLoc()->nf > fileHeader->channels){
      fprintf(stderr, "SoundStream::Audio file has %d channels, while the number of features is %d\n", fileHeader->channels, getLayerLoc()->nf);
      exit(EXIT_FAILURE);
   }
   //Allocate read buffer based on number of channels
   soundBuf = (float*) malloc(sizeof(float) * fileHeader->channels);
   if(frameStart <= 1){
      frameStart = 1;
   }
   //Set to frameStart, which is 1 indexed
   sf_seek(fileStream, frameStart-1, SEEK_SET);
   status = updateState(0,parent->getDeltaTime());
   //Reset filepointer to reread the same frame on the 0th timestep
   sf_seek(fileStream, frameStart-1, SEEK_SET);
   return status;
}
Example #3
0
void file_buffer_worker(void *ctx)
{
    AudioFile::pimpl *fileImpl = (AudioFile::pimpl *)ctx;
    int writeBuffer = (fileImpl->currentBufIndex == 0) ? 1 : 0;
    sf_seek(fileImpl->sndfile, fileImpl->framesBuffered, SF_SEEK_SET);
    size_t read = sf_readf_float(fileImpl->sndfile, fileImpl->bufs[writeBuffer], FRAMES_PER_FILE_BUFFER);
    fileImpl->framesBuffered += read;
    if (read < FRAMES_PER_FILE_BUFFER)
    {
        if (fileImpl->looping)
        {
            sf_seek(fileImpl->sndfile, 0, SF_SEEK_SET);
            size_t samplesDidRead = read * fileImpl->sfInfo.channels;
            size_t framesToRead = (FRAMES_PER_FILE_BUFFER - read);
            sf_readf_float(fileImpl->sndfile, &(fileImpl->bufs[writeBuffer][samplesDidRead]), framesToRead);
            fileImpl->framesBuffered = framesToRead;
        }
        else
        {
            fileImpl->needsBuffer = false;
        }
    }
    
    fileImpl->isBuffering = false;
}
Example #4
0
void
test_read_write_position_or_die (SNDFILE *file, int line_num, int pass, sf_count_t read_pos, sf_count_t write_pos)
{	sf_count_t pos ;

	/* Check the current read position. */
	if (read_pos >= 0 && (pos = sf_seek (file, 0, SEEK_CUR | SFM_READ)) != read_pos)
	{	printf ("\n\nLine %d ", line_num) ;
		if (pass > 0)
			printf ("(pass %d): ", pass) ;
		printf ("Read position (%ld) should be %ld.\n", SF_COUNT_TO_LONG (pos), SF_COUNT_TO_LONG (read_pos)) ;
		exit (1) ;
		} ;

	/* Check the current write position. */
	if (write_pos >= 0 && (pos = sf_seek (file, 0, SEEK_CUR | SFM_WRITE)) != write_pos)
	{	printf ("\n\nLine %d", line_num) ;
		if (pass > 0)
			printf (" (pass %d)", pass) ;
		printf (" : Write position (%ld) should be %ld.\n",
						SF_COUNT_TO_LONG (pos), SF_COUNT_TO_LONG (write_pos)) ;
		exit (1) ;
		} ;

	return ;
} /* test_read_write_position */
Example #5
0
static gint64
xmms_sndfile_seek (xmms_xform_t *xform, gint64 samples,
                   xmms_xform_seek_mode_t whence, xmms_error_t *error)
{
	xmms_sndfile_data_t *data;
	gint64 ret = -1;
	g_return_val_if_fail (xform, -1);
	g_return_val_if_fail (samples >= 0, -1);
	g_return_val_if_fail (whence == XMMS_XFORM_SEEK_SET ||
	                      whence == XMMS_XFORM_SEEK_CUR ||
	                      whence == XMMS_XFORM_SEEK_END, -1);

	data = xmms_xform_private_data_get (xform);
	g_return_val_if_fail (data, -1);

	switch ( whence ) {
		case XMMS_XFORM_SEEK_SET:
			ret = sf_seek (data->sndfile, samples, SEEK_SET);
			break;
		case XMMS_XFORM_SEEK_CUR:
			ret = sf_seek (data->sndfile, samples, SEEK_CUR);
			break;
		case XMMS_XFORM_SEEK_END:
			ret = sf_seek (data->sndfile, samples, SEEK_END);
			break;
	}

	return ret;
}
Example #6
0
void readBlockAroundPoint (int xPos, int halfXapp, int* curXapp, int* leftShift) {

    int startX = xPos - halfXapp;
    int ix, id, ida, iz, ind, dataShift, tracesShift, pointsNumToRead;
    size_t startPos;
    float *ptrToTrace, *ptrToTraceSq, *ptrFrom, *ptrTo, *ptrSqFrom, *ptrSqTo;

    /* check if the apperture is adequate... if not - correct it and the start point */
    checkBoundary (&startX, curXapp);
    *leftShift = xPos - startX;
    pointsNumToRead = dagSize_ * (*curXapp);

    ptrToDags_   = sf_floatalloc (pointsNumToRead);
    ptrToDagsSq_ = sf_floatalloc (pointsNumToRead);
    memset (ptrToDags_,   0, pointsNumToRead * sizeof (float));
    memset (ptrToDagsSq_, 0, pointsNumToRead * sizeof (float));

    ptrToData_   = sf_floatalloc (pointsNumToRead);
    ptrToDataSq_ = sf_floatalloc (pointsNumToRead);
    memset (ptrToData_,   0, pointsNumToRead * sizeof (float));
    memset (ptrToDataSq_, 0, pointsNumToRead * sizeof (float));			

    startPos = (size_t) startX * dagSize_ * sizeof (float);

    sf_seek (inDags_,   startPos, SEEK_SET);
    sf_seek (inDagsSq_, startPos, SEEK_SET);

    sf_floatread (ptrToData_,   pointsNumToRead, inDags_);
    sf_floatread (ptrToDataSq_, pointsNumToRead, inDagsSq_);

    /* substacking in the x-dip direction */
		
    for (ix = 0; ix < *curXapp; ++ix) {
		for (id = 0; id < dipNum_; ++id) {
			
		    tracesShift = ix * dipNum_ + id;
		    ptrToTrace   = ptrToDags_ + tracesShift * zNum_;
		    ptrToTraceSq = ptrToDagsSq_ + tracesShift * zNum_;

		    for (ida = 0; ida < xdipapp_; ++ida) {		
				ind = id - xdipapp_ / 2 + ida;
				if (ind < 0 || ind >= dipNum_) continue;		
				
				dataShift = ix * dipNum_ + ind;
				ptrFrom   = ptrToData_   + dataShift * zNum_;
				ptrSqFrom = ptrToDataSq_ + dataShift * zNum_;

				ptrTo     = ptrToTrace;
				ptrSqTo   = ptrToTraceSq;

				for (iz = 0; iz < zNum_; ++iz, ++ptrTo, ++ptrSqTo, ++ptrFrom, ++ptrSqFrom) {
				    *ptrTo += *ptrFrom;
				    *ptrSqTo += *ptrSqFrom;
				}
	    	}
		}
    }

    return;
}
Example #7
0
/* insert 'sample_count' samples at sample 'insert_pos'
 * to the soundfile.
 * 'insert_pos' == -1 means append to end of file.
 */
int soundfile_insert_samples(long linsert_pos, long lsample_count,
                             int *sample_data, int status_info)
{
    sf_count_t insert_pos = linsert_pos;
    sf_count_t sample_count = lsample_count;
    sf_count_t end_pos = sf_seek(sndfile, 0, SEEK_END|SFM_READ);

    if (insert_pos < 0 || insert_pos > end_pos)
        insert_pos = end_pos;

    if (soundfile_shift_samples_right(insert_pos, sample_count, status_info) < 0) {
        return -1;
    }

    /* go to insert position 'insert_pos'... */
    if (sf_seek(sndfile, insert_pos, SEEK_SET|SFM_WRITE) < 0) {
        perr("soundfile_insert_samples: sf_seek write pointer");
        warning("Libsndfile reports write pointer seek error in audio file");
        return -1;
    }
    /* ...and insert new data */
    if (sf_writef_int(sndfile, sample_data, sample_count) != sample_count) {
        perr("soundfile_insert_samples: append with sf_writef_int");
        warning("Libsndfile reports write error in audio file");
        return -1;
    }

    return 0;
}
Example #8
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);
 }
Example #9
0
void shot_image_stack(float *img,float mig_min_x,float mig_min_y,int mig_nx,int mig_ny,sf_file tag,
		      struct shot_image_par_type image_par)
/*< stack image >*/
{
    float *tmp_img;
    float img_min_x,img_max_x,img_min_y,img_max_y,img_dx,img_dy;
    float mig_max_x,rite_min_x,rite_max_x;
    int img_ny,img_nx,rite_nx;
    int n_hy_hx,img_nhx,img_nhy,nz;
    int ntmp_img[2],nimg[3];
    int rite_ix_b,array_ix_b;
    int block_size,block_i;
    int iy,rite_iy,ix,i_hy_hx,iz;

    img_min_x=image_par.min_x; img_max_x=image_par.max_x; img_min_y=image_par.min_y; img_max_y=image_par.max_y;
    img_dx=image_par.dx; img_dy=image_par.dy;             img_ny=image_par.ny; img_nx=image_par.nx;
    img_nhx=image_par.nhx; img_nhy=image_par.nhy;  nz=image_par.nz;

    mig_max_x=((float)(mig_nx-1))*img_dx+mig_min_x;

    rite_min_x=SF_MAX(img_min_x,mig_min_x); 
    rite_max_x=SF_MIN(img_max_x,mig_max_x);
    rite_nx=(rite_max_x-rite_min_x)/img_dx+1;

    n_hy_hx= img_nhy*img_nhx;  d3(n_hy_hx,nz,ntmp_img); d4(mig_ny,mig_nx,n_hy_hx,nimg);

    if (rite_nx >=1){
	rite_ix_b= (rite_min_x-img_min_x)/img_dx;
	array_ix_b=(rite_min_x-mig_min_x)/img_dx;
	tmp_img=sf_floatalloc(rite_nx*n_hy_hx*nz);
	block_size=4*n_hy_hx*nz;
	for(iy=0;iy<mig_ny;iy++){
	    vector_value_f(tmp_img,0.0,rite_nx*n_hy_hx*nz);
	    rite_iy= iy+(mig_min_y-img_min_y)/img_dy;
	    if (rite_iy < img_ny && rite_iy>= 0){
		block_i=rite_iy*img_nx+rite_ix_b;
		sf_seek(tag,block_i*block_size,SEEK_SET);
		sf_floatread(tmp_img,rite_nx*n_hy_hx*nz,tag);
		for(ix=0;ix<rite_nx;ix++){
		    for(i_hy_hx=0;i_hy_hx<n_hy_hx;i_hy_hx++){
			for(iz=0;iz<nz;iz++){
			    tmp_img[i3(ix,i_hy_hx,iz,ntmp_img)]+=img[i4(iz,iy,array_ix_b+ix,i_hy_hx,nimg)]; 
			}
		    }
		} 
		sf_seek(tag,block_i*block_size,SEEK_SET);
		sf_floatwrite(tmp_img,rite_nx*n_hy_hx*nz,tag);
	    }
	}
	free(tmp_img);
    }
}
Example #10
0
SINT SoundSourceSndFile::seekSampleFrame(
        SINT frameIndex) {
    DEBUG_ASSERT(isValidFrameIndex(frameIndex));

    const sf_count_t seekResult = sf_seek(m_pSndFile, frameIndex, SEEK_SET);
    if (0 <= seekResult) {
        return seekResult;
    } else {
        qWarning() << "Failed to seek libsnd file:" << seekResult
                << sf_strerror(m_pSndFile);
        return sf_seek(m_pSndFile, 0, SEEK_CUR);
    }
}
WavFileReadStream::WavFileReadStream(string path) :
    m_file(0),
    m_path(path),
    m_offset(0)
{
    m_channelCount = 0;
    m_sampleRate = 0;

    m_fileInfo.format = 0;
    m_fileInfo.frames = 0;
    m_file = sf_open(m_path.c_str(), SFM_READ, &m_fileInfo);

    if (!m_file || m_fileInfo.frames <= 0 || m_fileInfo.channels <= 0) {
	cerr << "WavFileReadStream::initialize: Failed to open file \""
                  << path << "\" (" << sf_strerror(m_file) << ")" << endl;
        if (sf_error(m_file) == SF_ERR_SYSTEM) {
	    m_error = string("Couldn't load audio file '") +
                m_path + "':\n" + sf_strerror(m_file);
            throw FileNotFound(m_path);
        }
	if (m_file) {
	    m_error = string("Couldn't load audio file '") +
                m_path + "':\n" + sf_strerror(m_file);
	} else {
	    m_error = string("Failed to open audio file '") +
		m_path + "'";
	}
        throw InvalidFileFormat(m_path, m_error);
    }

    m_channelCount = m_fileInfo.channels;
    m_sampleRate = m_fileInfo.samplerate;

    sf_seek(m_file, 0, SEEK_SET);
}
Example #12
0
bool BlockFile::OpenReadData()
{
   wxASSERT(mMode == BLOCK_MODE_NOT_OPEN);

   if (mType == BLOCK_TYPE_ALIAS) {
      mInfo = (void *)new SF_INFO;
      mSoundFile = (void *)sf_open_read(mAliasFullPath, (SF_INFO *)mInfo);

      if (mSoundFile != 0) {
         sf_seek((SNDFILE *)mSoundFile, mStart, SEEK_SET);
         mMode = BLOCK_MODE_READ_DATA;
         mPos = WaveTrack::GetHeaderLen();
         return true;
      }
      return false;
   } else {

      mFile = new wxFFile();
      bool success = mFile->Open((const wxChar *) mFullPath, "rb");

      if (success) {
         mMode = BLOCK_MODE_READ_DATA;
         SeekTo(0);     /* seek to the beginning of the data area */
      }

      return success;
   }
}
Example #13
0
unsigned AudioFileSndfile::seek(int pos, IAudioFile::SeekWhence sw,
    IAudioFile::SeekType st)
{
    if (!_info.seekable || !_handle) {
        RUNTIME_ERROR("File not seekable or handle not open");
    }

    static int whenceMap[3] = {
        SF_SEEK_CUR,
        SF_SEEK_END,
        SF_SEEK_SET,
    };

    int whence = whenceMap[sw];

    if (SeekTypeRead == st) {
        whence |= SFM_READ;
    } else if (SeekTypeWrite == st) {
        whence |= SFM_WRITE;
    }

    sf_count_t result = sf_seek(_handle.get(), pos, whence);

    if (result < 0) {
        int errorNumber = sf_error(_handle.get());
        SNDFILE_ERROR(errorNumber, "Unable to seek file");
    }

    return unsigned(result);
}
Example #14
0
File: Ola.cpp Project: alltom/taps
int OlaRandom::ReadSoundFile( char filename[] )
{
	// open file
	if( sfread )
	{
		sf_close( sfread );
	}
	sfread = sf_open( filename, SFM_READ, &readinfo );
	if( !sfread )
	{
		BB_log( BB_LOG_SEVERE, "[TreesynthIO]: Could not open input file '%s', %s", 
			filename, sf_error_number( sf_error( sfread ) ) );
		return 0;
	}
	strcpy( ifilename, filename );

	// determine number of buffers needed
	origsize = readinfo.frames;
	std::cerr << "frames: " << origsize << std::endl;
	SAFE_DELETE_ARRAY(origbuffer);
	origbuffer = new float[origsize];

	// read
	sf_seek( sfread, 0, SEEK_SET );
    int itemsread = sf_read_float( sfread, origbuffer, origsize);
	sf_close( sfread );
	sfread = NULL;

	return itemsread;
}
Example #15
0
bool BlockFile::SeekTo(int where)
{
   /* all modes but these two are legit */

   wxASSERT(mMode != BLOCK_MODE_NOT_OPEN && mMode != BLOCK_MODE_WRITE_DATA);
   
   if (mType == BLOCK_TYPE_ALIAS && mMode == BLOCK_MODE_READ_DATA) {

      int channels = ((SF_INFO *)mInfo)->channels;
      sf_seek((SNDFILE *)mSoundFile,
              mStart + (where / sizeof(sampleType)),
              SEEK_SET);
      mPos = where + WaveTrack::GetHeaderLen();

      return true;
   } else {
      
      wxASSERT(mFile);
      if(mMode == BLOCK_MODE_READ_DATA)
         mPos = where + WaveTrack::GetHeaderLen();
      else
         mPos = where;
      
      return mFile->Seek((long) mPos, wxFromStart);
   }
}
Example #16
0
DWORD ISndStreamWAV::GetCurrentTime()
{
    // return total time in ms
    if (GetSampleRate()>0)
        return (DWORD)sf_seek( m_pSndFile, 0, SEEK_CUR )/GetSampleRate()*1000;
    return 0;
}
static void
sndfile_stream_decode(struct decoder *decoder, struct input_stream *is)
{
	GError *error = NULL;
	SNDFILE *sf;
	SF_INFO info;
	struct audio_format audio_format;
	size_t frame_size;
	sf_count_t read_frames, num_frames;
	int buffer[4096];
	enum decoder_command cmd;

	info.format = 0;

	sf = sf_open_virtual(&vio, SFM_READ, &info, is);
	if (sf == NULL) {
		g_warning("sf_open_virtual() failed");
		return;
	}

	/* for now, always read 32 bit samples.  Later, we could lower
	   MPD's CPU usage by reading 16 bit samples with
	   sf_readf_short() on low-quality source files. */
	if (!audio_format_init_checked(&audio_format, info.samplerate,
				       SAMPLE_FORMAT_S32,
				       info.channels, &error)) {
		g_warning("%s", error->message);
		g_error_free(error);
		return;
	}

	decoder_initialized(decoder, &audio_format, info.seekable,
			    frame_to_time(info.frames, &audio_format));

	frame_size = audio_format_frame_size(&audio_format);
	read_frames = sizeof(buffer) / frame_size;

	do {
		num_frames = sf_readf_int(sf, buffer, read_frames);
		if (num_frames <= 0)
			break;

		cmd = decoder_data(decoder, is,
				   buffer, num_frames * frame_size,
				   0);
		if (cmd == DECODE_COMMAND_SEEK) {
			sf_count_t c =
				time_to_frame(decoder_seek_where(decoder),
					      &audio_format);
			c = sf_seek(sf, c, SEEK_SET);
			if (c < 0)
				decoder_seek_error(decoder);
			else
				decoder_command_finished(decoder);
			cmd = DECODE_COMMAND_NONE;
		}
	} while (cmd == DECODE_COMMAND_NONE);

	sf_close(sf);
}
Example #18
0
__int64 ISndStreamWAV::Seek( __int64 ddwOffset, UINT nFrom )
{
    __int64	ddwFilePosition = 0;
    int		nPercent = (int)ddwOffset;

    // Flush the stream
    Flush();

    switch ( nFrom )
    {
    case SEEK_PERCENT:
        if ( nPercent<0  ) nPercent= 0;
        if ( nPercent>99 ) nPercent=99;
        ddwFilePosition= (__int64)( nPercent * m_ddwTotalFileSize / 100.0 );
        break;

    case SEEK_TIME:
        ddwFilePosition= (__int64)( ddwOffset / 1000.0 * GetSampleRate() );
        break;
    default:
        ASSERT( FALSE );
        break;
    }

    ddwFilePosition = ddwFilePosition / 4 * 4;

    // Seek to the desired position
    sf_seek( m_pSndFile, ddwFilePosition, SEEK_SET );

    return ddwFilePosition;
}
Example #19
0
//-----------------------------------------------------------------------------
// name: int ReadSoundFile( char filename[], TS_FLOAT * data, int datasize )
// desc: Reads given sound file into data array
//-----------------------------------------------------------------------------
int TreesynthIO::ReadSoundFile( char filename[], TS_FLOAT * data, int datasize )
{
	if( !sfread ) {
		sfread = sf_open( filename, SFM_READ, &info );
		if( !sfread )
		{
			std::cerr << "TreesynthIO::ReadSoundFile : cannot open file '" << filename << "', quitting" << std::endl;
            char x[256];
			std::cin.getline( x, 256 );
			exit(1);
		}
	}

    datasize = rm_next_length;
	sf_seek( sfread, rm_next_pos, SEEK_SET );
	std::cerr << sfread << " " << data << " " << datasize << std::endl;
	int itemsread = sf_read_float( sfread, data, datasize );
	set_next_pos( filename );
    // rt audio
    /*if( !audio_initialize( info.samplerate ) ) {	// 44100
        std::cerr << "TreesynthIO::ReadSoundFile : cannot open audio interface, quitting" << std::endl;
		char x[256];
		std::cin.getline( x, 256 );
		exit(1);
    }*/

	return itemsread;
}
Example #20
0
bool SndFileDecoder::seek(size_t ms_offset, bool ms, bool /*mayrestart*/)
{
    size_t smp_offset = ms? (size_t)((double)ms_offset / 1000. * SndInfo.samplerate) : ms_offset;
    if(sf_seek(SndFile, smp_offset, SEEK_SET) < 0)
        return false;
    return true;
}
Example #21
0
soundfile * readsoundfilechunk(char *path, int start, int len) {
    soundfile * ret;
    SF_INFO info;
    SNDFILE *snd;

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

    if ( (snd = sf_open(path, SFM_READ, &info)) == NULL )
        diem("Couldn't open sound file for reading", path);

    if ( info.channels != 1 )
        diem("Sound file has more than one channel", path);

    if ( (ret = malloc(sizeof(*ret))) == NULL )
        die("Couldn't malloc space for soundfile");

    if ( (ret->data = malloc(sizeof(float)*len)) == NULL )
        die("Couldn't malloc space for sound buffer");

    sf_seek(snd, start, SEEK_SET);
    int actuallen = sf_read_float(snd, ret->data, len); // assumption: channel count is 1, verified above

    ret->length = actuallen;
    ret->samplerate = info.samplerate;

    if ( sf_close(snd) )
        diem("Couldn't close sound file", path);

    return ret;
}
Example #22
0
	size_t load_buffer(ALuint buf) {
		// seek to beginning if in a end
		if (is_end()) {
			if (info_.seekable) {
				if (sf_seek(file_.get(), 0, SEEK_SET) == -1) {
					Output::Error("libsndfile seek error: %s", sf_strerror(file_.get()));
					return 0;
				}
			} else {
				file_.reset(sf_open(filename_.c_str(), SFM_READ, &info_), sf_close);
				if (!file_) {
					Output::Error("libsndfile open error: %s", sf_strerror(NULL));
					return 0;
				}
			}
			loop_count_++;
			seek_pos_ = 0;
		}

		data_.resize(info_.channels * info_.samplerate * SECOND_PER_BUFFER);
		sf_count_t const read_size =
		    sf_readf_short(file_.get(), &data_.front(), data_.size() / info_.channels);
		alBufferData(buf, format_, &data_.front(), sizeof(int16_t) * data_.size(),
		             info_.samplerate);
		seek_pos_ += read_size;
		return read_size;
	}
Example #23
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;
}
Example #24
0
signed short*
ags_sndfile_read(AgsPlayable *playable, guint channel, GError **error)
{
  AgsSndfile *sndfile;
  signed short *buffer, *source;
  guint i;

  sndfile = AGS_SNDFILE(playable);

  source = (signed short *) malloc((size_t) sndfile->info->channels *
				   sndfile->info->frames *
				   sizeof(signed short));
  
  sf_seek(sndfile->file, 0, SEEK_SET);
  sf_read_short(sndfile->file, source, sndfile->info->frames * sndfile->info->channels);

  buffer = (signed short *) malloc((size_t) sndfile->info->frames *
				   sizeof(signed short));

  for(i = 0; i < sndfile->info->frames; i++){
    buffer[i] = source[i * sndfile->info->channels + channel];
  }

  free(source);

  return(buffer);
}
Example #25
0
void SoundFileStream::load( SNDFILE *sf, const SF_INFO &info, sf_count_t beg, sf_count_t dur )
{
  delete[] _data;

  _dataOffset = beg;
  _dataSize = dur;

  _data = new short [_dataSize * info.channels];
  sf_seek( sf, _dataOffset, SEEK_SET);

  if (info.format & SF_FORMAT_FLOAT || info.format & SF_FORMAT_DOUBLE)
  {
    // libsndfile reading float into short is broken for non-power-of-two channel counts
    int sampleCount = _dataSize * info.channels;
    float *tmp = new float [sampleCount];
    _dataSize = sf_readf_float( sf, tmp, _dataSize );
    for (int i = 0; i < sampleCount; ++i)
        _data[i] = std::max( -1.f, std::min( 1.f, tmp[i] ) ) * std::numeric_limits<short>::max();
    delete[] tmp;
  }
  else
  {
    _dataSize = sf_readf_short( sf, _data, _dataSize );
  }

  _ch = info.channels;
  _beg = _dataOffset;
  _dur = _dataSize;
}
Example #26
0
int64_t
ad_seek_sndfile(WfDecoder* d, int64_t pos)
{
	SndfileDecoder* priv = (SndfileDecoder*)d->d;
	if (!priv) return -1;
	return sf_seek(priv->sffile, pos, SEEK_SET);
}
bool SFReader::Seek_(int64 frame_offset)
{
 // FIXME error condition
 if(sf_seek(sf, frame_offset, SEEK_SET) != frame_offset)
  return(false);
 return(true);
}
sf_count_t Processor::read_frames(size_t start){
    size_t count = m_bufsize;
    sf_count_t readCount = 0;
    if (!m_file || !m_channelCount) {
        std::cerr << "no file or no channel" << std::endl;
        return 0;
    }
    if ((long)start >= m_fileInfo.frames) {
        std::cerr << "end of file" << std::endl;
	    return 0;
    }
    if (long(start + m_bufsize) > m_fileInfo.frames) {
	    count = m_fileInfo.frames - start;
    }
    if (sf_seek(m_file, start, SEEK_SET) < 0) {
        std::cerr << "sf_seek failed" << std::endl;
	    exit(EXIT_FAILURE);
	}
    if ((readCount = sf_readf_float(m_file, m_buffer, count)) < 0) {
        std::cerr << "sf_readf_float failed" << std::endl;
	    exit(EXIT_FAILURE);
	}
    //std::cout << readCount << std::endl;
    return readCount;
}
Example #29
0
int SoundStream::updateState(double time, double dt){
   int status = PV_SUCCESS;
   assert(fileStream);
    
    // if (time >= nextSampleTime) {
    //     nextSampleTime += (1.0 / sampleRate);
       //Read 1 frame
       int numRead = sf_readf_float(fileStream, soundBuf, 1);
       //EOF
       if(numRead == 0){
          sf_seek(fileStream, 0, SEEK_SET);
          numRead = sf_readf_float(fileStream, soundBuf, 1);
          if(numRead == 0){
             fprintf(stderr, "SoundStream:: Fatal error, is the file empty?\n");
             exit(EXIT_FAILURE);
          }
          std::cout << "Rewinding sound file\n";
       }
       else if(numRead > 1){
          fprintf(stderr, "SoundStream:: Fatal error, numRead is bigger than 1\n");
          exit(EXIT_FAILURE);
       }
       for(int fi = 0; fi < getLayerLoc()->nf; fi++){
          soundData[fi] = soundBuf[fi];
       }
   // }
    
   return status;
}
void
WavFileReader::getInterleavedFrames(size_t start, size_t count,
				    SampleBlock &results) const
{
    if (count == 0) return;
    results.clear();
    results.reserve(count * m_fileInfo.channels);

    QMutexLocker locker(&m_mutex);

    if (!m_file || !m_channelCount) {
        return;
    }

    if ((long)start >= m_fileInfo.frames) {
//        SVDEBUG << "WavFileReader::getInterleavedFrames: " << start
//                  << " > " << m_fileInfo.frames << endl;
	return;
    }

    if (long(start + count) > m_fileInfo.frames) {
	count = m_fileInfo.frames - start;
    }

    sf_count_t readCount = 0;

    if (start != m_lastStart || count != m_lastCount) {

	if (sf_seek(m_file, start, SEEK_SET) < 0) {
//            std::cerr << "sf_seek failed" << std::endl;
	    return;
	}
	
	if (count * m_fileInfo.channels > m_bufsiz) {
//	    std::cerr << "WavFileReader: Reallocating buffer for " << count
//		      << " frames, " << m_fileInfo.channels << " channels: "
//		      << m_bufsiz << " floats" << std::endl;
	    m_bufsiz = count * m_fileInfo.channels;
	    delete[] m_buffer;
	    m_buffer = new float[m_bufsiz];
	}
	
	if ((readCount = sf_readf_float(m_file, m_buffer, count)) < 0) {
//            std::cerr << "sf_readf_float failed" << std::endl;
	    return;
	}

	m_lastStart = start;
	m_lastCount = readCount;
    }

    for (size_t i = 0; i < count * m_fileInfo.channels; ++i) {
        if (i >= m_bufsiz) {
            std::cerr << "INTERNAL ERROR: WavFileReader::getInterleavedFrames: " << i << " >= " << m_bufsiz << std::endl;
        }
	results.push_back(m_buffer[i]);
    }

    return;
}