예제 #1
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 */
static ssize_t
sa_sndfile_read( simpleaudio *sa, void *buf, size_t nframes )
{
    SNDFILE *s = (SNDFILE *)sa->backend_handle;
    int n;
    switch ( sa->format ) {
	case SA_SAMPLE_FORMAT_FLOAT:
		n = sf_readf_float(s, buf, nframes);
		break;
	case SA_SAMPLE_FORMAT_S16:
		n = sf_readf_short(s, buf, nframes);
		break;
	default:
		assert(0);
		break;
    }
    if ( n < 0 ) {
	fprintf(stderr, "sf_read: ");
	sf_perror(s);
	return -1;
    }

    if ( sa->rxnoise != 0.0 ) {
	int i;
	float *fbuf = buf;
	float f = sa->rxnoise * 2;
	for ( i=0; i<nframes; i++ )
	    fbuf[i] += (drand48() - 0.5) * f;
    }

    // fprintf(stderr, "sf_read: nframes=%ld n=%d\n", nframes, n);
    return n;
}
예제 #3
0
int
main (int argc, char *argv[])
{   char 		*progname, *infilename, *outfilename ;
    SNDFILE	 	*infile, *outfile ;
    SF_INFO	 	sfinfo ;
    double		normfactor ;

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

    if (argc != 3)
    {   print_usage (progname) ;
        return  1 ;
    } ;

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

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

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

    if (sfinfo.format != (SF_FORMAT_WAV | SF_FORMAT_FLOAT))
    {   fprintf (stderr, "Error : Input file %s is not a 32 bit floating point WAV file.\n", infilename) ;
        return  1 ;
    } ;

    sfinfo.format = (SF_FORMAT_AIFF | SF_FORMAT_PCM_24) ;

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

    if (normfactor < 1.0 && normfactor > 0.0)
        normfactor = ((double) 0x400000) ;
    else
        normfactor = 1.0 ;

    fprintf (stderr, "normfactor : %g\n", normfactor) ;

    if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)))
    {   fprintf (stderr, "Not able to open output file %s.\n", outfilename) ;
        return  1 ;
    } ;

    copy_data (outfile, infile, BUFFER_LEN / sfinfo.channels, normfactor) ;

    sf_close (infile) ;
    sf_close (outfile) ;

    return 0 ;
} /* main */
예제 #4
0
SNDFILE *xsf_open(const char *path, int mode, SF_INFO *sfinfo)
{
  SNDFILE *s = sf_open(path, mode, sfinfo);
  if(!s) {
    sf_perror(s);
    exit(EXIT_FAILURE);
  }
  return s;
}
예제 #5
0
/** 
 * End recording.
 * 
 * @return TRUE on success, FALSE on failure.
 */
