Example #1
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;
   }
}
int fluid_sample_import_compute_file_samples(char * filepath, long* nbFrames, int* nbChannels) {
	SNDFILE *		infile = NULL;
	SF_INFO			sfinfo;
	int 			bytesPerSample;
	int err;

	// open file, read info
	infile = sf_open_read (filepath, &sfinfo) ;
	if (!infile) {
		return FLUIDXTRAERR_OPENREADFILE;
	}
    
	bytesPerSample = sfinfo.pcmbitwidth/8;
	if (bytesPerSample != 2) {
        if (infile) sf_close (infile);
        return FLUIDXTRAERR_BADFILEFORMAT;
    }
	
	*nbFrames = (long)sfinfo.samples;
    *nbChannels = sfinfo.channels;
    
    if (infile) sf_close (infile);

    err = 0;
    return err;
}
Example #3
0
int		main (int argc, char *argv[])
{   SNDFILE	*file ;
    SF_INFO sfinfo ;
    int		k, count, max = 0, total = 0 ;

    if (argc < 2)
    {   printf ("Expecting input file name.\n") ;
        return 0 ;
    } ;

    if (! (file = sf_open_read (argv [1], &sfinfo)))
    {   printf ("sf_open_read failed with error : ") ;
        sf_perror (NULL) ;
        exit (1) ;
    } ;

    while ((count = sf_read_short (file, buffer, BUFFER_SIZE)))
    {   for (k = 0 ; k < count ; k++)
            if (abs (buffer [k]) > max)
                max = abs (buffer [k]) ;
        total += count ;
    } ;

    printf ("Total         : %d\n", total) ;
    printf ("Maximun value : %d\n", max) ;

    sf_close (file) ;

    return 0 ;
} /* main */
Example #4
0
/** 
 * @brief  Open a file and check the format
 *
 * @param filename [in] file name to open
 * 
 * @return TRUE on success, FALSE on failure.
 */
static boolean
adin_sndfile_open(char *filename)
{
#ifndef HAVE_LIBSNDFILE_VER1
  sinfo.samplerate = sfreq;
  sinfo.pcmbitwidth = 16;
  sinfo.channels = 1;
#endif
  sinfo.format = 0x0;
  if ((sp = 
#ifdef HAVE_LIBSNDFILE_VER1
       sf_open(filename, SFM_READ, &sinfo)
#else
       sf_open_read(filename, &sinfo)
#endif
       ) == NULL) {
    /* retry assuming raw format */
    sinfo.samplerate = sfreq;
    sinfo.channels = 1;
#ifdef HAVE_LIBSNDFILE_VER1
    sinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16 | SF_ENDIAN_BIG;
#else
    sinfo.pcmbitwidth = 16;
    sinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_BE;
#endif
    if ((sp =
#ifdef HAVE_LIBSNDFILE_VER1
	 sf_open(filename, SFM_READ, &sinfo)
#else
	 sf_open_read(filename, &sinfo)
#endif
	 ) == NULL) {
      sf_perror(sp);
      jlog("Error: adin_sndfile: failed to open speech data: \"%s\"\n",filename);
    }
  }
  if (sp == NULL) {		/* open failure */
    return FALSE;
  }
  /* check its format */
  if (! check_format(&sinfo)) {
    return FALSE;
  }
  return TRUE;
}
SNDFILE *sf_open(const char *path, int mode, SF_INFO *info)
{
    if (path == NULL || info == NULL)
        return NULL;
    switch (mode) {
    case SFM_READ:
        return sf_open_read(path, info);
    case SFM_WRITE:
        return sf_open_write(path, info);
    default:
        return NULL;
    }
}
int fluid_sample_import_file(char * filepath, short *data, long seekPos, long nbFramesToLoad, long *nbFramesLoaded, int *samplerate, int *nbchannels)
{
	int err;
	int 			bytesPerSample;
	int				bytesPerFrame;
	unsigned long			fileBytes;
	long 			nbSamplesRead;
	short 			needsTwoComplementing;
	SNDFILE *		infile;
	SF_INFO			sfinfo;
	long            samplesToRead;
    
	// open file, read info
	infile = sf_open_read (filepath, &sfinfo) ;
	if (!infile) {
		return FLUIDXTRAERR_OPENREADFILE;
	}

	bytesPerSample = sfinfo.pcmbitwidth/8;
	if (bytesPerSample != 2) {
		err = FLUIDXTRAERR_BADFILEFORMAT;
		goto bail;
	}
	
	bytesPerFrame = sfinfo.channels*bytesPerSample;
	fileBytes = (unsigned long)sfinfo.samples*bytesPerFrame;
	needsTwoComplementing = (sfinfo.format & SF_FORMAT_AIFF) && (bytesPerSample == 1);

    if (seekPos > 0) {
        off_t res =	sf_seek(infile, seekPos, SEEK_SET);
        if (res < 0) {
            err = FLUIDXTRAERR_SEEKFILE;
            *nbFramesLoaded = 0;
            goto bail;
        }
    }
    
    samplesToRead = (nbFramesToLoad >= 0 ? nbFramesToLoad : sfinfo.samples)*sfinfo.channels;
	nbSamplesRead = sf_read_short (infile, data, samplesToRead);
	
	*nbFramesLoaded = nbSamplesRead/sfinfo.channels;
	*samplerate = sfinfo.samplerate;
	*nbchannels = sfinfo.channels;

	err = 0;
	
bail:
	if (infile) sf_close (infile);

	return err;
}
Example #7
0
bool IsPCM(wxString fName)
{
    wxFile testFile;
    testFile.Open(fName);
    if (!testFile.IsOpened())
        return false;
    testFile.Close();

    SF_INFO    info;
    SNDFILE   *fp;

    fp = sf_open_read(OSFILENAME(fName), &info);

    if (fp) {
        sf_close(fp);
        return true;
    }

    return false;
}
Example #8
0
/* Loads a sound file into a sound structure and sends the data to OpenAL.
   This code is mostly derived from libsndfile example code in Chapter 5. */
int LoadSoundFile(char *filename, sound_p sound)
{
    SNDFILE *file;
    SF_INFO file_info;
    short *buffer_short = NULL;
    u_int8_t *buffer_8 = NULL;
    int16_t *buffer_16 = NULL;
    unsigned int i;

    /* Open the file and retrieve sample information. */
    file = sf_open_read(filename, &file_info);
    if (file == NULL) {
	printf("Unable to open '%s'.\n", filename);
	return -1;
    }
	
    /* Make sure the format is acceptable. */
    if ((file_info.format & 0x0F) != SF_FORMAT_PCM) {
	printf("'%s' is not a PCM-based audio file.\n", filename);
	sf_close(file);
	return -1;
    }
	
    if ((file_info.pcmbitwidth == 8) && (file_info.channels == 1)) {
	sound->format = AL_FORMAT_MONO8;
    } else if ((file_info.pcmbitwidth == 8) && (file_info.channels == 2)) {
	sound->format = AL_FORMAT_STEREO8;
    } else if ((file_info.pcmbitwidth == 16) && (file_info.channels == 1)) {
	sound->format = AL_FORMAT_MONO16;
    } else if ((file_info.pcmbitwidth == 16) && (file_info.channels == 2)) {
	sound->format = AL_FORMAT_STEREO16;
    } else {
	printf("Unknown sample format in %s.\n", filename);
	sf_close(file);
	return -1;
    }
	
    /* Allocate buffers. */
    buffer_short = (short *)malloc(file_info.samples *
				   file_info.channels * 
				   sizeof (short));

    buffer_8 = (u_int8_t *)malloc(file_info.samples *
				  file_info.channels *
				  file_info.pcmbitwidth / 8);

    buffer_16 = (int16_t *)buffer_8;

    if (buffer_short == NULL || buffer_8 == NULL) {
	printf("Unable to allocate enough memory for '%s'.\n", filename);
	goto error_cleanup;
    }

    /* Read the entire sound file. */
    if (sf_readf_short(file,buffer_short,file_info.samples) == (size_t)-1) {
	printf("Error while reading samples from '%s'.\n", filename);
	goto error_cleanup;
    }
	
    /* Convert the data to the correct format. */
    for (i = 0; i < file_info.samples * file_info.channels; i++) {
	if (file_info.pcmbitwidth == 8) {
	    /* Convert the sample from a signed short to an unsigned byte */
	    buffer_8[i] = (u_int8_t)((short)buffer_short[i] + 128);
	} else {
	    buffer_16[i] = (int16_t)buffer_short[i];
	}
    }
	
    /* Fill in the sound data structure. */
    sound->freq = file_info.samplerate;
    sound->size = file_info.samples * file_info.channels *
	file_info.pcmbitwidth / 8;

    /* Give our sound data to OpenAL. */
    alGenBuffers(1, &sound->name);
    if (alGetError() != AL_NO_ERROR) {
	printf("Error creating an AL buffer name for %s.\n", filename);
	goto error_cleanup;
    }

    alBufferData(sound->name, sound->format, buffer_8, sound->size, sound->freq);
    if (alGetError() != AL_NO_ERROR) {
	printf("Error sending buffer data to OpenAL for %s.\n", filename);
	goto error_cleanup;
    }
	
    /* Close the file and return success. */
    sf_close(file);
    free(buffer_short);
    free(buffer_8);

    return 0;

 error_cleanup:
    if (file != NULL) fclose(file);
    free(buffer_short);
    free(buffer_8);
    return -1;
}
FILE * OpenSndFile(lame_global_flags *gfp,const char* lpszFileName, int default_samp,
int default_channels)
{
  input_bitrate=0;
  if (gfp->input_format==sf_mp3) {
#ifdef AMIGA_MPEGA
    if (-1==lame_decode_initfile(lpszFileName,&num_channels,&samp_freq,&input_bitrate,&num_samples)) {
      fprintf(stderr,"Error reading headers in mp3 input file %s.\n", lpszFileName);
      exit(1);
    }
#endif
#ifdef HAVEMPGLIB
    if ((musicin = fopen(lpszFileName, "rb")) == NULL) {
      fprintf(stderr, "Could not find \"%s\".\n", lpszFileName);
      exit(1);
    }
    if (-1==lame_decode_initfile(musicin,&num_channels,&samp_freq,&input_bitrate,&num_samples)) {
      fprintf(stderr,"Error reading headers in mp3 input file %s.\n", lpszFileName);
      exit(1);
    }
#endif
    gs_wfInfo.samples=num_samples;
    gs_wfInfo.channels=num_channels;
    gs_wfInfo.samplerate=samp_freq;

  } else {

    /* Try to open the sound file */
    /* set some defaults incase input is raw PCM */
    gs_wfInfo.seekable=(gfp->input_format!=sf_raw);  /* if user specified -r, set to not seekable */
    gs_wfInfo.samplerate=default_samp;
    gs_wfInfo.pcmbitwidth=16;
    gs_wfInfo.channels=default_channels;
    if (DetermineByteOrder()==order_littleEndian) {
      if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_BE;
      else gs_wfInfo.format=SF_FORMAT_RAW_LE;
    } else {
      if (gfp->swapbytes) gs_wfInfo.format=SF_FORMAT_RAW_LE;
      else gs_wfInfo.format=SF_FORMAT_RAW_BE;
    }

    gs_pSndFileIn=sf_open_read(lpszFileName,&gs_wfInfo);

        /* Check result */
	if (gs_pSndFileIn==NULL)
	{
	        sf_perror(gs_pSndFileIn);
		fprintf(stderr, "Could not open sound file \"%s\".\n", lpszFileName);
		exit(1);
	}

    if ((gs_wfInfo.format==SF_FORMAT_RAW_LE) || 
	(gs_wfInfo.format==SF_FORMAT_RAW_BE)) 
      gfp->input_format=sf_raw;

#ifdef _DEBUG_SND_FILE
	printf("\n\nSF_INFO structure\n");
	printf("samplerate        :%d\n",gs_wfInfo.samplerate);
	printf("samples           :%d\n",gs_wfInfo.samples);
	printf("channels          :%d\n",gs_wfInfo.channels);
	printf("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
	printf("format            :");

	/* new formats from [email protected]  1/2000 */
        if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_WAV)
	  printf("Microsoft WAV format (big endian). ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AIFF)
	  printf("Apple/SGI AIFF format (little endian). ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AU)
	  printf("Sun/NeXT AU format (big endian). ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_AULE)
	  printf("DEC AU format (little endian). ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_RAW)
	  printf("RAW PCM data. ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_PAF)
	  printf("Ensoniq PARIS file format. ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_SVX)
	  printf("Amiga IFF / SVX8 / SV16 format. ");
	if ((gs_wfInfo.format&SF_FORMAT_TYPEMASK)==SF_FORMAT_NIST)
	  printf("Sphere NIST format. ");

	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM)
	  printf("PCM data in 8, 16, 24 or 32 bits.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_FLOAT)
	  printf("32 bit Intel x86 floats.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ULAW)
	  printf("U-Law encoded.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_ALAW)
	  printf("A-Law encoded.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_IMA_ADPCM)
	  printf("IMA ADPCM.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_MS_ADPCM)
	  printf("Microsoft ADPCM.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_BE)
	  printf("Big endian PCM data.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_LE)
	  printf("Little endian PCM data.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_S8)
	  printf("Signed 8 bit PCM.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_PCM_U8)
	  printf("Unsigned 8 bit PCM.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_FIB)
	  printf("SVX Fibonacci Delta encoding.");
	if ((gs_wfInfo.format&SF_FORMAT_SUBMASK)==SF_FORMAT_SVX_EXP)
	  printf("SVX Exponential Delta encoding.");




	printf("\n");
	printf("pcmbitwidth       :%d\n",gs_wfInfo.pcmbitwidth);
	printf("sections          :%d\n",gs_wfInfo.sections);
	printf("seekable          :\n",gs_wfInfo.seekable);
#endif
  }

  if (gs_wfInfo.samples==MAX_U_32_NUM) {
    struct stat sb;
    /* try to figure out num_samples */
    if (0==stat(lpszFileName,&sb)) {
      /* try file size, assume 2 bytes per sample */
      if (gfp->input_format == sf_mp3) {
	FLOAT totalseconds = (sb.st_size*8.0/(1000.0*GetSndBitrate()));
	gs_wfInfo.samples= totalseconds*GetSndSampleRate();
      }else{
	gs_wfInfo.samples = sb.st_size/(2*GetSndChannels());
      }
    }
  }
  return musicin;    
}
Example #10
0
File: Musicin.c Project: IMSoP/CDex
int main(int argc,char* argv[])
{
	DWORD		dwSamples=0;
	DWORD		dwBufferSize=0;
	HMP2_STREAM	hStream=0;

	CHAR		strFNameIn[MAX_NAME_SIZE]={'\0',};
	CHAR		strFNameOut[MAX_NAME_SIZE]={'\0',};

	FILE*		pFileOut=NULL;

	BYTE*		pPCM=NULL;
	BYTE*		pMP2=NULL;

	DWORD		dwRead=0;
	DWORD		dwWrite=0;
	INT			nTime=0;

	BOOL		bSwapBytes=FALSE;
	BOOL		bDownMixToMono=FALSE;

	MP2ENC_CONFIG	mp2Config={0,};
	SNDFILE*		pSndFile=NULL;
	SF_INFO			wfInfo;

	// Parse command line arguments
	ParseArgs(argc,argv,&mp2Config,&bDownMixToMono,&bSwapBytes,strFNameIn,strFNameOut);

	// Clear sound structure
	memset(&wfInfo,0,sizeof(SF_INFO));

	// Open input file
	if (! ( pSndFile = sf_open_read(strFNameIn,&wfInfo)))
	{
		MP2LibError("Could not open input file %s\n",strFNameIn);
		return -1;
	}

	// Open output file
	pFileOut=fopen(strFNameOut,"wb+");

	if (pFileOut==NULL)
	{
		MP2LibError("Could not create output file %s\n",strFNameOut);
		return -1;
	}

	
	// Init the stream
	MP2EncOpen(&mp2Config,&dwSamples,&dwBufferSize,&hStream);

	// Allocate PCM input buffer
	pPCM=(PBYTE)calloc(dwSamples,sizeof(SHORT));

	// Allocate MP2 output buffer
	pMP2=(PBYTE)calloc(dwBufferSize,1);


	TimeEval(0);
	TimeEval(0);

	while ( (dwRead=(sf_readf_short(pSndFile,(PSHORT)pPCM,dwSamples/2)*2)) >0 )
	{
		// Encode it
		MP2EncEncodeFrame(hStream,dwRead,(PSHORT)pPCM, pMP2,&dwWrite);
		
		if (dwWrite)
		{
			fwrite(pMP2,dwWrite,1,pFileOut);
		}
	}


	// Close the encoder
	MP2EncClose(hStream);

	nTime=TimeEval(1);

	printf ("nTime is %d \n",nTime);

	// free PCM input buffer
	if (pPCM)
		free(pPCM);

	// free MP2 output buffer
	if (pMP2)
		free(pMP2);

	// close input file
	if (pSndFile)
		sf_close(pSndFile);

	// close output file
	if (pFileOut)
		fclose(pFileOut);

	return 0;
}
static	
void	lossy_comp_test_double (char *str, char *filename, int typemajor, int typeminor, double margin)
{	SNDFILE			*file ;
	SF_INFO			sfinfo ;
	int				k, m, seekpos ;
	unsigned int	datalen ;
	double			*orig, *data ;

	printf ("    lossy_comp_test_double : %s ... ", str) ;
	
	datalen = BUFFER_SIZE ;

	orig = (double*) orig_buffer ;
	data = (double*) test_buffer ;
	gen_signal (orig_buffer, datalen) ;
		
	sfinfo.samplerate  = 11025 ;
	sfinfo.samples     = 123456789 ;	/* Ridiculous value. */
	sfinfo.channels    = 1 ;
	sfinfo.pcmbitwidth = 16 ;
	sfinfo.format 	   = (typemajor | typeminor) ;

	if (! (file = sf_open_write (filename, &sfinfo)))
	{	printf ("sf_open_write failed with error : ") ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;
	
	if ((k = sf_write_double (file, orig, datalen, 0)) != datalen)
	{	printf ("sf_write_double failed with double write (%d => %d).\n", datalen, k) ;
		exit (1) ;
		} ;
	sf_close (file) ;
	
	memset (data, 0, datalen * sizeof (double)) ;
	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	
	if (! (file = sf_open_read (filename, &sfinfo)))
	{	printf ("sf_open_read failed with error : ") ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;
	
	if (sfinfo.format != (typemajor | typeminor))
	{	printf ("Returned format incorrect (0x%08X => 0x%08X).\n", (typemajor | typeminor), sfinfo.format) ;
		exit (1) ;
		} ;
	
	if (sfinfo.samples < datalen)
	{	printf ("Too few samples in file. (%d should be a little more than %d)\n", datalen, sfinfo.samples) ;
		exit (1) ;
		} ;
	
	if (sfinfo.samples > (datalen + datalen/2))
	{	printf ("Too many samples in file. (%d should be a little more than %d)\n", datalen, sfinfo.samples) ;
		exit (1) ;
		} ;
	
	if (sfinfo.channels != 1)
	{	printf ("Incorrect number of channels in file.\n") ;
		exit (1) ;
		} ;

	if (sfinfo.pcmbitwidth != 16)
	{	printf ("Incorrect bit width (%d).\n", sfinfo.pcmbitwidth) ;
		exit (1) ;
		} ;

	if ((k = sf_read_double (file, data, datalen, 0)) != datalen)
	{	printf ("double read (%d).\n", k) ;
		exit (1) ;
		} ;

	for (k = 0 ; k < datalen ; k++)
		if (error_function (data [k], orig [k], margin))
		{	printf ("Incorrect sample (A #%d : %d should be %d).\n", k, (int) data [k], (int) orig [k]) ;
			exit (1) ;
			} ;

	if ((k = sf_read_double (file, data, datalen, 0)) != sfinfo.samples - datalen)
	{	printf ("Incorrect read length (%d should be %d).\n", sfinfo.samples - datalen, k) ;
		exit (1) ;
		} ;
		
	for (k = 0 ; k < sfinfo.samples - datalen ; k++)
		if (abs ((int) data [k]) > decay_response (k))
		{	printf ("Incorrect sample (B #%d : abs (%d) should be < %d).\n", datalen + k, (int) data [k], decay_response (k)) ;
			exit (1) ;
			} ;


	/* Now test sf_seek function. */
	
	if ((k = sf_seek (file, 0, SEEK_SET)) != 0)
	{	printf ("Seek to start of file failed (%d).\n", k) ;
		exit (1) ;
		} ;

	for (m = 0 ; m < 3 ; m++)
	{	if ((k = sf_read_double (file, data, datalen/7, 0)) != datalen / 7)
		{	printf ("Incorrect read length (%d => %d).\n", datalen / 7, k) ;
			exit (1) ;
			} ;

		for (k = 0 ; k < datalen/7 ; k++)
			if (error_function (data [k], orig [k + m * (datalen / 7)], margin))
			{	printf ("Incorrect sample (C #%d : %d => %d).\n", k + m * (datalen / 7), (int) orig [k + m * (datalen / 7)], (int) data [k]) ;
				for (m = 0 ; m < 10 ; m++)
					printf ("%d ", (int) data [k]) ;
				printf ("\n") ;
				exit (1) ;
				} ;
		} ;

	/* Now test sf_seek function. */
	
	seekpos = BUFFER_SIZE / 10 ;
	
	/* Check seek from start of file. */
	if ((k = sf_seek (file, seekpos, SEEK_SET)) != seekpos)
	{	printf ("Seek to start of file + %d failed (%d).\n", seekpos, k) ;
		exit (1) ;
		} ;
	if ((k = sf_read_double (file, data, 1, 0)) != 1)
	{	printf ("sf_read_double (file, data, 1) returned %d.\n", k) ;
		exit (1) ;
		} ;
	
	if (error_function (data [0], orig [seekpos], margin))
	{	printf ("sf_seek (SEEK_SET) followed by sf_read_double failed (%d, %d).\n", (int) orig [1], (int) data [0]) ;
		exit (1) ;
		} ;
	
	seekpos += BUFFER_SIZE / 5 ;
	k = sf_seek (file, BUFFER_SIZE / 5, SEEK_CUR) ;
	sf_read_double (file, data, 1, 0) ;
	if (error_function (data [0], orig [seekpos], margin) || k != seekpos + 1)
	{	printf ("sf_seek (SEEK_CUR) followed by sf_read_double failed (%d, %d) (%d, %d).\n", (int) data [0], (int) orig [seekpos], k, seekpos) ;
		exit (1) ;
		} ;
	
	seekpos -= 20 ;
	/* Check seek backward from current position. */
	k = sf_seek (file, -20, SEEK_CUR) ;
	sf_read_double (file, data, 1, 0) ;
	if (error_function (data [0], orig [seekpos], margin) || k != seekpos + 2)
	{	printf ("sf_seek (SEEK_CUR) followed by sf_read_double failed (%d, %d) (%d, %d).\n", (int) data [0], (int) orig [seekpos], k, seekpos) ;
		exit (1) ;
		} ;
	
	/* Check that read past end of file returns number of items. */
	sf_seek (file, (int) datalen, SEEK_SET) ;

 	if ((k = sf_read_double (file, data, datalen, 0)) != sfinfo.samples - datalen)
 	{	printf ("Return value from sf_read_double past end of file incorrect (%d).\n", k) ;
 		exit (1) ;
 		} ;
	
	/* Check seek backward from end. */
	if ((k = sf_seek (file, 5 - (int) sfinfo.samples, SEEK_END)) != 5)
	{	printf ("sf_seek (SEEK_END) returned %d instead of %d.\n", k, 5) ;
		exit (1) ;
		} ;

	sf_read_double (file, data, 1, 0) ;
	if (error_function (data [0], orig [5], margin))
	{	printf ("sf_seek (SEEK_END) followed by sf_read_double failed (%d, %d).\n", (int) data [0], (int) orig [5]) ;
		exit (1) ;
		} ;

	sf_close (file) ;

	printf ("ok\n") ;
} /* lossy_comp_test_double */
Example #12
0
bool ImportPCM(wxWindow * parent,
               wxString fName,
               WaveTrack ** channels[],
               int *numChannels,
               DirManager * dirManager)
{
    SF_INFO       info;
    SNDFILE      *fp;
    sampleFormat  format;

    fp = sf_open_read(OSFILENAME(fName), &info);

    if (!fp) {
        char str[1000];
        sf_error_str((SNDFILE *)NULL, str, 1000);
        wxMessageBox(LAT1CTOWX(str));

        return false;
    }

    wxString progressStr;
    wxString formatName = sf_header_name(info.format & SF_FORMAT_TYPEMASK);
    progressStr.Printf(_("Importing %s File..."),
                       formatName.c_str());

    *numChannels = info.channels;
    *channels = new WaveTrack*[*numChannels];

    if (info.pcmbitwidth > 16)
        format = floatSample;
    else
        format = int16Sample;

    int c;
    for(c=0; c<*numChannels; c++) {
        (*channels)[c] = new WaveTrack(dirManager, format, info.samplerate);
        (*channels)[c]->SetName(TrackNameFromFileName(fName));
        (*channels)[c]->SetChannel(Track::MonoChannel);
    }

    if (*numChannels == 2) {
        (*channels)[0]->SetChannel(Track::LeftChannel);
        (*channels)[1]->SetChannel(Track::RightChannel);
        (*channels)[0]->SetLinked(true);
        (*channels)[1]->SetTeamed(true);
    }

    sampleCount fileTotalFrames = (sampleCount)info.frames;
    sampleCount maxBlockSize = (*channels)[0]->GetMaxBlockSize();

    wxString copyEdit =
        gPrefs->Read(wxT("/FileFormats/CopyOrEditUncompressedData"), wxT("edit"));

    // Fall back to "edit" if it doesn't match anything else
    bool doEdit = true;
    if (copyEdit.IsSameAs(wxT("copy"), false))
        doEdit = false;

    if (doEdit) {
        wxLogDebug(wxT("Importing PCM...ImportPCM \n"));

        // If this mode has been selected, we form the tracks as
        // aliases to the files we're editing, i.e. ("foo.wav", 12000-18000)
        // instead of actually making fresh copies of the samples.

        bool cancelling = false;

        GetActiveProject()->ProgressShow(_("Import"), progressStr);

        for (sampleCount i = 0; i < fileTotalFrames; i += maxBlockSize) {
            sampleCount blockLen = maxBlockSize;
            if (i + blockLen > fileTotalFrames)
                blockLen = fileTotalFrames - i;

            for(c=0; c<*numChannels; c++)
                (*channels)[c]->AppendAlias(fName, i, blockLen, c);

            cancelling = !GetActiveProject()->ProgressUpdate((int)((i*1000.0)/fileTotalFrames));

            if (cancelling)
                i = fileTotalFrames;
        }

        GetActiveProject()->ProgressHide();

        //printf(_("Time elapsed: %d\n"), wxGetElapsedTime());

        if (cancelling) {
            for(c=0; c<*numChannels; c++)
                delete (*channels)[c];
            delete[] (*channels);
            *channels = NULL;

            return false;
        }

        return true;
    }

    // Otherwise, we're in the "copy" mode, where we read in the actual
    // samples from the file and store our own local copy of the
    // samples in the tracks.

    samplePtr srcbuffer = NewSamples(maxBlockSize * (*numChannels),
                                     format);
    samplePtr buffer = NewSamples(maxBlockSize, format);

    sampleCount framescompleted = 0;

    bool cancelling = false;

    GetActiveProject->ProgressShow(_("Import"), progressStr);

    long block;
    do {
        block = maxBlockSize;

        if (format == int16Sample)
            block = sf_readf_short(fp, (short *)srcbuffer, block);
        else
            block = sf_readf_float(fp, (float *)srcbuffer, block);

        if (block) {
            for(c=0; c<(*numChannels); c++) {

                if (format==int16Sample) {
                    if (info.pcmbitwidth == 8) {
                        for(int j=0; j<block; j++)
                            ((short *)buffer)[j] =
                                ((short *)srcbuffer)[(*numChannels)*j+c] << 8;
                    }
                    else {
                        for(int j=0; j<block; j++)
                            ((short *)buffer)[j] =
                                ((short *)srcbuffer)[(*numChannels)*j+c];
                    }
                }
                else
                    for(int j=0; j<block; j++)
                        ((float *)buffer)[j] =
                            ((float *)srcbuffer)[(*numChannels)*j+c];

                (*channels)[c]->Append(buffer, format, block);
            }

            framescompleted += block;
        }

        int progressvalue = (framescompleted > fileTotalFrames) ?
                            fileTotalFrames : framescompleted;

        cancelling =
            !GetActiveProject()->ProgressUpdate((int)((progressvalue*1000.0)/fileTotalFrames));

        if (cancelling)
            block = 0;
    } while (block > 0);

    GetActiveProject()->ProgressHide();

    sf_close(fp);

    //printf("Time elapsed: %d\n", wxGetElapsedTime());

    DeleteSamples(srcbuffer);
    DeleteSamples(buffer);

    if (cancelling) {
        for(c=0; c<*numChannels; c++)
            delete (*channels)[c];
        delete[] (*channels);
        *channels = NULL;

        return false;
    }

    return true;
}
Example #13
0
bool ImportPCM(wxWindow * parent,
               wxString fName, 
               WaveTrack ** channels[],
               int *numChannels,
               DirManager * dirManager)
{
   SF_INFO    info;
   SNDFILE   *fp;

   fp = sf_open_read(fName, &info);

   if (!fp) {
      char str[1000];
      sf_error_str((SNDFILE *)NULL, str, 1000);
      wxMessageBox(str);

      return false;
   }

   wxString progressStr;
   wxString formatName;
   for(int z=0; z<gNumPCMFormats; z++)
      if ((info.format & SF_FORMAT_TYPEMASK) == gPCMFormats[z].id)
         formatName = gPCMFormats[z].name;
   progressStr.Printf("Importing %s file...",
                      formatName);

   *numChannels = info.channels;
   *channels = new WaveTrack*[*numChannels];

   int c;
   for(c=0; c<*numChannels; c++) {
      (*channels)[c] = new WaveTrack(dirManager);
      (*channels)[c]->rate = info.samplerate;
      (*channels)[c]->name = TrackNameFromFileName(fName);
      (*channels)[c]->channel = VTrack::MonoChannel;
   }

   if (*numChannels == 2) {
      (*channels)[0]->channel = VTrack::LeftChannel;
      (*channels)[1]->channel = VTrack::RightChannel;
      (*channels)[0]->linked = true;
   }

   sampleCount fileTotalFrames = (sampleCount)info.samples;
   sampleCount maxBlockSize = (sampleCount)WaveTrack::GetIdealBlockSize();

   wxString copyEdit =
       gPrefs->Read("/FileFormats/CopyOrEditUncompressedData", "edit");

   // Fall back to "edit" if it doesn't match anything else
   bool doEdit = true;          
   if (copyEdit.IsSameAs("copy", false))
      doEdit = false;

   if (doEdit) {

      // If this mode has been selected, we form the tracks as
      // aliases to the files we're editing, i.e. ("foo.wav", 12000-18000)
      // instead of actually making fresh copies of the samples.

      wxProgressDialog *progress = NULL;
      wxYield();
      wxStartTimer();
      wxBusyCursor busy;

      bool cancelling = false;

      for (sampleCount i = 0; i < fileTotalFrames; i += maxBlockSize) {
         sampleCount blockLen = maxBlockSize;
         if (i + blockLen > fileTotalFrames)
            blockLen = fileTotalFrames - i;

         for(c=0; c<*numChannels; c++)
            (*channels)[c]->AppendAlias(fName, i, blockLen, c);

         if (!progress && wxGetElapsedTime(false) > 500) {
            progress =
                new wxProgressDialog("Import", progressStr,
                                     1000,
                                     parent,
                                     wxPD_CAN_ABORT |
                                     wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
         }
         if (progress) {
            cancelling = !progress->Update((int)((i*1000.0)/fileTotalFrames));

            if (cancelling)
               i = fileTotalFrames;
         }
      }

      //printf("Time elapsed: %d\n", wxGetElapsedTime());

      if (progress)
         delete progress;

      if (cancelling) {
         for(c=0; c<*numChannels; c++)
            delete (*channels)[c];
         delete[] (*channels);
         *channels = NULL;

         return false;
      }

      return true;
   }

   // Otherwise, we're in the "copy" mode, where we read in the actual
   // samples from the file and store our own local copy of the
   // samples in the tracks.

   sampleType *srcbuffer = new short[maxBlockSize * (*numChannels)];
   sampleType *buffer = new short[maxBlockSize];

   unsigned long framescompleted = 0;

   wxProgressDialog *progress = NULL;
   wxYield();
   wxStartTimer();
   wxBusyCursor busy;

   bool cancelling = false;

   long block;
   do {
      block = maxBlockSize;
      block = sf_readf_short(fp, srcbuffer, block);

      if (block) {
         for(c=0; c<(*numChannels); c++) {
            for(int j=0; j<block; j++)
               buffer[j] = srcbuffer[(*numChannels)*j+c];
            (*channels)[c]->Append(buffer, block);
         }

         framescompleted += block;
      }

      if (!progress && wxGetElapsedTime(false) > 500) {
         progress =
            new wxProgressDialog("Import", progressStr,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         int progressvalue = (framescompleted > fileTotalFrames) ?
             fileTotalFrames : framescompleted;

         cancelling =
            !progress->Update((int)((progressvalue*1000.0)/fileTotalFrames));

         if (cancelling)
            block = 0;
      }
   } while (block > 0);

   sf_close(fp);

   //printf("Time elapsed: %d\n", wxGetElapsedTime());

   if (progress)
      delete progress;

   delete[] srcbuffer;
   delete[] buffer;

   if (cancelling) {
      for(c=0; c<*numChannels; c++)
         delete (*channels)[c];
      delete[] (*channels);
      *channels = NULL;

      return false;
   }

   return true;
}
Example #14
0
int LoadSoundFile(char *filename, unsigned int *rate, unsigned int *channels,
                  unsigned int *bits, u_int8_t **buf, unsigned int *buflen)
{
    SNDFILE *file;
    SF_INFO file_info;
    short *buffer_short = NULL;
    u_int8_t *buffer_8 = NULL;
    int16_t *buffer_16 = NULL;
    unsigned int i;
	
    /* Open the file and retrieve sample information. */
    file = sf_open_read(filename, &file_info);
    if (file == NULL) {
	printf("Unable to open '%s'.\n", filename);
	return -1;
    }
	
    /* Make sure the format is acceptable. */
    if ((file_info.format & 0x0F) != SF_FORMAT_PCM) {
	printf("'%s' is not a PCM-based audio file.\n", filename);
	sf_close(file);
	return -1;
    }
	
    if ((file_info.pcmbitwidth != 8) && (file_info.pcmbitwidth != 16)) {
	printf("'%s' uses an unrecognized sample size.\n", filename);
	sf_close(file);
	return -1;
    }
	
    /* Allocate buffers. */
    buffer_short = (short *)malloc(file_info.samples *
				   file_info.channels * 
				   sizeof (short));

    buffer_8 = (u_int8_t *)malloc(file_info.samples *
				  file_info.channels *
				  file_info.pcmbitwidth / 8);

    buffer_16 = (int16_t *)buffer_8;

    if (buffer_short == NULL || buffer_8 == NULL) {
	printf("Unable to allocate enough memory for '%s'.\n", filename);
	fclose(file);
	free(buffer_short);
	free(buffer_8);
	return -1;
    }

    /* Read the entire sound file. */
    if (sf_readf_short(file,buffer_short,file_info.samples) == (size_t)-1) {
	printf("Error while reading samples from '%s'.\n", filename);
	fclose(file);
	free(buffer_short);
	free(buffer_8);
	return -1;
    }
	
    /* Convert the data to the correct format. */
    for (i = 0; i < file_info.samples * file_info.channels; i++) {
	if (file_info.pcmbitwidth == 8) {
	    /* Convert the sample from a signed short to an unsigned byte */
	    buffer_8[i] = (u_int8_t)((short)buffer_short[i] + 128);
	} else {
	    buffer_16[i] = (int16_t)buffer_short[i];
	}
    }
	
    /* Return the sound data. */
    *rate = file_info.samplerate;
    *channels = file_info.channels;
    *bits = file_info.pcmbitwidth;
    *buf = buffer_8;
    *buflen = file_info.samples * file_info.channels * file_info.pcmbitwidth / 8;
	
    /* Close the file and return success. */
    sf_close(file);
    free(buffer_short);

    return 0;
}