boolean
adin_sndfile_end()
{
  /* close files */
  if (sf_close(sp) != 0) {
    sf_perror(sp);
    jlog("Error: adin_sndfile: failed to close\n");
    return FALSE;
  }
  return TRUE;
}
예제 #6
0
void write_signal_file(const char *name, const float *data, int n)
{
  SF_INFO sfi;
  sfi.channels = 1;
  sfi.samplerate = 44100;
  sfi.frames = 0;
  sfi.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;
  SNDFILE *sfp = sf_open(name, SFM_WRITE, &sfi);
  if(!sfp) {
    sf_perror(sfp);
    exit(EXIT_FAILURE);
  }
  int err = sf_write_float(sfp, data, n);
  if(err == -1) {
    fprintf(stderr, "sf_write_float() failed\n");
    sf_perror(sfp);
    exit(EXIT_FAILURE);
  }
  sf_close(sfp);
}
static int
sa_sndfile_open_stream(
		simpleaudio *sa,
		const char *backend_device,
		sa_direction_t sa_stream_direction,
		sa_format_t sa_format,
		unsigned int rate, unsigned int channels,
		char *app_name, char *stream_name )
{
    const char *path = stream_name;

    int sf_format;
    switch ( sa->format ) {
	case SA_SAMPLE_FORMAT_FLOAT:
		sf_format = SF_FORMAT_FLOAT;
		break;
	case SA_SAMPLE_FORMAT_S16:
		sf_format = SF_FORMAT_PCM_16;
		break;
	default:
		assert(0);
    }

    /* setting for SA_STREAM_PLAYBACK (file write) */
    SF_INFO sfinfo = {
	.format = sf_format,
	.samplerate = rate,
	.channels = channels,
    };

    if ( sa_stream_direction == SA_STREAM_PLAYBACK )
	sfinfo.format = sndfile_format_from_path(path) | sf_format;

    /* Create the recording stream */
    SNDFILE *s;
    s = sf_open(path,
	    sa_stream_direction == SA_STREAM_RECORD ? SFM_READ : SFM_WRITE,
	    &sfinfo);
    if ( !s ) {
	fprintf(stderr, "%s: ", path);
	sf_perror(s);
        return 0;
    }

    /* good or bad to override these? */
    sa->rate = sfinfo.samplerate;
    sa->channels = sfinfo.channels;

    sa->backend_handle = s;
    sa->backend_framesize = sa->channels * sa->samplesize; 

    return 1;
}
예제 #8
0
void convert_mono_to_stereo(char* filepath, char* new_file_name){
    SNDFILE *infile, *outfile;
    SF_INFO sfinfo, sfOutInfo;
    sf_count_t readCount;
    double *input_buffer, *output_buffer;

    sfinfo.format=0;
    if (! (infile = sf_open(filepath, SFM_READ, &sfinfo))) {
        printf ("Not able to open input file %s.\n", filepath) ;
        sf_perror(NULL);
    }

    input_buffer = malloc(sfinfo.frames * sizeof(double));
    output_buffer = malloc(sfinfo.frames * sizeof(double));

    readCount = sf_read_double(infile, input_buffer, sfinfo.frames);

    for(int i = 0; i < sfinfo.frames * 2; i+=2){
        output_buffer[i] = input_buffer[i/2];
    }

    for(int i = 0; i < sfinfo.frames *2; i+=2){
        output_buffer[i] = input_buffer[(int)(i/2) - 1];
    }

    sfOutInfo.frames = sfinfo.frames * 2;
    sfOutInfo.samplerate = sfinfo.samplerate;
    sfOutInfo.channels = sfinfo.channels * 2;
    sfOutInfo.format = SF_FORMAT_AIFF | SF_FORMAT_PCM_16;

    if (! (outfile = sf_open(filepath, SFM_WRITE, &sfOutInfo))) {
        printf ("Not able to open input file %s.\n", filepath) ;
        sf_perror(NULL);
    }

    sf_close(infile);
    sf_close(outfile);
    free(input_buffer);
    free(output_buffer);
}
예제 #9
0
void
soundfile_die(soundfile_t *sf, char *format,  ...) {
	va_list ap;
	if (myname)
		fprintf(stderr, "%s: ", myname);
	va_start(ap, format);
	vfprintf(stderr, format, ap);
	if (sf && sf->t == sft_libsndfile)
		sf_perror(sf->p);
	if (verbosity > 9)
		abort();
	exit(1);
}
예제 #10
0
void
sdie(SNDFILE *sf, char *format,  ...) {
	va_list ap;
	if (myname)
		fprintf(stderr, "%s: ", myname);
	va_start(ap, format);
	vfprintf(stderr, format, ap);
	if (sf)
		sf_perror(sf);
	if (verbosity > 9)
		abort();
	exit(1);
}
예제 #11
0
float *read_signal_file(const char *name, int nc, int *n)
{
  SF_INFO sfi;
  SNDFILE *sfp = sf_open(name, SFM_READ, &sfi);
  if(!sfp) {
    fprintf(stderr, "sf_open() failed\n");
    sf_perror(sfp);
    exit(EXIT_FAILURE);
  }
  if(sfi.channels != nc) {
    fprintf(stderr, "illegal channel count: %d\n", sfi.channels);
    exit(EXIT_FAILURE);
  }
  *n = sfi.frames * sfi.channels;
  float *data = xmalloc(*n * sizeof(float));
  int err = sf_read_float(sfp, data, *n);
  if(err == -1) {
    fprintf(stderr, "sf_read_float() failed\n");
    sf_perror(sfp);
    exit(EXIT_FAILURE);
  }
  return data;
}
예제 #12
0
/** 
 * Try to read @a sampnum samples and returns actual sample num recorded.
 * 
 * @param buf [out] samples obtained in this function
 * @param sampnum [in] wanted number of samples to be read
 * 
 * @return actural number of read samples, -1 if EOF, -2 if error.
 */
int
adin_sndfile_read(SP16 *buf, int sampnum)
{
  int cnt;

  cnt = sf_read_short(sp, buf, sampnum);
  if (cnt == 0) {		/* EOF */
    return -1;
  } else if (cnt < 0) {		/* error */
    sf_perror(sp);
    sf_close(sp);
    return -2;		/* error */
  }
  return cnt;
}
예제 #13
0
int 
main (void) 
{	SNDFILE	*file ; 
	SF_INFO	sfinfo ; 
	int		k ; 
	short	*buffer ; 
	 
	if (! (buffer = malloc (2 * SAMPLE_COUNT * sizeof (short)))) 
	{	printf ("Malloc failed.\n") ; 
		exit (0) ; 
		} ; 

	memset (&sfinfo, 0, sizeof (sfinfo)) ; 
	 
	sfinfo.samplerate  = SAMPLE_RATE ; 
	sfinfo.frames     = SAMPLE_COUNT ; 
	sfinfo.channels	   = 1 ; 
	sfinfo.format      = (SF_FORMAT_WAV | SF_FORMAT_PCM_16) ; 

	if (! (file = sf_open ("sine.wav", SFM_WRITE, &sfinfo))) 
	{	printf ("Error : Not able to open output file.\n") ; 
		return 1 ; 
		} ; 

	if (sfinfo.channels == 1)
	{	for (k = 0 ; k < SAMPLE_COUNT ; k++)	 
			buffer [k] = AMPLITUDE * sin (LEFT_FREQ * 2 * k * M_PI) ; 
		}
	else if (sfinfo.channels == 2)
	{	for (k = 0 ; k < SAMPLE_COUNT ; k++)	 
		{	buffer [2*k  ] = AMPLITUDE * sin (LEFT_FREQ * 2 * k * M_PI) ; 
			buffer [2*k+1] = AMPLITUDE * sin (RIGHT_FREQ * 2 * k * M_PI) ; 
			} ; 
		}
	else
	{	printf ("makesine can only generate mono or stereo files.\n") ;
		exit (1) ;
		} ;
		
	if (sf_write_short (file, buffer, sfinfo.channels * SAMPLE_COUNT) != 
											sfinfo.channels * SAMPLE_COUNT) 
		sf_perror (file) ; 

	sf_close (file) ; 
	return	 0 ; 
} /* main */ 
예제 #14
0
void convert_file_to_AIFF(char* filepath) {
    SNDFILE *infile;
    SF_INFO sfinfo;
    sf_count_t readCount;

    sfinfo.format=0;
    if (! (infile = sf_open(filepath, SFM_READ, &sfinfo))) {
        printf ("Not able to open input file %s.\n", filepath) ;
        sf_perror(NULL);
    }

    printf("%s%d\n", "Frames: ", (int) sfinfo.frames);
    printf("%s%d\n", "Samplerate: ", sfinfo.samplerate);
    printf("%s%d\n", "Channels: ", sfinfo.channels);
    sf_close(infile);

}
예제 #15
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;
}
예제 #16
0
int     main (int argc, char *argv[])
{	static	char	strbuffer [BUFFER_LEN] ;
	unsigned int	linecount ;
	char 		*progname, *infilename ;
	SNDFILE	 	*infile ;
	SF_INFO	 	sfinfo ;
	int			k, start, readcount ;

	progname = strrchr (argv [0], '/') ;
	progname = progname ? progname + 1 : argv [0] ;
		
	if (argc != 2)
	{	print_usage (progname) ;
		return  1 ;
		} ;
		
	infilename = argv [1] ;
		
	if (! (infile = sf_open (infilename, SFM_READ, &sfinfo)))
	{	printf ("Error : Not able to open input file %s.\n", infilename) ;
		sf_perror (NULL) ;
		sf_command (NULL, SFC_GET_LOG_INFO, strbuffer, BUFFER_LEN) ;
		printf (strbuffer) ;
		return  1 ;
		} ;
		
	start = 0 ;
	
	linecount = 24 ;
	
	while ((readcount = sf_read_raw (infile, strbuffer, linecount)))
	{	printf ("%08X: ", start) ;
		for (k = 0 ; k < readcount ; k++)
			printf ("%02X ", strbuffer [k] & 0xFF) ;
		for (k = readcount ; k < 16 ; k++)
			printf ("   ") ;
		printf ("\n") ;
		start += readcount ;
		} ;

	sf_close (infile) ;
	
	return 0 ;
} /* main */
예제 #17
0
static	void	
stdout_test	(char *str, int typemajor, int count)
{	static	short	data [BUFFER_LEN] ;

	SNDFILE			*file ;
	SF_INFO			sfinfo ;
	unsigned int	k, total, this_write ;
	
	fprintf (stderr, "    %-5s : writing %d samples to stdout  ... ", str, count) ;
	
	sfinfo.samplerate  = 44100 ;
	sfinfo.pcmbitwidth = 16 ;
	sfinfo.format 	   = (typemajor | SF_FORMAT_PCM) ;
	sfinfo.channels    = 1 ;
	sfinfo.samples     = 0 ;

	/* Create some random data. */
	for (k = 0 ; k < BUFFER_LEN ; k++)
		data [k] = (rand () % 2000) ;
		
	if (! (file = sf_open_write ("-", &sfinfo)))
	{	fprintf (stderr, "sf_open_write failed with error : ") ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;

	total = 0 ;
	
	while (total < count)
	{	this_write = (count - total > BUFFER_LEN) ? BUFFER_LEN : count - total ;
		if ((k = sf_write_short (file, data, this_write)) != this_write)
		{	fprintf (stderr, "sf_write_short # %d failed with short write (%d ->%d)\n", count, this_write, k) ;
			exit (1) ;
			} ;
		total += k ;
		} ;
	
	sf_close (file) ;
	
	fprintf (stderr, "ok\n") ;

	return ;
} /* stdout_test */
static ssize_t
sa_sndfile_write( simpleaudio *sa, void *buf, size_t nframes )
{
    // fprintf(stderr, "sf_write: nframes=%ld\n", nframes);
    SNDFILE *s = (SNDFILE *)sa->backend_handle;
    int n;
    switch ( sa->format ) {
	case SA_SAMPLE_FORMAT_FLOAT:
		n = sf_writef_float(s, buf, nframes);
		break;
	case SA_SAMPLE_FORMAT_S16:
		n = sf_writef_short(s, buf, nframes);
		break;
	default:
		assert(0);
		break;
    }
    if ( n < 0 ) {
	fprintf(stderr, "sf_write: ");
	sf_perror(s);
	return -1;
    }
    return n;
}
예제 #19
0
int main(int argc, char *argv[])
{
  SNDFILE*	in_sf;
  SNDFILE*	out_sf;
  SF_INFO	in_info;
  SF_INFO	out_info;
  unsigned int nAppend = 0; // number of frames to append beyond input file

  if (argc < 3) {
    fprintf(stderr,"*** USAGE: %s input_soundfile output_soundfile\n",argv[0]);
    exit(1);
  }

  nAppend = loptrm(&argc, argv, "--continue", "-c", 0);
    
  CMDUI* interface = new CMDUI(argc, argv);
  DSP.buildUserInterface(interface);
  interface->process_command();

  // open input file
  in_info.format = 0;
  in_sf = sf_open(interface->input_file(), SFM_READ, &in_info);
  if (in_sf == NULL) {
    fprintf(stderr,"*** Input file not found.\n");
    sf_perror(in_sf); 
    exit(1); 
  }

  // open output file
  out_info = in_info;
  out_info.format = in_info.format;
  out_info.channels = DSP.getNumOutputs();
  out_sf = sf_open(interface->output_file(), SFM_WRITE, &out_info);
  if (out_sf == NULL) { 
    fprintf(stderr,"*** Cannot write output file.\n");
    sf_perror(out_sf); 
    exit(1); 
  }

  // create separator and interleaver
  Separator   sep(kFrames, in_info.channels, DSP.getNumInputs());
  Interleaver ilv(kFrames, DSP.getNumOutputs());

  // init signal processor
  DSP.init(in_info.samplerate);
  //DSP.buildUserInterface(interface);
  interface->process_init();

  // process all samples
  int nbf;
  do {
    nbf = READ_SAMPLE(in_sf, sep.input(), kFrames);
    sep.separate();
    DSP.compute(nbf, sep.outputs(), ilv.inputs());
    ilv.interleave();
    sf_writef_float(out_sf, ilv.output(), nbf);
    //sf_write_raw(out_sf, ilv.output(), nbf);
  } while (nbf == kFrames);

  sf_close(in_sf);

  // compute tail, if any
  if (nAppend>0) {
    FAUSTFLOAT *input = (FAUSTFLOAT*) calloc(nAppend * DSP.getNumInputs(), sizeof(FAUSTFLOAT));
    FAUSTFLOAT *inputs[1] = { input };
    Interleaver ailv(nAppend, DSP.getNumOutputs());
    DSP.compute(nAppend, inputs, ailv.inputs());
    ailv.interleave();
    sf_writef_float(out_sf, ailv.output(), nAppend);
  }

  sf_close(out_sf);
}
예제 #20
0
int		
main (void)
{	static	short	buffer [BUFFER_SIZE] ;
	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	int			k, filetype ;	
	char		*filename = "headerless.wav" ;

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

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

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

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

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

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

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

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

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

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

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

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

	return 0;
} /* main */
int main(int argc, char *argv[]) {
    long l_lWritecount = 0;
    pa_simple *l_SSimple = NULL;
    long l_lSizeonesec = (PLAY_FRAMES_PER_BUFFER * 2) * sizeof(float);

    /* Alloc size for one block */
    float *l_fSampleBlock = (float *)malloc(l_lSizeonesec);
    int l_iError = 0;
    struct sigaction l_SSa;

    static const pa_sample_spec l_SSs = {
         .format = PA_SAMPLE_FLOAT32,
         .rate = 44100,
         .channels = 2
    };

    printf("Playing file: '%s'\n", argv[1]);

    /* Open file. Because this is just a example we asume
      What you are doing and give file first argument */
    if (! (m_SInfile = sf_open(argv[1], SFM_READ, &m_SSfinfo))) {
        printf ("Not able to open input file %s.\n", argv[1]) ;
        sf_perror (NULL) ;
        return  1 ;
    }

    l_SSa.sa_flags = SA_SIGINFO;
    sigemptyset(&l_SSa.sa_mask);
    l_SSa.sa_sigaction = handler;

    if (sigaction(SIGINT, &l_SSa, NULL) == -1) {
        printf("Can't set SIGINT handler!\n");
        sf_close(m_SInfile);
        return -1;
    }

    if (sigaction(SIGHUP, &l_SSa, NULL) == -1) {
        printf("Can't set SIGHUP handler!\n");
        sf_close(m_SInfile);
        return -1;
    }

    /* Create a new playback stream */
    if (!(l_SSimple = pa_simple_new(NULL, "Simple example Pulseaudio playback application", PA_STREAM_PLAYBACK, NULL, "Playback", &l_SSs, NULL, NULL, &l_iError))) {
       fprintf(stderr, "main: pa_simple_new() failed: %s\n", pa_strerror(l_iError));
       goto exit;
    }

    fflush(stdout);

    while(1) {
        l_lWritecount = sf_read_float(m_SInfile, l_fSampleBlock, l_lSizeonesec / 4);

        if(l_lWritecount <= 0) {
            printf("** File has ended!\n");
            break;
        }

        if (pa_simple_write(l_SSimple, l_fSampleBlock, l_lWritecount * 4, &l_iError) < 0) {
            fprintf(stderr, "main: pa_simple_write() failed: %s (%ld)\n", pa_strerror(l_iError), l_lWritecount / 2);
            goto exit;
        }

        if(m_iLoop) {
           break;
        }
    }

    /* Make sure that every single sample was played */
    if (pa_simple_drain(l_SSimple, &l_iError) < 0) {
        fprintf(stderr, "main: pa_simple_drain() failed: %s\n", pa_strerror(l_iError));
        goto exit;
    }

exit:
    sf_close(m_SInfile);
    if (l_SSimple)
       pa_simple_free(l_SSimple);
    return 0;
}
예제 #22
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 */
예제 #23
0
void init_state_and_scan_work_item(struct filename_list_node *fln, struct scan_opts *opts)
{
    struct file_data *fd = (struct file_data *) fln->d;

    struct input_ops* ops = NULL;
    struct input_handle* ih = NULL;
    int r128_mode = EBUR128_MODE_I;
    unsigned int i;
    int *channel_map;

    int result;
    float *buffer = NULL;
    size_t nr_frames_read;

#ifdef USE_SNDFILE
    SNDFILE *outfile = NULL;
#endif

    result = open_plugin(fln->fr->raw, fln->fr->display, &ops, &ih);
    if (result) {
        g_mutex_lock(progress_mutex);
        elapsed_frames += fd->number_of_frames;
        g_cond_broadcast(progress_cond);
        g_mutex_unlock(progress_mutex);
        goto free;
    }

    if (opts->lra)
        r128_mode |= EBUR128_MODE_LRA;
    if (opts->peak) {
        if (!strcmp(opts->peak, "sample") || !strcmp(opts->peak, "all"))
            r128_mode |= EBUR128_MODE_SAMPLE_PEAK;
#ifdef USE_SPEEX_RESAMPLER
        if (!strcmp(opts->peak, "true") || !strcmp(opts->peak, "dbtp") ||
            !strcmp(opts->peak, "all"))
            r128_mode |= EBUR128_MODE_TRUE_PEAK;
#endif
    }
    if (opts->histogram)
        r128_mode |= EBUR128_MODE_HISTOGRAM;

    fd->st = ebur128_init(ops->get_channels(ih),
                          ops->get_samplerate(ih),
                          r128_mode);

    channel_map = g_malloc(fd->st->channels * sizeof(int));
    if (!ops->set_channel_map(ih, channel_map)) {
        for (i = 0; i < fd->st->channels; ++i) {
            ebur128_set_channel(fd->st, i, channel_map[i]);
        }
    }
    free(channel_map);

    if (fd->st->channels == 1 && opts->force_dual_mono) {
        ebur128_set_channel(fd->st, 0, EBUR128_DUAL_MONO);
    }

    result = ops->allocate_buffer(ih);
    if (result) abort();
    buffer = ops->get_buffer(ih);

#ifdef USE_SNDFILE
    if (opts->decode_file) {
        SF_INFO sf_info;
        memset(&sf_info, '\0', sizeof sf_info);
        sf_info.samplerate = (int) fd->st->samplerate;
        sf_info.channels = (int) fd->st->channels;
        sf_info.format = SF_FORMAT_WAV | SF_FORMAT_FLOAT;
        outfile = sf_open(opts->decode_file, SFM_WRITE, &sf_info);
        if (!outfile) {
            fprintf(stderr, "output file could not be opened\n");
            exit(EXIT_FAILURE);
        }
    }
#endif

    while ((nr_frames_read = ops->read_frames(ih))) {
        g_mutex_lock(progress_mutex);
        elapsed_frames += nr_frames_read;
        g_cond_broadcast(progress_cond);
        g_mutex_unlock(progress_mutex);
        fd->number_of_elapsed_frames += nr_frames_read;
        result = ebur128_add_frames_float(fd->st, buffer, nr_frames_read);
#ifdef USE_SNDFILE
        if (opts->decode_file) {
            if (sf_writef_float(outfile, buffer, (sf_count_t) nr_frames_read) != (sf_count_t) nr_frames_read)
                sf_perror(outfile);
        }
#endif
        if (result) abort();
    }

#ifdef USE_SNDFILE
    if (opts->decode_file) {
        sf_close(outfile);
    }
#endif

    if (fd->number_of_elapsed_frames != fd->number_of_frames) {
        if (verbose) {
            fprintf(stderr, "Warning: Could not read full file"
                            " or determine right length: "
                            "Expected: %lu Got: %lu",
                            fd->number_of_frames, fd->number_of_elapsed_frames);
        }
        g_mutex_lock(progress_mutex);
        total_frames = total_frames + fd->number_of_elapsed_frames - fd->number_of_frames;
        g_cond_broadcast(progress_cond);
        g_mutex_unlock(progress_mutex);
    }
    ebur128_loudness_global(fd->st, &fd->loudness);
    if (opts->lra) {
        result = ebur128_loudness_range(fd->st, &fd->lra);
        if (result) abort();
    }

    if ((fd->st->mode & EBUR128_MODE_SAMPLE_PEAK) == EBUR128_MODE_SAMPLE_PEAK) {
        for (i = 0; i < fd->st->channels; ++i) {
            double sp;
            ebur128_sample_peak(fd->st, i, &sp);
            if (sp > fd->peak) {
                fd->peak = sp;
            }
        }
    }
#ifdef USE_SPEEX_RESAMPLER
    if ((fd->st->mode & EBUR128_MODE_TRUE_PEAK) == EBUR128_MODE_TRUE_PEAK) {
        for (i = 0; i < fd->st->channels; ++i) {
            double tp;
            ebur128_true_peak(fd->st, i, &tp);
            if (tp > fd->true_peak) {
                fd->true_peak = tp;
            }
        }
    }
#endif
    fd->scanned = TRUE;

    if (ih) ops->free_buffer(ih);
  free:
    if (!result) ops->close_file(ih);
    if (ih) ops->handle_destroy(&ih);
}
예제 #24
0
int main( int argc, char *argv[])
{
  /* This is a buffer of double precision floating point values
  ** which will hold our data while we process it.
  */
  static double data [BUFFER_LEN] ;

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

  /* A pointer to an SF_INFO stutct is passed to sf_open and sf_open_write
  ** which fill this struct with information about the file.
  */ 
  SF_INFO      sfinfo ;
  int          readcount ;

  if( argc < 2 ){
    printf("Usage: loopdump <file.wav>\n");
    exit(1);
  }

  /* Here's where we open the input file. We pass sf_open the file name and
  ** a pointer to an SF_INFO struct.
  ** On successful open, sf_open returns a SNDFILE* pointer which is used
  ** for all subsequent operations on that file. 
  ** If an error occurs during sf_open, the function returns a NULL pointer.
  */
  char *infilename = argv[1];
  if (! (infile = sf_open(infilename, SFM_READ, &sfinfo)))
  {   /* Open failed so print an error message. */
      printf ("Not able to open input file %s.\n", infilename) ;
      /* Print the error message fron libsndfile. */
      sf_perror (NULL) ;
      return  1 ;
      } ;

  if (sfinfo.channels > MAX_CHANNELS)
  {   printf ("Not able to process more than %d channels\n", MAX_CHANNELS) ;
      return  1 ;
      } ;

  SF_INSTRUMENT instr;
  if( sf_command (infile, SFC_GET_INSTRUMENT, &instr, sizeof (instr)) == SF_FALSE ) exit(1);

  if( instr.loops[0].start == 0 ){
    printf("no loopdata found\n");
    exit(0);
  }

  printf("[x] file=%s\n", infilename );
  printf("[x] sampleframes=%llu\n",sfinfo.frames);

  int i;
  for( i = 0; i < 16; i++ ){
    if( instr.loops[i].start == 0 ) continue;
    printf("[x] loop[%c].start=%i\n",i,instr.loops[i].start);
    printf("[x] loop[%c].end=%i\n",i,instr.loops[i].end);
    printf("[x] loop[%c].count=%i\n",i,instr.loops[i].count);
  }


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

	return 0;
}
int main(int argc, char *argv[]) {
    long i = 0;
    long readcount = 0;
    PaStreamParameters inputParameters;
    PaStream *stream = NULL;
    long sizeonesec = (PLAY_FRAMES_PER_BUFFER * 2) * sizeof(float);

    /* Alloc size for one block */
    float *sampleBlock = (float *)malloc(sizeonesec);
    PaError retval = 0;
    struct sigaction sa;

    printf("Record to file: '%s'\n", argv[1]);

    /*
      We use two channels
      Samplerate is 44100
      Wave 16 bit output format
    */
    sfinfo.channels = 2;
    sfinfo.samplerate = 44100;
    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;

    /* Open file. Because this is just a example we asume
      What you are doing and give file first argument */
    if (! (outfile = sf_open(argv[1], SFM_WRITE, &sfinfo))) {
        printf ("Not able to open output file %s.\n", argv[1]) ;
        sf_perror (NULL) ;
        return  1 ;
    }

    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;

    if (sigaction(SIGINT, &sa, NULL) == -1) {
        printf("Can't set SIGINT handler!\n");
        sf_close(outfile);
        return -1;
    }

    if (sigaction(SIGHUP, &sa, NULL) == -1) {
        printf("Can't set SIGHUP handler!\n");
        sf_close(outfile);
        return -1;
    }

    /* -- initialize PortAudio -- */
    retval = Pa_Initialize();

    if(retval != paNoError) {
        goto exit;
    }

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default output device */

    if (inputParameters.device == paNoDevice) {
        fprintf(stderr, "Error: No default output device.\n");
        goto exit;
    }

    /* -- setup stream -- */
    inputParameters.channelCount = 2;       /* stereo output */
    inputParameters.sampleFormat = paFloat32;  /* 32 bit floating point output */
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowOutputLatency;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    retval = Pa_OpenStream(
                 &stream,
                 &inputParameters,
                 NULL, /* no output */
                 44100,
                 PLAY_FRAMES_PER_BUFFER,
                 paClipOff,      /* we won't output out of range samples so don't bother clipping them */
                 NULL,
                 outfile);

    if(retval != paNoError) {
        printf("Can't open device\n");
        goto exit;
    }

    /* -- start stream -- */
    retval = Pa_StartStream(stream);

    if(retval != paNoError) {
        goto exit;
    }

    printf("Wire on. Will run one minute.\n");
    fflush(stdout);

    /* -- Here's the loop where we pass data from input to output -- */
    for(i = 0; i < ((10 * sizeonesec) / (44100 * 2)); ++i) {
        retval = Pa_ReadStream(stream, (void *)sampleBlock, sizeonesec / 8);

        if(retval != paNoError) {
            printf("** Can't read from input!\n");
            goto exit;
        }

        readcount = sf_write_float(outfile, sampleBlock, sizeonesec / 4);

        if(readcount <= 0) {
            printf("** Can't write to file!\n");
            goto exit;
        }


    }

exit:
    sf_close(outfile);
    retval = Pa_StopStream(stream);
    retval = Pa_CloseStream(stream);
    Pa_Terminate();
    return 0;

}
예제 #26
0
int     
main (void)
{   /* This is a buffer of double precision floating point values
    ** which will hold our data while we process it.
    */
    static double data [BUFFER_LEN] ;

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

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

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

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

    /* While there are.frames in the input file, read them, process
    ** them and write them to the output file.
    */
    while ((readcount = sf_read_double (infile, data, BUFFER_LEN)))
    {   process_data (data, readcount, sfinfo.channels) ;
        sf_write_double (outfile, data, readcount) ;
        } ;

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

    return 0 ;
} /* main */
예제 #27
0
int main(int argc, char **argv)
{
	/* A SNDFILE is very much like a FILE in the Standard C library. The
	** sf_open_read and sf_open_write functions return an SNDFILE* pointer
	** when they sucessfully open the specified file.
	*/
	SNDFILE      *infile=0, *outfile=0;

	/* A pointer to an SF_INFO stutct is passed to sf_open_read and sf_open_write
	** which fill this struct with information about the file.
	*/
	char *fd1, *fd2, *strt;
	bool encode = true;
	SF_INFO      sfinfo;
	int seed = 0;
	long long    readcount
		,		 readcount2;
	/*
	srand(123);
	codeBuffSize = 10;
	xresidualPerc = 10;
	xdisplacement = 0;
	dataBuffLen = 0;
	direction='d';
	inFileName	= "b:\\snds\\input.wav";
	outFileName	= "b:\\snds\\output.wav";
*/
	*buff = '|';
	strcat(buff + 1, argv[1]);
	strcat(buff,",=");
	strt = buff;
/*
              123456789012345
 */
	 char *parms="|mode         |codefile     |srcfilein    |srcfileout   |seed         |residualperc |blocklen     |displacement |";
	 size_t token = 0;
	 char *fd3;
	 while (*strt != 0)
	 {
		 *strt = tolower(*strt);
		 strt++;
	 }

	 strt = buff;
	while ((fd1 = strchr(strt, '=')) != 0)
	{
		if (strlen(fd1) < 2) break;
		*fd1 = 0, fd1++;
		fd2 = strchr(fd1, ',');
		*fd2 = 0, fd2++;
		if ((fd3=strstr(parms, strt)) != 0)
		{
			token = (fd3-parms)/14;
			switch (token)
			{
				case 0:	// mode
					if (*(fd1) == 'e') direction = 'e';
					else direction = 'd';
					break;
				case 1:	// codefile
					strcpy(codeFileName,fd1);
					break;
				case 2:	// srcfilein
					inFileName = (fd1);
					break;
				case 3:	// srcfileout
					outFileName = (fd1);
					break;
				case 4:	// seed
				{
							seed = atoi(fd1);
							srand(seed);
							break;
				}
				case 5: // residualperc
					xresidualPerc = atoi(fd1);
					break;
				case 6: //blocklen
					codeBuffSize = atoi(fd1);
					break;
				case 7: // displacement
					xdisplacement = atoi(fd1);
					break;
				default:
					break;
			}
			strt=fd2;
		}
	}

	myOctopus = new octopus(seed, codeBuffSize, xresidualPerc, xdisplacement, direction);
	encode = myOctopus->getMode();
	if (!encode) strcat(codeFileName, ".out");

	myOctopus->setGetBit(getBit);
	myOctopus->setSetBit(setBit);
	dataBuffLen = myOctopus->getMixBuffLength();
	codeBuffer = (unsigned char *)calloc(codeBuffSize+2, 1);

	data = (short *)calloc(dataBuffLen, sizeof(short));
	/* Here's where we open the input file. We pass sf_open_read the file name and
	** a pointer to an SF_INFO struct.
	** On successful open, sf_open_read returns a SNDFILE* pointer which is used
	** for all subsequent operations on that file.
	** If an error occurs during sf_open_read, the function returns a NULL pointer.
	*/
	char *srcFileName, *tgtFileName;
	char *codeMode;

	if (encode)
	{
		codeMode = "r";
		srcFileName = inFileName;
		tgtFileName = outFileName;

	}
	else
	{
		codeMode = "w";
		srcFileName = outFileName;
		tgtFileName = codeFileName;
	}

	if (!(codeFile = fopen(codeFileName, codeMode)))
	{   /* Open failed so print an error message. */
		printf("Not able to open code file %s.\n", codeFileName);
		/* Print the error message fron libsndfile. */
		return  1;
	};

//	sfinfo.format = ((sfinfo.format & 0xffffff00) | 1);
	/* Open the output file. */

	if (!(infile = sf_open(srcFileName, SFM_READ, &sfinfo)))
	{
		printf("Not able to open source file %s.\n", outFileName);
		sf_perror(NULL);
		return  1;
	};
	if (sfinfo.channels > MAX_CHANNELS)
	{
		printf("Not able to process more than %d channels\n", MAX_CHANNELS);
		return  1;
	};
	if (encode)
	{
		if (!(outfile = sf_open(tgtFileName, SFM_WRITE, &sfinfo)))
		{
			printf("Not able to open target file %s.\n", outFileName);
			sf_perror(NULL);
			return  1;
		}
	}


	/* While there are samples in the input file, read them, process
	** them and write them to the output file.
	*/
	bool eofcode = false;
	bool eofmix = false;
		while ((readcount = sf_read_short(infile, data, dataBuffLen)))
		{
//			printf("\tread sound: %d", readcount);
				if (!eofmix)
				{
					if (encode)
					{
						if (!eofcode)
						{
							readcount2 = fread(codeBuffer, 1, codeBuffSize, codeFile);
							if ((eofcode = (readcount2 < codeBuffSize)))
							{
								printf("\teof CodeData: %d", readcount2);
								readcount2 = codeBuffSize;
							}
							process_data(data,((int)readcount), sfinfo.channels);
							memset(codeBuffer, 0, codeBuffSize);
						}
					}
					else
					{
						process_data(data, ((int)readcount), sfinfo.channels);
					}
					eofmix = (readcount < dataBuffLen);
				}
				if (encode)
				{
					sf_write_short(outfile, data, readcount);
					printf("\twrote mix: %d", readcount);
				}
				else
				{
					unsigned int l = 0;
					fprintf(codeFile,"%s", codeBuffer);
					printf("\twrote code: %d\n", (l=strlen((char *)codeBuffer)));
					if (l < codeBuffSize)
						break;
				}
			memset(data,0, (size_t)dataBuffLen);
			if (eofmix) break;
		}
	printf("done");
	free(buff);

	/* Close input and output files. */
	if (infile != 0)		sf_close(infile);
	if (outfile != 0)	sf_close(outfile);
	if (codeFile != 0)	fclose(codeFile);

	return 0;
} /* main */
예제 #28
0
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;    
}
예제 #29
0
static void	
test_float_peak (char *str, char *filename, int typemajor)
{	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	int			k, frames, count ;

	printf ("    test_float_peak : %s ... ", str) ;
	
	sfinfo.samplerate  = 44100 ;
	sfinfo.format 	   = (typemajor | SF_FORMAT_FLOAT) ;
	sfinfo.channels    = 4 ;
	sfinfo.frames     = 0 ;

	frames = BUFFER_LEN / sfinfo.channels ;
	
	/* Create some random data with a peak value of 0.66. */
	for (k = 0 ; k < BUFFER_LEN ; k++)
		data [k] = (rand () % 2000) / 3000.0 ;
		
	/* Insert some larger peaks a know locations. */
	data [4 * (frames / 8) + 0] = (frames / 8) * 0.01 ;	/* First channel */
	data [4 * (frames / 6) + 1] = (frames / 6) * 0.01 ;	/* Second channel */
	data [4 * (frames / 4) + 2] = (frames / 4) * 0.01 ;	/* Third channel */
	data [4 * (frames / 2) + 3] = (frames / 2) * 0.01 ;	/* Fourth channel */
		
	if (! (file = sf_open (filename, SFM_WRITE, &sfinfo)))
	{	printf ("Line %d: sf_open_write failed with error : ", __LINE__) ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;

	/*	Write the data in four passed. The data is designed so that peaks will 
	**	be written in the different calls to sf_write_double ().
	*/
	for (count = 0 ; count < 4 ; count ++)
	{	if ((k = sf_write_double (file, data + count * BUFFER_LEN / 4, BUFFER_LEN / 4)) != BUFFER_LEN / 4)
		{	printf ("Line %d: sf_write_double # %d failed with short write (%d ->%d)\n", __LINE__, count, BUFFER_LEN / 4, k) ;
			exit (1) ;
			} ;
		} ;
	
	sf_close (file) ;
	
	if (! (file = sf_open (filename, SFM_READ, &sfinfo)))
	{	printf ("Line %d: sf_open_read failed with error : ", __LINE__) ;
		sf_perror (NULL) ;
		exit (1) ;
		} ;
	
	if (sfinfo.format != (typemajor | SF_FORMAT_FLOAT))
	{	printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, (typemajor | SF_FORMAT_FLOAT), sfinfo.format) ;
		exit (1) ;
		} ;
	
	if (sfinfo.frames != frames)
	{	printf ("Line %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, frames, (long) sfinfo.frames) ;
		exit (1) ;
		} ;
	
	if (sfinfo.channels != 4)
	{	printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ;
		exit (1) ;
		} ;

	/* Get the log buffer data. */
	log_buffer [0] = 0 ;
	sf_command	(file, SFC_GET_LOG_INFO, log_buffer, LOG_BUFFER_SIZE) ;
	
	if (strlen (log_buffer) == 0)
	{	printf ("Line %d: Empty log buffer,\n", __LINE__) ;
		exit (1) ;
		} ;

	check_logged_peaks (log_buffer) ;

	sf_close (file) ;

	unlink (filename) ;
	printf ("ok\n") ;
} /* test_float_peak */
int main(int argc, char *argv[]) {
    int retval = 0;
    struct sigaction l_SSa;
    SDL_Event       l_SEvent;

    /* Open file. Because this is just a example we asume
      What you are doing and give file first argument */
    if (! (m_SInfile = sf_open(argv[1], SFM_READ, &m_SSinfo))) {
        fprintf (stderr, "main: Not able to open input file %s.\n", argv[1]) ;
        sf_perror (NULL) ;
        return  1 ;
    }

    printf("Opened file: (%s)\n", argv[1]);

    l_SSa.sa_flags = SA_SIGINFO;
    sigemptyset(&l_SSa.sa_mask);
    l_SSa.sa_sigaction = handler;

    if (sigaction(SIGINT, &l_SSa, NULL) == -1) {
        fprintf(stderr, "main: Can't set SIGINT handler!\n");
        sf_close(m_SInfile);
        return -1;
    }

    if (sigaction(SIGHUP, &l_SSa, NULL) == -1) {
        fprintf(stderr, "main: Can't set SIGHUP handler!\n");
        sf_close(m_SInfile);
        goto exit;
    }

    /* SDL initialize */
    if(SDL_Init(SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
        fprintf(stderr, "main: Could not initialize SDL - %s\n", SDL_GetError());
        goto exit;
    }

    printf("We have samplerate: %5d and channels %2d\n", m_SSinfo.samplerate, m_SSinfo.channels);

    if( m_SSinfo.format & SF_FORMAT_PCM_S8 ) {
        printf("Subformat: 8-bit!\n");

    } else if( m_SSinfo.format & SF_FORMAT_PCM_16 ) {
        printf("Subformat: 16-bit!\n");

    } else if( m_SSinfo.format & SF_FORMAT_PCM_24 ) {
        printf("Subformat: 24-bit!\n");

    } else if( m_SSinfo.format & SF_FORMAT_PCM_32 ) {
        printf("Subformat: 32-bit!\n");

    } else if( m_SSinfo.format & SF_FORMAT_FLOAT ) {
        printf("Subformat: FLOAT!\n");

    } else if( m_SSinfo.format & SF_FORMAT_DOUBLE ) {
        printf("Subformat: DOUBLE!\n");
    }

    SDL_zero(m_SWantedSpec);
    SDL_zero(m_SSDLspec);

    m_SWantedSpec.freq = m_SSinfo.samplerate;
#if SDL_MAJOR_VERSION == 2
    m_SWantedSpec.format = AUDIO_F32LSB;
#else
    m_SWantedSpec.format = AUDIO_S16LSB;
#endif
    m_SWantedSpec.channels =  m_SSinfo.channels;
    m_SWantedSpec.silence = 0;
    m_SWantedSpec.samples = 1024;
    m_SWantedSpec.callback = sdlLibsndfileCb;
    m_SWantedSpec.userdata = m_SInfile;

    if(SDL_OpenAudio(&m_SWantedSpec, &m_SSDLspec) < 0) {
        fprintf(stderr, "main: SDL_OpenAudio: %s\n", SDL_GetError());
        goto exit;
    }

    SDL_PauseAudio(0);
    atexit(SDL_Quit);

    /* Loop until we exit */
    while(!l_iLoop) {
        SDL_PollEvent(&l_SEvent);
    }

exit:
    /* clean up and disconnect */
    printf("\nExit and clean\n");
    sf_close(m_SInfile);
    m_SInfile = NULL;

    return retval;
}