示例#1
0
int
main (int argc, char **argv)
{	STATE state ;
	SF_INFO sfinfo ;
	char pathname [512], ext [32], *cptr ;
	int ch, double_split ;

	if (argc != 2)
	{	if (argc != 1)
			puts ("\nError : need a single input file.\n") ;
		usage_exit () ;
		} ;

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

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

	if (sfinfo.channels < 2)
	{	printf ("\nError : Input file '%s' only has one channel.\n", argv [1]) ;
		exit (1) ;
		} ;

	state.channels = sfinfo.channels ;
	sfinfo.channels = 1 ;

	snprintf (pathname, sizeof (pathname), "%s", argv [1]) ;
	if ((cptr = strrchr (pathname, '.')) == NULL)
		ext [0] = 0 ;
	else
	{	snprintf (ext, sizeof (ext), "%s", cptr) ;
		cptr [0] = 0 ;
		} ;

	printf ("Input file : %s\n", pathname) ;
	puts ("Output files :") ;

	for (ch = 0 ; ch < state.channels ; ch++)
	{	char filename [520] ;

		snprintf (filename, sizeof (filename), "%s_%02d%s", pathname, ch, ext) ;

		if ((state.outfile [ch] = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
		{	printf ("Not able to open output file '%s'\n%s\n", filename, sf_strerror (NULL)) ;
			exit (1) ;
			} ;

		printf ("    %s\n", filename) ;
		} ;

	switch (sfinfo.format & SF_FORMAT_SUBMASK)
	{	case SF_FORMAT_FLOAT :
		case SF_FORMAT_DOUBLE :
		case SF_FORMAT_VORBIS :
			double_split = 1 ;
			break ;

		default :
			double_split = 0 ;
			break ;
		} ;

	if (double_split)
		deinterleave_double (&state) ;
	else
		deinterleave_int (&state) ;

	sf_close (state.infile) ;
	for (ch = 0 ; ch < MAX_CHANNELS ; ch++)
		if (state.outfile [ch] != NULL)
			sf_close (state.outfile [ch]) ;

	return 0 ;
} /* main */
示例#2
0
void World_Cleanup(World *world, bool unload_plugins)
{
	if (!world) return;

	if (scsynth::asioThreadStarted()){
		scsynth::stopAsioThread();
	}

	if(unload_plugins)
		deinitialize_library();

	HiddenWorld *hw = world->hw;

	if (hw && world->mRealTime) hw->mAudioDriver->Stop();

	world->mRunning = false;

	if (world->mTopGroup) Group_DeleteAll(world->mTopGroup);

	reinterpret_cast<SC_Lock*>(world->mDriverLock)->lock();
	if (hw) {
		sc_free(hw->mWireBufSpace);
		delete hw->mAudioDriver;
		hw->mAudioDriver = 0;
	}
	delete reinterpret_cast<SC_Lock*>(world->mNRTLock);
	reinterpret_cast<SC_Lock*>(world->mDriverLock)->unlock();
	delete reinterpret_cast<SC_Lock*>(world->mDriverLock);
	World_Free(world, world->mTopGroup);

	for (uint32 i=0; i<world->mNumSndBufs; ++i) {
		SndBuf *nrtbuf = world->mSndBufsNonRealTimeMirror + i;
		SndBuf * rtbuf = world->mSndBufs + i;

		if (nrtbuf->data) free_alig(nrtbuf->data);
		if (rtbuf->data && rtbuf->data != nrtbuf->data) free_alig(rtbuf->data);

#ifndef NO_LIBSNDFILE
		if (nrtbuf->sndfile) sf_close(nrtbuf->sndfile);
		if (rtbuf->sndfile && rtbuf->sndfile != nrtbuf->sndfile) sf_close(rtbuf->sndfile);
#endif
	}

	free_alig(world->mSndBufsNonRealTimeMirror);
	free_alig(world->mSndBufs);

	free_alig(world->mControlBusTouched);
	free_alig(world->mAudioBusTouched);
	if (hw->mShmem) {
		delete hw->mShmem;
	} else
		free_alig(world->mControlBus);
	free_alig(world->mAudioBus);
	delete [] world->mRGen;
	if (hw) {

#ifndef NO_LIBSNDFILE
		if (hw->mNRTInputFile) sf_close(hw->mNRTInputFile);
		if (hw->mNRTOutputFile) sf_close(hw->mNRTOutputFile);
		if (hw->mNRTCmdFile) fclose(hw->mNRTCmdFile);
#endif
		delete hw->mUsers;
		delete hw->mAvailableClientIDs;
		delete hw->mClientIDdict;
		delete hw->mNodeLib;
		delete hw->mGraphDefLib;
		delete hw->mQuitProgram;
		delete hw->mAllocPool;
		free_alig(hw);
	}
	free_alig(world);
}
示例#3
0
static void
vorbis_test (void)
{	static float float_data [DFT_DATA_LENGTH] ;
	const char * filename = "vorbis_test.oga" ;
	SNDFILE * file ;
	SF_INFO sfinfo ;
	float max_abs = 0.0 ;
	unsigned k ;

	print_test_name ("vorbis_test", filename) ;

	/* Generate float data. */
	gen_windowed_sine_float (float_data, ARRAY_LEN (float_data), 1.0) ;

	/* Set up output file type. */
	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS ;
	sfinfo.channels = 1 ;
	sfinfo.samplerate = SAMPLE_RATE ;

	/* Write the output file. */

	/*	The Vorbis encoder has a bug on PowerPC and X86-64 with sample rates
	**	<= 22050. Increasing the sample rate to 32000 avoids triggering it.
	**	See https://trac.xiph.org/ticket/1229
	*/
	if ((file = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
	{	const char * errstr ;

		errstr = sf_strerror (NULL) ;
		if (strstr (errstr, "Sample rate chosen is known to trigger a Vorbis") == NULL)
		{	printf ("Line %d: sf_open (SFM_WRITE) failed : %s\n", __LINE__, errstr) ;
			dump_log_buffer (NULL) ;
			exit (1) ;
			} ;

		printf ("\n                                  Sample rate -> 32kHz    ") ;
		sfinfo.samplerate = 32000 ;

		file = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, SF_TRUE, __LINE__) ;
		} ;

	test_write_float_or_die (file, 0, float_data, ARRAY_LEN (float_data), __LINE__) ;
	sf_close (file) ;

	memset (float_data, 0, sizeof (float_data)) ;

	/* Read the file back in again. */
	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	file = test_open_file_or_die (filename, SFM_READ, &sfinfo, SF_FALSE, __LINE__) ;
	test_read_float_or_die (file, 0, float_data, ARRAY_LEN (float_data), __LINE__) ;
	sf_close (file) ;

	for (k = 0 ; k < ARRAY_LEN (float_data) ; k ++)
		max_abs = max_float (max_abs, fabs (float_data [k])) ;

	if (max_abs > 1.021)
	{	printf ("\n\n    Error : max_abs %f should be < 1.021.\n\n", max_abs) ;
		exit (1) ;
		} ;

	puts ("ok") ;
	unlink (filename) ;
} /* vorbis_test */
示例#4
0
int main(int argc, char **argv)
{
    SNDFILE *srcfile, *dstfile;
    SF_INFO srcinfo, dstinfo;
    SF_FORMAT_INFO formatinfo;
    char *extension;
    void **handle;
    int channels;
    int srclen, dstlen;
    float *src, *srci;
    float *dst, *dsti;
    double ratio = 0.0;
    double srcrate;
    double dstrate = 0.0;
    struct timeval tv0, tv1;
    double deltat;
    int numformats;
    int pos, bufferpos, outcount;
    int i, c;

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

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

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

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

    channels = srcinfo.channels;

    /* figure out format of destination file */

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

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

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

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

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

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

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

    gettimeofday(&tv0, NULL);

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

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

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

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

            for(i=0; i<out; i++)
            {
                if(dst[i] <= -1)
                    dsti[i*channels+c] = -1;
                else if(dst[i] >= 1)
                    dsti[i*channels+c] = 1;
                else
                    dsti[i*channels+c] = dst[i];
            }
        }

        sf_writef_float(dstfile, dsti, out);

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

    sf_close(srcfile);
    sf_close(dstfile);

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

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

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

    exit(0);
}
示例#5
0
///////////////////////////////////////////////////////////////////////////////////
// stopRecording ------------------------------------------------------------------------
///////////////////////////////////////////////////////////////////////////////////
void Echo::stopRecording(){
	sf_close(outfile);
	soundPlayer.loadSound(filename);
	isRecorded = true;
}
示例#6
0
/* phase vocoder by complex arithmetics with fixed hops.
 */
void pv_complex_curses (const char * file,
                        long len, long hop_syn)
{
   extern int flag_nofft;
   int flag_window = 3;
   struct pv_complex * pv;
   SNDFILE * sf = NULL;
   SF_INFO sfinfo;
   double pv_rate  = 1.0;
   double pv_pitch = 0.0;
   long frame0 = 0;
   long frame1;
   int flag_play = 1;
   long play_cur = 0;
   long len_1sec;
   long len_10sec;
   ao_device * ao;       /*  = NULL; */
   long status = 1; /* TRUE */
   int ch;

   /* ncurses initializing */

   initscr();             /* Start curses mode */
   raw();                 /* Line buffering disabled */
   keypad(stdscr, TRUE);  /* We get F1, F2 etc.. */
   noecho();              /* Don't echo() while we do getch */
   nodelay(stdscr, TRUE); /* Don't wait the key press */

   pv = pv_complex_init (len, hop_syn, flag_window);
   CHECK_MALLOC (pv, "pv_complex_curses");

   /* open input file */

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

   pv_complex_set_input (pv, sf, &sfinfo);

   ao = ao_init_16_stereo (sfinfo.samplerate, 0);
   pv_complex_set_output_ao (pv, ao);


   /* initial values */

   pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);

   frame1 = (long) pv->sfinfo->frames - 1;
   pv->flag_lock = 0; /* no phase-lock */

   len_1sec  = (long) (pv->sfinfo->samplerate /* Hz */);
   len_10sec = (long) (10 * pv->sfinfo->samplerate /* Hz */);

   mvprintw (Y_comment, 1, "Welcome WaoN-pv in curses mode.         ");
   curses_print_pv (file, pv, flag_play, frame0, frame1,
                    pv_pitch, pv_rate);

   /* main loop */

   do
   {
      if (flag_play != 0)
      {
         status = play_100msec_curses (pv, &play_cur, frame0, frame1);
      }

      /* scan keyboard */

      ch = getch();
      switch (ch)
      {
      case ERR: /* no key event */
         break;

      case ' ': /* SPACE */
         flag_play++;
         flag_play = flag_play % 2;
         if (flag_play == 0) mvprintw(Y_status, 1, "status     : stop");
         else                mvprintw(Y_status, 1, "status     : play");
         break;

      case '>':
      case '.':
         frame1 = play_cur;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case '<':
      case ',':
         frame0 = play_cur;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case ']':
         frame1 += len_10sec;
         if (frame1 >= pv->sfinfo->frames - 1) frame1 = pv->sfinfo->frames - 1;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case '}':
         frame1 += len_1sec;
         if (frame1 >= pv->sfinfo->frames - 1) frame1 = pv->sfinfo->frames - 1;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case '[':
         frame0 -= len_10sec;
         if (frame0 < 0) frame0 = 0;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case '{':
         frame0 -= len_1sec;
         if (frame0 < 0) frame0 = 0;
         mvprintw (Y_loop,   1, "loop       : %010ld - %010ld",
                   frame0, frame1);
         break;

      case 'L':
      case 'l':
         pv->flag_lock++;
         pv->flag_lock = pv->flag_lock % 2;

         if (pv->flag_lock == 0) mvprintw(Y_lock, 1, "phase-lock : off");
         else                    mvprintw(Y_lock, 1, "phase-lock : on ");
         break;

      case 'W':
      case 'w':
         pv->flag_window++;
         pv->flag_window = pv->flag_window % 7; /* 0 to 6 */

         /* reset scale factor */
         pv->window_scale
            = get_scale_factor_for_window (pv->len, pv->hop_syn,
                                           pv->flag_window);
         curses_print_window (pv->flag_window);
         break;

      case 'H':
         pv->hop_syn *= 2;
         if (pv->hop_syn > len) pv->hop_syn = len;
         /* hop_res, hop_ana depend on hop_syn */
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case 'h':
         pv->hop_syn /= 2;
         if (pv->hop_syn < 1) pv->hop_syn = 1;
         /* hop_res, hop_ana depend on hop_syn */
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case KEY_UP:
         pv_pitch += 1.0;
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         curses_print_pitch (pv_pitch);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case KEY_DOWN:
         pv_pitch -= 1.0;
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         curses_print_pitch (pv_pitch);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case KEY_LEFT:
         pv_rate -= 0.1;
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         mvprintw (Y_rate,   1, "rate       : %-5.1f", pv_rate);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case KEY_RIGHT:
         pv_rate += 0.1;
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         mvprintw (Y_rate,   1, "rate       : %-5.1f", pv_rate);
         mvprintw (Y_hop_syn, 1, "hop(syn)   : %06ld", pv->hop_syn);
         mvprintw (Y_hop_ana, 1, "hop(ana)   : %06ld", pv->hop_ana);
         mvprintw (Y_hop_res, 1, "hop(res)   : %06ld", pv->hop_res);
         break;

      case KEY_HOME:
      case 'R':
      case 'r':
         frame0 = 0;
         frame1 = (long)pv->sfinfo->frames - 1;
         pv_rate = 1.0;
         pv_pitch = 0.0;
         pv->hop_syn = hop_syn; /* value in the argument */
         pv_complex_change_rate_pitch (pv, pv_rate, pv_pitch);
         curses_print_pv (file, pv, flag_play, frame0, frame1,
                          pv_pitch, pv_rate);
         mvprintw (Y_comment, 1, "reset everything                        ");
         break;

      case 'Q':
      case 'q':
         status = 0;
         mvprintw (Y_comment, 1, "good-bye!                               ");
         break;

      case 'N':
      case 'n':
         flag_nofft ++;
         if (flag_nofft == 2) flag_nofft = 0;

         if (flag_nofft == 0)    mvprintw(Y_lock, 21, "      ");
         else                    mvprintw(Y_lock, 21, "no-FFT");

         break;

         /*
         defaut :
         break;
         */
      }
      mvprintw (Y_frames, 1, "current    : %010ld", play_cur);
      refresh();
   }
   while (status == 1)
      ;

   pv_complex_free (pv);
   sf_close (sf) ;
   endwin(); /* End ncurses mode */
}
示例#7
0
////////////////////////////////////////////////////////////
/// Destructor
////////////////////////////////////////////////////////////
SoundFileDefault::~SoundFileDefault()
{
    if (myFile)
        sf_close(myFile);
}
示例#8
0
static int
compare (void)
{	double buf1 [BUFLEN], buf2 [BUFLEN] ;
	SF_INFO sfinfo1, sfinfo2 ;
	SNDFILE * sf1 = NULL, * sf2 = NULL ;
	sf_count_t items, i, nread1, nread2, offset = 0 ;
	int retval = 0 ;

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

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

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

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

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

	while ((nread1 = sf_readf_double (sf1, buf1, items)) > 0)
	{	nread2 = sf_readf_double (sf2, buf2, nread1) ;
		if (nread2 != nread1)
		{	retval = comparison_error ("PCM data lengths", -1) ;
			goto out ;
		} ;
		for (i = 0 ; i < nread1 * sfinfo1.channels ; i++)
		{	if (buf1 [i] != buf2 [i])
			{	retval = comparison_error ("PCM data", offset + i / sfinfo1.channels) ;
				goto out ;
			} ;
		} ;
		offset += nread1 ;
	} ;

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

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

	return retval ;
} /* compare */
示例#9
0
bool wfg_generateImage(char* audioFileName, char* pictureFileName, WFGO* options)
{	
	int width = options->width;
	int height = options->height;

	// Initial audio part
	
	SF_INFO sfinfo;
	memset(&sfinfo, 0, sizeof(sfinfo));
	
	SNDFILE* sfile =  sf_open(audioFileName, SFM_READ, &sfinfo);
	
	if(sfile == NULL)
	{
		lastErrorMessage = "Could not open input file!";
		return false;
	}
	
	long framesPerLine = (long) sfinfo.frames / width;
	long samplesPerLine = framesPerLine * sfinfo.channels;
	
	int seconds = sfinfo.frames / sfinfo.samplerate;
	
	
	// although one could think, that these values are flexible, the loops
	// below only work in these configurations (1/all or all/1)
	
	int channelsPerDrawing = 1;
	int drawnChannels = sfinfo.channels;
	
	if(options->mixChannels)
	{
		channelsPerDrawing = sfinfo.channels;
		drawnChannels = 1;
	}
		
	float * buffer = malloc(sizeof(float) * samplesPerLine);
	
	// malloc fail
	if(buffer == NULL)
	{
		lastErrorMessage = "Could not allocate memory!";
		sf_close(sfile);
		return false;
	}
	
	// Allocate Image
	gdImagePtr im = gdImageCreate(width,height);
	
	if(im == NULL)
	{
		lastErrorMessage = "Could not allocate image!";
		free(buffer);
		sf_close(sfile);
		return false;
	}
	
	// calculate how large one drawing should be
	
	int drawHeight = height;
	
	// leave space for the timeline
	if(options->drawTimeline)
		drawHeight -= 13;
	
	// subtract spacing
	drawHeight = drawHeight - ((drawnChannels - 1) * options->channelSpacing);
	
	// divide by drawnChannels
	drawHeight = drawHeight / drawnChannels;
	
	// background color
	int bgColor = gdImageColorAllocate(im,WFG_UNPACK_RGB(options->bgColor));
	
	if(options->transparentBg) {
		gdImageColorTransparent(im,bgColor);
	}
	
	int rmsColor =  gdImageColorAllocate(im, WFG_UNPACK_RGB(options->rmsColor));
	int peakColor = gdImageColorAllocate(im, WFG_UNPACK_RGB(options->peakColor));
	
	// too many nested loops ...
	for(int i = 0; i < width; i++)
	{
		if(sf_read_float(sfile, buffer, samplesPerLine) != samplesPerLine)
		{
			lastErrorMessage = "Could not read samples from audio file!";
			sf_close(sfile);
			free(buffer);
			gdImageDestroy(im);
			return false;			
		}
		
		int drawOffset = 0;

		for(int d = 0; d < drawnChannels; d++)
		{
			double val = 0.0;
			
			float peakP = 0.0;
			float peakM = 0.0;
			
			for(long e = 0; e < framesPerLine; e++)
			{
				for(int f = 0; f < channelsPerDrawing; f++)
				{
					float smpl = buffer[e * drawnChannels + d];
					val = val + (smpl*smpl);
					
					if(peakM > smpl)
						peakM = smpl;
					
					if(peakP < smpl)
						peakP = smpl;
				}
			}
			
			val = val / (float) (framesPerLine * channelsPerDrawing);
			val = sqrt(val);
			
			double ddrawHeight = drawHeight;
			
			int peakPP = drawHeight/2 -  round(peakP * (ddrawHeight/2.0));
			int peakMP = drawHeight/2 +  round(peakM * -1.0 * (ddrawHeight/2.0));
					
			// avoid rounding errors when peak is very small
			// if(peakP > 0.001 || peakM < -0.001) 
			gdImageLine(im, i,peakPP + drawOffset,i,peakMP + drawOffset, peakColor);
			
			int rmsSize;
			rmsSize = val * (double) (drawHeight/2);
			gdImageLine(im, i,drawHeight/2 - rmsSize + drawOffset,i,drawHeight/2 + rmsSize + drawOffset, rmsColor);
			
			drawOffset += drawHeight + options->channelSpacing;
		}
	}

	
	sf_close(sfile);
	free(buffer);
	
	if(options->drawTimeline)
		drawTimeline(im, options, seconds);
	
	// write out file
	FILE* file = fopen(pictureFileName,"wb");
	if(file == NULL)
	{
		lastErrorMessage = "Could not open output file!";
		gdImageDestroy(im);
	}
	
	gdImagePng(im,file);
	
	fclose(file);
	gdImageDestroy(im);
	
	return true;
}
示例#10
0
RTC::ReturnCode_t WavPlayer::onDeactivated(RTC::UniqueId ec_id)
{
	sf_close( sfr );
	return RTC::RTC_OK;
}
示例#11
0
文件: pacat.c 项目: Thread974/pa
int main(int argc, char *argv[]) {
    pa_mainloop* m = NULL;
    int ret = 1, c;
    char *bn, *server = NULL;
    pa_time_event *time_event = NULL;
    const char *filename = NULL;
    /* type for pa_read/_write. passed as userdata to the callbacks */
    unsigned long type = 0;

    static const struct option long_options[] = {
        {"record",       0, NULL, 'r'},
        {"playback",     0, NULL, 'p'},
        {"device",       1, NULL, 'd'},
        {"server",       1, NULL, 's'},
        {"client-name",  1, NULL, 'n'},
        {"stream-name",  1, NULL, ARG_STREAM_NAME},
        {"version",      0, NULL, ARG_VERSION},
        {"help",         0, NULL, 'h'},
        {"verbose",      0, NULL, 'v'},
        {"volume",       1, NULL, ARG_VOLUME},
        {"rate",         1, NULL, ARG_SAMPLERATE},
        {"format",       1, NULL, ARG_SAMPLEFORMAT},
        {"channels",     1, NULL, ARG_CHANNELS},
        {"channel-map",  1, NULL, ARG_CHANNELMAP},
        {"fix-format",   0, NULL, ARG_FIX_FORMAT},
        {"fix-rate",     0, NULL, ARG_FIX_RATE},
        {"fix-channels", 0, NULL, ARG_FIX_CHANNELS},
        {"no-remap",     0, NULL, ARG_NO_REMAP},
        {"no-remix",     0, NULL, ARG_NO_REMIX},
        {"latency",      1, NULL, ARG_LATENCY},
        {"process-time", 1, NULL, ARG_PROCESS_TIME},
        {"property",     1, NULL, ARG_PROPERTY},
        {"raw",          0, NULL, ARG_RAW},
        {"passthrough",  0, NULL, ARG_PASSTHROUGH},
        {"file-format",  2, NULL, ARG_FILE_FORMAT},
        {"list-file-formats", 0, NULL, ARG_LIST_FILE_FORMATS},
        {"latency-msec", 1, NULL, ARG_LATENCY_MSEC},
        {"process-time-msec", 1, NULL, ARG_PROCESS_TIME_MSEC},
        {NULL,           0, NULL, 0}
    };

    setlocale(LC_ALL, "");
#ifdef ENABLE_NLS
    bindtextdomain(GETTEXT_PACKAGE, PULSE_LOCALEDIR);
#endif

    bn = pa_path_get_filename(argv[0]);

    if (strstr(bn, "play")) {
        mode = PLAYBACK;
        raw = FALSE;
    } else if (strstr(bn, "record")) {
        mode = RECORD;
        raw = FALSE;
    } else if (strstr(bn, "cat")) {
        mode = PLAYBACK;
        raw = TRUE;
    } if (strstr(bn, "rec") || strstr(bn, "mon")) {
        mode = RECORD;
        raw = TRUE;
    }

    proplist = pa_proplist_new();

    while ((c = getopt_long(argc, argv, "rpd:s:n:hv", long_options, NULL)) != -1) {

        switch (c) {
            case 'h' :
                help(bn);
                ret = 0;
                goto quit;

            case ARG_VERSION:
                printf(_("pacat %s\n"
                         "Compiled with libpulse %s\n"
                         "Linked with libpulse %s\n"),
                       PACKAGE_VERSION,
                       pa_get_headers_version(),
                       pa_get_library_version());
                ret = 0;
                goto quit;

            case 'r':
                mode = RECORD;
                break;

            case 'p':
                mode = PLAYBACK;
                break;

            case 'd':
                pa_xfree(device);
                device = pa_xstrdup(optarg);
                break;

            case 's':
                pa_xfree(server);
                server = pa_xstrdup(optarg);
                break;

            case 'n': {
                char *t;

                if (!(t = pa_locale_to_utf8(optarg)) ||
                    pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, t) < 0) {

                    pa_log(_("Invalid client name '%s'"), t ? t : optarg);
                    pa_xfree(t);
                    goto quit;
                }

                pa_xfree(t);
                break;
            }

            case ARG_STREAM_NAME: {
                char *t;

                if (!(t = pa_locale_to_utf8(optarg)) ||
                    pa_proplist_sets(proplist, PA_PROP_MEDIA_NAME, t) < 0) {

                    pa_log(_("Invalid stream name '%s'"), t ? t : optarg);
                    pa_xfree(t);
                    goto quit;
                }

                pa_xfree(t);
                break;
            }

            case 'v':
                verbose = 1;
                break;

            case ARG_VOLUME: {
                int v = atoi(optarg);
                volume = v < 0 ? 0U : (pa_volume_t) v;
                volume_is_set = TRUE;
                break;
            }

            case ARG_CHANNELS:
                sample_spec.channels = (uint8_t) atoi(optarg);
                sample_spec_set = TRUE;
                break;

            case ARG_SAMPLEFORMAT:
                sample_spec.format = pa_parse_sample_format(optarg);
                sample_spec_set = TRUE;
                break;

            case ARG_SAMPLERATE:
                sample_spec.rate = (uint32_t) atoi(optarg);
                sample_spec_set = TRUE;
                break;

            case ARG_CHANNELMAP:
                if (!pa_channel_map_parse(&channel_map, optarg)) {
                    pa_log(_("Invalid channel map '%s'"), optarg);
                    goto quit;
                }

                channel_map_set = TRUE;
                break;

            case ARG_FIX_CHANNELS:
                flags |= PA_STREAM_FIX_CHANNELS;
                break;

            case ARG_FIX_RATE:
                flags |= PA_STREAM_FIX_RATE;
                break;

            case ARG_FIX_FORMAT:
                flags |= PA_STREAM_FIX_FORMAT;
                break;

            case ARG_NO_REMIX:
                flags |= PA_STREAM_NO_REMIX_CHANNELS;
                break;

            case ARG_NO_REMAP:
                flags |= PA_STREAM_NO_REMAP_CHANNELS;
                break;

            case ARG_LATENCY:
                if (((latency = (size_t) atoi(optarg))) <= 0) {
                    pa_log(_("Invalid latency specification '%s'"), optarg);
                    goto quit;
                }
                break;

            case ARG_PROCESS_TIME:
                if (((process_time = (size_t) atoi(optarg))) <= 0) {
                    pa_log(_("Invalid process time specification '%s'"), optarg);
                    goto quit;
                }
                break;

            case ARG_LATENCY_MSEC:
                if (((latency_msec = (int32_t) atoi(optarg))) <= 0) {
                    pa_log(_("Invalid latency specification '%s'"), optarg);
                    goto quit;
                }
                break;

            case ARG_PROCESS_TIME_MSEC:
                if (((process_time_msec = (int32_t) atoi(optarg))) <= 0) {
                    pa_log(_("Invalid process time specification '%s'"), optarg);
                    goto quit;
                }
                break;

            case ARG_PROPERTY: {
                char *t;

                if (!(t = pa_locale_to_utf8(optarg)) ||
                    pa_proplist_setp(proplist, t) < 0) {

                    pa_xfree(t);
                    pa_log(_("Invalid property '%s'"), optarg);
                    goto quit;
                }

                pa_xfree(t);
                break;
            }

            case ARG_RAW:
                raw = TRUE;
                break;

            case ARG_PASSTHROUGH:
                flags |= PA_STREAM_PASSTHROUGH;
                break;

            case ARG_FILE_FORMAT:
                if (optarg) {
                    if ((file_format = pa_sndfile_format_from_string(optarg)) < 0) {
                        pa_log(_("Unknown file format %s."), optarg);
                        goto quit;
                    }
                }

                raw = FALSE;
                break;

            case ARG_LIST_FILE_FORMATS:
                pa_sndfile_dump_formats();
                ret = 0;
                goto quit;

            default:
                goto quit;
        }
    }

    if (!pa_sample_spec_valid(&sample_spec)) {
        pa_log(_("Invalid sample specification"));
        goto quit;
    }

    if (optind+1 == argc) {
        int fd;

        filename = argv[optind];

        if ((fd = pa_open_cloexec(argv[optind], mode == PLAYBACK ? O_RDONLY : O_WRONLY|O_TRUNC|O_CREAT, 0666)) < 0) {
            pa_log(_("open(): %s"), strerror(errno));
            goto quit;
        }

        if (dup2(fd, mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO) < 0) {
            pa_log(_("dup2(): %s"), strerror(errno));
            goto quit;
        }

        pa_close(fd);

    } else if (optind+1 <= argc) {
        pa_log(_("Too many arguments."));
        goto quit;
    }

    if (!raw) {
        SF_INFO sfi;
        pa_zero(sfi);

        if (mode == RECORD) {
            /* This might patch up the sample spec */
            if (pa_sndfile_write_sample_spec(&sfi, &sample_spec) < 0) {
                pa_log(_("Failed to generate sample specification for file."));
                goto quit;
            }

            if (file_format <= 0) {
                char *extension;
                if (filename && (extension = strrchr(filename, '.')))
                    file_format = pa_sndfile_format_from_string(extension+1);
                if (file_format <= 0)
                    file_format = SF_FORMAT_WAV;
                /* Transparently upgrade classic .wav to wavex for multichannel audio */
                if (file_format == SF_FORMAT_WAV &&
                    (sample_spec.channels > 2 ||
                    (channel_map_set &&
                    !(sample_spec.channels == 1 && channel_map.map[0] == PA_CHANNEL_POSITION_MONO) &&
                    !(sample_spec.channels == 2 && channel_map.map[0] == PA_CHANNEL_POSITION_LEFT
                                                && channel_map.map[1] == PA_CHANNEL_POSITION_RIGHT))))
                    file_format = SF_FORMAT_WAVEX;
            }

            sfi.format |= file_format;
        }

        if (!(sndfile = sf_open_fd(mode == RECORD ? STDOUT_FILENO : STDIN_FILENO,
                                   mode == RECORD ? SFM_WRITE : SFM_READ,
                                   &sfi, 0))) {
            pa_log(_("Failed to open audio file."));
            goto quit;
        }

        if (mode == PLAYBACK) {
            if (sample_spec_set)
                pa_log(_("Warning: specified sample specification will be overwritten with specification from file."));

            if (pa_sndfile_read_sample_spec(sndfile, &sample_spec) < 0) {
                pa_log(_("Failed to determine sample specification from file."));
                goto quit;
            }
            sample_spec_set = TRUE;

            if (!channel_map_set) {
                /* Allow the user to overwrite the channel map on the command line */
                if (pa_sndfile_read_channel_map(sndfile, &channel_map) < 0) {
                    if (sample_spec.channels > 2)
                        pa_log(_("Warning: Failed to determine channel map from file."));
                } else
                    channel_map_set = TRUE;
            }
        }
    }

    if (!channel_map_set)
        pa_channel_map_init_extend(&channel_map, sample_spec.channels, PA_CHANNEL_MAP_DEFAULT);

    if (!pa_channel_map_compatible(&channel_map, &sample_spec)) {
        pa_log(_("Channel map doesn't match sample specification"));
        goto quit;
    }

    if (!raw) {
        pa_proplist *sfp;

        if (mode == PLAYBACK)
            readf_function = pa_sndfile_readf_function(&sample_spec);
        else {
            if (pa_sndfile_write_channel_map(sndfile, &channel_map) < 0)
                pa_log(_("Warning: failed to write channel map to file."));

            writef_function = pa_sndfile_writef_function(&sample_spec);
        }

        /* Fill in libsndfile prop list data */
        sfp = pa_proplist_new();
        pa_sndfile_init_proplist(sndfile, sfp);
        pa_proplist_update(proplist, PA_UPDATE_MERGE, sfp);
        pa_proplist_free(sfp);
    }

    if (verbose) {
        char tss[PA_SAMPLE_SPEC_SNPRINT_MAX], tcm[PA_CHANNEL_MAP_SNPRINT_MAX];

        pa_log(_("Opening a %s stream with sample specification '%s' and channel map '%s'."),
                mode == RECORD ? _("recording") : _("playback"),
                pa_sample_spec_snprint(tss, sizeof(tss), &sample_spec),
                pa_channel_map_snprint(tcm, sizeof(tcm), &channel_map));
    }

    /* Fill in client name if none was set */
    if (!pa_proplist_contains(proplist, PA_PROP_APPLICATION_NAME)) {
        char *t;

        if ((t = pa_locale_to_utf8(bn))) {
            pa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, t);
            pa_xfree(t);
        }
    }

    /* Fill in media name if none was set */
    if (!pa_proplist_contains(proplist, PA_PROP_MEDIA_NAME)) {
        const char *t;

        if ((t = filename) ||
            (t = pa_proplist_gets(proplist, PA_PROP_APPLICATION_NAME)))
            pa_proplist_sets(proplist, PA_PROP_MEDIA_NAME, t);

        if (!pa_proplist_contains(proplist, PA_PROP_MEDIA_NAME)) {
            pa_log(_("Failed to set media name."));
            goto quit;
        }
    }

    /* Set up a new main loop */
    if (!(m = pa_mainloop_new())) {
        pa_log(_("pa_mainloop_new() failed."));
        goto quit;
    }

    mainloop_api = pa_mainloop_get_api(m);

    pa_assert_se(pa_signal_init(mainloop_api) == 0);
    pa_signal_new(SIGINT, exit_signal_callback, NULL);
    pa_signal_new(SIGTERM, exit_signal_callback, NULL);
#ifdef SIGUSR1
    pa_signal_new(SIGUSR1, sigusr1_signal_callback, NULL);
#endif
    pa_disable_sigpipe();

    if (raw) {
#ifdef OS_IS_WIN32
        /* need to turn on binary mode for stdio io. Windows, meh */
        setmode(mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO, O_BINARY);
#endif
        if (!(stdio_event = mainloop_api->io_new(mainloop_api,
                                                 mode == PLAYBACK ? STDIN_FILENO : STDOUT_FILENO,
                                                 mode == PLAYBACK ? PA_IO_EVENT_INPUT : PA_IO_EVENT_OUTPUT,
                                                 mode == PLAYBACK ? stdin_callback : stdout_callback, &type))) {
            pa_log(_("io_new() failed."));
            goto quit;
        }
    }

    /* Create a new connection context */
    if (!(context = pa_context_new_with_proplist(mainloop_api, NULL, proplist))) {
        pa_log(_("pa_context_new() failed."));
        goto quit;
    }

    pa_context_set_state_callback(context, context_state_callback, NULL);

    /* Connect the context */
    if (pa_context_connect(context, server, 0, NULL) < 0) {
        pa_log(_("pa_context_connect() failed: %s"), pa_strerror(pa_context_errno(context)));
        goto quit;
    }

    if (verbose) {
        if (!(time_event = pa_context_rttime_new(context, pa_rtclock_now() + TIME_EVENT_USEC, time_event_callback, NULL))) {
            pa_log(_("pa_context_rttime_new() failed."));
            goto quit;
        }
    }

    /* Run the main loop */
    if (pa_mainloop_run(m, &ret) < 0) {
        pa_log(_("pa_mainloop_run() failed."));
        goto quit;
    }

quit:
    if (stream)
        pa_stream_unref(stream);

    if (context)
        pa_context_unref(context);

    if (stdio_event) {
        pa_assert(mainloop_api);
        mainloop_api->io_free(stdio_event);
    }

    if (time_event) {
        pa_assert(mainloop_api);
        mainloop_api->time_free(time_event);
    }

    if (m) {
        pa_signal_done();
        pa_mainloop_free(m);
    }

    pa_xfree(silence_buffer);
    pa_xfree(buffer);

    pa_xfree(server);
    pa_xfree(device);

    if (sndfile)
        sf_close(sndfile);

    if (proplist)
        pa_proplist_free(proplist);

    return ret;
}
示例#12
0
AUD_SndFileWriter::~AUD_SndFileWriter()
{
	sf_close(m_sndfile);
}
示例#13
0
void World_NonRealTimeSynthesis(struct World *world, WorldOptions *inOptions)
{
	if (inOptions->mLoadGraphDefs) {
		World_LoadGraphDefs(world);
	}
	int bufLength = world->mBufLength;
	int fileBufFrames = inOptions->mPreferredHardwareBufferFrameSize;
	if (fileBufFrames <= 0) fileBufFrames = 8192;
	int bufMultiple = (fileBufFrames + bufLength - 1) / bufLength;
	fileBufFrames = bufMultiple * bufLength;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

			World_Run(world);

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

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

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

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

	free(packet.mData);
	World_Cleanup(world,true);
}
示例#14
0
int
main (int argc, char **argv)
{	STATE state ;
	SF_INFO sfinfo ;
	int k, double_merge = 0 ;

	if (argc < 5)
	{	if (argc > 1)
			puts ("\nError : need at least 2 input files.") ;
		usage_exit () ;
	} ;

	if (strcmp (argv [argc - 2], "-o") != 0)
	{	puts ("\nError : second last command line parameter should be '-o'.\n") ;
		usage_exit () ;
	} ;

	if (argc - 3 > MAX_INPUTS)
	{	printf ("\nError : Cannot handle more than %d input channels.\n\n", MAX_INPUTS) ;
		exit (1) ;
	} ;

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

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

		if (sfinfo.channels != 1)
		{	printf ("\bError : Input file '%s' should be mono (has %d channels).\n", argv [k], sfinfo.channels) ;
			exit (1) ;
		} ;

		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_FLOAT :
			case SF_FORMAT_DOUBLE :
			case SF_FORMAT_VORBIS :
				double_merge = 1 ;
				break ;

			default :
				break ;
		} ;

		state.channels ++ ;
	} ;

	sfinfo.channels = state.channels ;
	sfinfo.format = sfe_file_type_of_ext (argv [argc - 1], sfinfo.format) ;

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

	if (double_merge)
		interleave_double (&state) ;
	else
		interleave_int (&state) ;

	for (k = 0 ; k < MAX_INPUTS ; k++)
		if (state.infile [k] != NULL)
			sf_close (state.infile [k]) ;
	sf_close (state.outfile) ;

	return 0 ;
} /* main */
示例#15
0
void
PlayAudioFile( char *filename, int volume )
{
  static short buffer[BUFFER_LEN];
  SNDFILE *sndfile;
  SF_INFO sfinfo;
  int audio_fd;
  int readcount;
  int status;
#if defined (__linux__)
  int subformat;
  int m;
#elif( defined(sun) && defined(unix) )
  unsigned long	delay_time;
  long start_count, output_count, write_count;
  bool done;
#endif

  if( wmnotify_infos.debug ) {
    printf( "%s: PlayAudioFile() Entry\n", PACKAGE );
  }

  if( filename == NULL ) {
    fprintf( stderr, "%s: No audio file specified.\n", PACKAGE );
    ErrorLocation( __FILE__, __LINE__ );
    exit( EXIT_FAILURE );
  }

  sndfile = sf_open( filename, SFM_READ, &sfinfo );

  if( sndfile == NULL ) {
    fprintf( stderr, "%s: sf_open() failed trying to open '%s':\n", PACKAGE, filename );
    fprintf( stderr, "  %s\n", sf_strerror(NULL) );
    fprintf( stderr, "  Check if file exists and has correct read permissions.\n" );
    ErrorLocation( __FILE__, __LINE__ );
    return;
  }

  if( sfinfo.channels < 1 || sfinfo.channels > 2 ) {
    fprintf( stderr, "%s: Audio file has %d channel(s), but ", PACKAGE, sfinfo.channels );
    fprintf( stderr, "we support only 1 or 2 channels.\n" );
    ErrorLocation( __FILE__, __LINE__ );
    exit( EXIT_FAILURE );
  }

  audio_fd = OpenDspDevice( sfinfo.channels, sfinfo.samplerate );
  if( audio_fd < 0 ) {
    goto play_audio_file_close_file;
  }

#if( defined(sun) && defined(unix) )
  /* Delay time equal to 1/4 of a buffer in microseconds. */
  delay_time = (BUFFER_LEN * 1000000) / (sfinfo.samplerate * 4);
#endif

  subformat = sfinfo.format & SF_FORMAT_SUBMASK;

  if( subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE ) {
    static float flt_buffer[BUFFER_LEN];
    double scale;

    status = sf_command( sndfile, SFC_CALC_SIGNAL_MAX, &scale, (int) sizeof(scale) );
    if( status == 0 ) {
      fprintf( stderr, "%s: Warning, sf_command() failed.\n", PACKAGE );
      ErrorLocation( __FILE__, __LINE__ );
      goto play_audio_file_close_audio;
    }

    if (scale < 1e-10) {
      scale = 1.0;
    }
    else {
      scale = 32700.0 / scale;
    }

    while( ( readcount = (int) sf_read_float( sndfile, flt_buffer, BUFFER_LEN ) ) != 0 ) {
    /* Linux/OSS -- FLOAT samples */
#if defined (__linux__)
      for( m = 0 ; m < readcount ; m++ ) {
	/* Float to integer conversion. */
	buffer[m] = (short) ( scale * flt_buffer[m] );
	/* Changing volume */
	buffer[m] = buffer[m] * volume / 100;
      }
      status = (int) write( audio_fd, buffer, readcount * sizeof(short) );
      if( status == -1 ) {
	perror( PACKAGE );
	ErrorLocation( __FILE__, __LINE__ );
	goto play_audio_file_close_audio;
      }

      /* Solaris -- FLOAT samples */
#elif( defined(sun) && defined(unix) )
      start_count = 0;
      output_count = read_count * sizeof(short);

      while( output_count > 0 ) {
	/* Write as much data as possible */
	for( m = 0 ; m < readcount ; m++ ) {
	  /* Float to integer conversion. */
	  buffer[m] = (short) ( scale * flt_buffer[m] );
	  /* Changing volume */
	  buffer[m] = buffer[m] * volume / 100;
	}

	write_count = write( audio_fd, &(buffer[start_count]), output_count );
	if( write_count > 0 ) {
	  output_count -= write_count;
	  start_count += write_count;
	}
	else {
	  /* Give the audio output time to catch up. */
	  usleep( delay_time );
	}
      } /* while( output_count > 0 ) */
#endif
    } /* while( ( readcount... ) */
  }
  else {
    while( ( readcount = (int) sf_read_short( sndfile, buffer, BUFFER_LEN ) ) != 0 ) {
      /* Linux/OSS -- INTEGER samples */
#if defined (__linux__)
      /* Changing volume... */
      for( m = 0 ; m < readcount ; m++ ) {
	buffer[m] = ( buffer[m] * volume ) / 100;
      }

      status = (int) write( audio_fd, buffer, readcount * sizeof(short) );
      if( status == -1 ) {
	perror( PACKAGE );
	ErrorLocation( __FILE__, __LINE__ );
	goto play_audio_file_close_audio;
      }

      /* Solaris -- INTEGER samples */
#elif( defined(sun) && defined(unix) )
      start_count = 0;
      output_count = read_count * sizeof(short);

      while( output_count > 0 ) {
	/* Write as much data as possible */

	/* Changing volume. */
	for( m = 0 ; m < read_count ; m++ ) {
	  buffer[m] = ( buffer[m] * volume ) / 100;
	}

	write_count = write( audio_fd, &(buffer[start_count]), output_count );
	if( write_count > 0 ) {
	  output_count -= write_count;
	  start_count += write_count;
	}
	else {
	  /* Give the audio output time to catch up. */
	  usleep( delay_time );
	}
      } /* while( output_count > 0 ) */
#endif
    } /* while( ( readcount... ) */
  } /* else */

 play_audio_file_close_audio:

  status = close( audio_fd );
  if( status != 0 ) {
    fprintf( stderr, "%s: Error, close() failed.\n", PACKAGE );
    ErrorLocation( __FILE__, __LINE__ );
    exit( EXIT_FAILURE );
  }

 play_audio_file_close_file:

  status = sf_close( sndfile );
  if( status != 0 ) {
    fprintf( stderr, "%s: Error, sf_close() failed.\n", PACKAGE );
    ErrorLocation( __FILE__, __LINE__ );
    exit( EXIT_FAILURE );
  }

  if( wmnotify_infos.debug ) {
    printf( "%s: PlayAudioFile() Exit\n", PACKAGE );
  }

  return;
}
示例#16
0
int lsamp_close_sfile(lsamp_data *ls){
    sf_close(ls->sfile);
    return 0;
}
示例#17
0
int main (int argc, char *argv[])
{
    int i;
    int j;
    int level;
    int clip_high;
    int clip_low;
    int quality;
    int total_samples;
    int seed = 1234567;
    int outframes;
    int16_t value;
    double total;
    double x;
    double p;
    double o;
    int bins[65536];
    int16_t amp[1024];
    noise_state_t noise_source;
    SNDFILE *outhandle;

    if ((outhandle = sf_open_telephony_write(OUT_FILE_NAME, 1)) == NULL)
    {
        fprintf(stderr, "    Cannot create audio file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }

    for (quality = 7;  quality <= 20;  quality += (20 - 7))
    {
        /* Generate AWGN at several RMS levels between -50dBOv and 0dBOv. Noise is
           generated for a large number of samples (1,000,000), and the RMS value
           of the noise is calculated along the way. If the resulting level is
           close to the requested RMS level, at least the scaling of the noise
           should be Ok. At high levels some clipping may distort the result a
           little. */
        printf("Testing AWGN power, with quality %d\n", quality);
        for (level = -50;  level <= 0;  level += 5)
        {
            clip_high = 0;
            clip_low = 0;
            total = 0.0;
            noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_AWGN, quality);
            total_samples = 1000000;
            for (i = 0;  i < total_samples;  i++)
            {
                value = noise(&noise_source);
                if (value == 32767)
                    clip_high++;
                else if (value == -32768)
                    clip_low++;
                total += ((double) value)*((double) value);
            }
            printf ("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n",
                    log10(sqrt(total/total_samples)/32768.0)*20.0,
                    level,
                    100.0*(1.0 - sqrt(total/total_samples)/(pow(10.0, level/20.0)*32768.0)),
                    clip_low,
                    clip_high);
            if (level < -5  &&  fabs(log10(sqrt(total/total_samples)/32768.0)*20.0 - level) > 0.2)
            {
                printf("Test failed\n");
                exit(2);
            }
        }
    }

    /* Now look at the statistical spread of the results, by collecting data in
       bins from a large number of samples. Use a fairly high noise level, but
       low enough to avoid significant clipping. Use the Gaussian model to
       predict the real probability, and present the results for graphing. */
    quality = 7;
    printf("Testing the statistical spread of AWGN, with quality %d\n", quality);
    memset(bins, 0, sizeof(bins));
    clip_high = 0;
    clip_low = 0;
    level = -15;
    noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_AWGN, quality);
    total_samples = 10000000;
    for (i = 0;  i < total_samples;  i++)
    {
        value = noise(&noise_source);
        if (value == 32767)
            clip_high++;
        else if (value == -32768)
            clip_low++;
        bins[value + 32768]++;
    }
    /* Find the RMS power level to expect */
    o = pow(10.0, level/20.0)*(32768.0*0.70711);
    for (i = 0;  i < 65536 - 10;  i++)
    {
        x = i - 32768;
        /* Find the real probability for this bin */
        p = (1.0/(o*sqrt(2.0*M_PI)))*exp(-(x*x)/(2.0*o*o));
        /* Now do a little smoothing on the real data to get a reasonably
           steady answer */
        x = 0;
        for (j = 0;  j < 10;  j++)
            x += bins[i + j];
        x /= 10.0;
        x /= total_samples;
        /* Now send it out for graphing. */
        if (p > 0.0000001)
            printf("%6d %.7f %.7f\n", i - 32768, x, p);
    }

    printf("Generating AWGN at -15dBOv to file\n");
    for (j = 0;  j < 50;  j++)
    {
        for (i = 0;  i < 1024;  i++)
            amp[i] = noise(&noise_source);
        outframes = sf_writef_short(outhandle, amp, 1024);
        if (outframes != 1024)
        {
            fprintf(stderr, "    Error writing audio file\n");
            exit(2);
        }
    }

    /* Generate Hoth noise at several RMS levels between -50dBm and 0dBm. Noise
       is generated for a large number of samples (1,000,000), and the RMS value
       of the noise is calculated along the way. If the resulting level is
       close to the requested RMS level, at least the scaling of the noise
       should be Ok. At high levels some clipping may distort the result a
       little. */
    quality = 7;
    printf("Testing Hoth noise power, with quality %d\n", quality);
    for (level = -50;  level <= 0;  level += 5)
    {
        clip_high = 0;
        clip_low = 0;
        total = 0.0;
        noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_HOTH, quality);
        total_samples = 1000000;
        for (i = 0;  i < total_samples;  i++)
        {
            value = noise(&noise_source);
            if (value == 32767)
                clip_high++;
            else if (value == -32768)
                clip_low++;
            total += ((double) value)*((double) value);
        }
        printf ("RMS = %.3f (expected %d) %.2f%% error [clipped samples %d+%d]\n",
                log10(sqrt(total/total_samples)/32768.0)*20.0,
                level,
                100.0*(1.0 - sqrt(total/total_samples)/(pow(10.0, level/20.0)*32768.0)),
                clip_low,
                clip_high);
        if (level < -5  &&  fabs(log10(sqrt(total/total_samples)/32768.0)*20.0 - level) > 0.2)
        {
            printf("Test failed\n");
            exit(2);
        }
    }
    
    quality = 7;
    printf("Generating Hoth noise at -15dBOv to file\n");
    level = -15;
    noise_init_dbov(&noise_source, seed, (float) level, NOISE_CLASS_HOTH, quality);
    for (j = 0;  j < 50;  j++)
    {
        for (i = 0;  i < 1024;  i++)
            amp[i] = noise(&noise_source);
        outframes = sf_writef_short(outhandle, amp, 1024);
        if (outframes != 1024)
        {
            fprintf(stderr, "    Error writing audio file\n");
            exit(2);
        }
    }

    if (sf_close(outhandle))
    {
        fprintf(stderr, "    Cannot close audio file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    
    printf("Tests passed.\n");
    return  0;
}
示例#18
0
int main(int argc, char *argv[])
{
    int i;
    SNDFILE *inhandle;
    SNDFILE *outhandle;
    int frames;
    int dec_frames;
    int outframes;
    int oki_bytes;
    int bit_rate;
    double pre_energy;
    double post_energy;
    double diff_energy;
    int16_t pre_amp[HIST_LEN];
    int16_t post_amp[HIST_LEN];
    uint8_t oki_data[HIST_LEN];
    int16_t history[HIST_LEN];
    int hist_in;
    int hist_out;
    oki_adpcm_state_t *oki_enc_state;
    oki_adpcm_state_t *oki_dec_state;
    oki_adpcm_state_t *oki_dec_state2;
    int xx;
    int total_pre_samples;
    int total_compressed_bytes;
    int total_post_samples;
    int successive_08_bytes;
    int successive_80_bytes;
    int encoded_fd;
    const char *encoded_file_name;
    const char *in_file_name;
    int log_encoded_data;
    int opt;

    bit_rate = 32000;
    encoded_file_name = NULL;
    in_file_name = IN_FILE_NAME;
    log_encoded_data = FALSE;
    while ((opt = getopt(argc, argv, "2d:i:l")) != -1)
    {
        switch (opt)
        {
        case '2':
            bit_rate = 24000;
            break;
        case 'd':
            encoded_file_name = optarg;
            break;
        case 'i':
            in_file_name = optarg;
            break;
        case 'l':
            log_encoded_data = TRUE;
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }

    if (encoded_file_name)
    {
        if ((encoded_fd = open(encoded_file_name, O_RDONLY)) < 0)
        {
            fprintf(stderr, "    Cannot open encoded file '%s'\n", encoded_file_name);
            exit(2);
        }
    }
    else
    {
        if ((inhandle = sf_open_telephony_read(in_file_name, 1)) == NULL)
        {
            fprintf(stderr, "    Cannot open audio file '%s'\n", in_file_name);
            exit(2);
        }
        if ((oki_enc_state = oki_adpcm_init(NULL, bit_rate)) == NULL)
        {
            fprintf(stderr, "    Cannot create encoder\n");
            exit(2);
        }
    }

    if ((outhandle = sf_open_telephony_write(OUT_FILE_NAME, 1)) == NULL)
    {
        fprintf(stderr, "    Cannot create audio file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }
    if ((oki_dec_state = oki_adpcm_init(NULL, bit_rate)) == NULL)
    {
        fprintf(stderr, "    Cannot create decoder\n");
        exit(2);
    }
    if ((oki_dec_state2 = oki_adpcm_init(NULL, bit_rate)) == NULL)
    {
        fprintf(stderr, "    Cannot create decoder\n");
        exit(2);
    }

    hist_in = 0;
    if (bit_rate == 32000)
        hist_out = 0;
    else
        hist_out = HIST_LEN - 27;
    memset(history, 0, sizeof(history));
    pre_energy = 0.0;
    post_energy = 0.0;
    diff_energy = 0.0;
    total_pre_samples = 0;
    total_compressed_bytes = 0;
    total_post_samples = 0;
    if (encoded_file_name)
    {
        /* Decode a file of OKI ADPCM code to a linear wave file */
        while ((oki_bytes = read(encoded_fd, oki_data, 80)) > 0)
        {
            total_compressed_bytes += oki_bytes;
            dec_frames = oki_adpcm_decode(oki_dec_state, post_amp, oki_data, oki_bytes);
            total_post_samples += dec_frames;
            for (i = 0;  i < dec_frames;  i++)
            {
                post_energy += (double) post_amp[i] * (double) post_amp[i];
                xx = post_amp[i] - history[hist_out++];
                if (hist_out >= HIST_LEN)
                    hist_out = 0;
                diff_energy += (double) xx * (double) xx;
            }
            outframes = sf_writef_short(outhandle, post_amp, dec_frames);
        }
        close(encoded_fd);
    }
    else
    {
        /* Perform a linear wave file -> OKI ADPCM -> linear wave file cycle. Along the way
           check the decoder resets on the sequence specified for this codec, and the gain
           and worst case sample distortion. */
        successive_08_bytes = 0;
        successive_80_bytes = 0;
        while ((frames = sf_readf_short(inhandle, pre_amp, 159)))
        {
            total_pre_samples += frames;
            oki_bytes = oki_adpcm_encode(oki_enc_state, oki_data, pre_amp, frames);
            if (log_encoded_data)
                write(1, oki_data, oki_bytes);
            total_compressed_bytes += oki_bytes;
            /* Look for a condition which is defined as something which should cause a reset of
               the decoder (48 samples of 0, 8, 0, 8, etc.), and verify that it really does. Use
               a second decode, which we feed byte by byte, for this. */
            for (i = 0;  i < oki_bytes;  i++)
            {
                oki_adpcm_decode(oki_dec_state2, post_amp, &oki_data[i], 1);
                if (oki_data[i] == 0x08)
                    successive_08_bytes++;
                else
                    successive_08_bytes = 0;
                if (oki_data[i] == 0x80)
                    successive_80_bytes++;
                else
                    successive_80_bytes = 0;
                if (successive_08_bytes == 24  ||  successive_80_bytes == 24)
                {
                    if (oki_dec_state2->step_index != 0)
                    {
                        fprintf(stderr, "Decoder reset failure\n");
                        exit(2);
                    }
                }
            }
            dec_frames = oki_adpcm_decode(oki_dec_state, post_amp, oki_data, oki_bytes);
            total_post_samples += dec_frames;
            for (i = 0;  i < frames;  i++)
            {
                history[hist_in++] = pre_amp[i];
                if (hist_in >= HIST_LEN)
                    hist_in = 0;
                pre_energy += (double) pre_amp[i] * (double) pre_amp[i];
            }
            for (i = 0;  i < dec_frames;  i++)
            {
                post_energy += (double) post_amp[i] * (double) post_amp[i];
                xx = post_amp[i] - history[hist_out++];
                if (hist_out >= HIST_LEN)
                    hist_out = 0;
                diff_energy += (double) xx * (double) xx;
                //post_amp[i] = xx;
            }
            outframes = sf_writef_short(outhandle, post_amp, dec_frames);
        }
        printf("Pre samples: %d\n", total_pre_samples);
        printf("Compressed bytes: %d\n", total_compressed_bytes);
        printf("Post samples: %d\n", total_post_samples);

        printf("Output energy is %f%% of input energy.\n", 100.0*post_energy/pre_energy);
        printf("Residual energy is %f%% of the total.\n", 100.0*diff_energy/post_energy);
        if (bit_rate == 32000)
        {
            if (fabs(1.0 - post_energy/pre_energy) > 0.01
                ||
                fabs(diff_energy/post_energy) > 0.01)
            {
                printf("Tests failed.\n");
                exit(2);
            }
        }
        else
        {
            if (fabs(1.0 - post_energy/pre_energy) > 0.11
                ||
                fabs(diff_energy/post_energy) > 0.05)
            {
                printf("Tests failed.\n");
                exit(2);
            }
        }


        oki_adpcm_release(oki_enc_state);
        if (sf_close(inhandle) != 0)
        {
            fprintf(stderr, "    Cannot close audio file '%s'\n", in_file_name);
            exit(2);
        }
    }
    oki_adpcm_release(oki_dec_state);
    oki_adpcm_release(oki_dec_state2);
    if (sf_close(outhandle) != 0)
    {
        fprintf(stderr, "    Cannot close audio file '%s'\n", OUT_FILE_NAME);
        exit(2);
    }

    printf("Tests passed.\n");
    return 0;
}
示例#19
0
文件: cosby.c 项目: nicknassar/cosby
/* Initialize. Play out what we need to. Get out. */
int press_play(char *data_filename, char *wave_filename) {
  double *one_audio;
  double *zero_audio;
  void *out_file;
  FILE *in_file;
  char cur_byte;
  int is_pos;
  int (*output_samples)(void *,double *,size_t);

  make_output_audio(&zero_audio, &one_audio,DEFAULT_WAVELENGTH);

  /* If there's no filename, use the standard input */
  if (data_filename == NULL)
    in_file = stdin;
  else
    in_file = fopen(data_filename,"r");

  if (in_file == NULL) {
    cosby_print_err("Couldn't open %s\n",data_filename);
    return -1;
  }
  if (wave_filename == NULL) {
    output_samples = &output_to_speaker;
    if (init_speaker_output(&out_file) < 0)
      return -1;
  } else {
    output_samples = &output_to_file;
    init_file_output(&out_file, wave_filename);
  } 
  /* Output five seconds of 0 */
  for (int c=0;c<DEFAULT_SAMPLE_RATE*5/DEFAULT_WAVELENGTH;c++) {
    output_samples(out_file,zero_audio,DEFAULT_WAVELENGTH);
  }

  /* Output a byte of all 1s */
  for (int n=7;n>=0;n--) {
    output_samples(out_file,one_audio,DEFAULT_WAVELENGTH/2);
  }
  is_pos = 1;

  /* Loop through the data and output the appropriate
     portion of the appropriate wave.

     If you understand this part, you pretty much understand
     playback. You could just take the sine instead of all that fancy
     FFT bull. FFTW is at its most ineffecient when it's generating a
     single wave. It's expensive to make the plan, so it's usually
     used by running the same plan over and over.
  */
  while (fread(&cur_byte,1,1,in_file)) {
    for (int n=7;n>=0;n--) {
      if (get_nth_bit(cur_byte,n)) {
	if (is_pos) {
	  /* positive one */
	  output_samples(out_file,one_audio,DEFAULT_WAVELENGTH/2);
	} else {
	  /* negative one */
	  output_samples(out_file,one_audio+DEFAULT_WAVELENGTH/4,DEFAULT_WAVELENGTH-DEFAULT_WAVELENGTH/2);
	}
      } else {
	if (is_pos) {
	  /* positive zero */
	  output_samples(out_file,zero_audio,DEFAULT_WAVELENGTH/2);
	} else {
	  /* negative zero */
	  output_samples(out_file,zero_audio+DEFAULT_WAVELENGTH/2,DEFAULT_WAVELENGTH-DEFAULT_WAVELENGTH/2);
	}
	is_pos = !is_pos;
      }
    }
  }

  /* and an extra half a wave for padding */
  if (is_pos) {
    /* positive zero */
    output_samples(out_file,zero_audio,DEFAULT_WAVELENGTH/2);
  } else {
    /* negative zero */
    output_samples(out_file,zero_audio+DEFAULT_WAVELENGTH/2,DEFAULT_WAVELENGTH-DEFAULT_WAVELENGTH/2);
  }

  if (wave_filename == NULL) {
    /* FIXME You forgot to close the soundcard on the way out, you jerk! */
  } else {
    sf_close((SNDFILE *)out_file);
  }

  /* Close the input file, free the audio */
  if (data_filename != NULL)
    fclose(in_file);
  free_audio_output(zero_audio, one_audio);
  return 0;
}
示例#20
0
/* Returns 0 if the file is read as a libsndfile
 * Returns 1 is not.
 * Returns -1 and spews if we have a system read error */
static
int read_sndfile(struct qp_source *source, struct qp_reader *rd)
{
  double *x, rate;
  size_t count;
  SNDFILE *file;
  SF_INFO info;
  size_t skip_lines;

  skip_lines = app->op_skip_lines;

  file = sf_open_fd(rd->fd, SFM_READ, &info, 0);
  if(!file)
  {
    QP_INFO("file \"%s\" is not readable by libsndfile\n",
        rd->filename);
    return 1; /* not a libsndfile */
  }
  else if(info.frames < skip_lines)
  {
    QP_INFO("file \"%s\" is readable by libsndfile with %"PRId64
        " samples which is less the lines to skip from --skip-lines=%zu\n",
        rd->filename, info.frames, skip_lines);
    return -1; /* error */
  }


  rate = info.samplerate;
  x = qp_malloc(sizeof(double)*(info.channels+1));

  source->num_channels = info.channels+1;
  source->channels = qp_realloc(source->channels,
        sizeof(struct qp_channel *)*(info.channels+2));
  source->channels[source->num_channels] = NULL;
  source->value_type = QP_TYPE_DOUBLE;

  /* use count as dummy index for now */
  for(count=0; count<source->num_channels; ++count)
    source->channels[count] =
      qp_channel_create(QP_CHANNEL_FORM_SERIES, QP_TYPE_DOUBLE);

  count = 0;

  while(1)
  {
    int i;

    if(sf_readf_double(file, x, 1) < 1)
      break;

    if(skip_lines)
    {
      --skip_lines;
      continue;
    }

    /* TODO: use other channel types like load as shorts or ints */

    qp_channel_series_double_append(source->channels[0], count/rate);
    for(i=0;i<info.channels;++i)
       qp_channel_series_double_append(source->channels[i+1], x[i]);

    ++count;
  }

  source->num_values = count;
  free(x);
  sf_close(file);

  if(count)
  {
    char label0[128];
    snprintf(label0, 128, "time (1/%d sec)", info.samplerate);
  
    source->labels = qp_malloc(sizeof(char *)*2);
    source->labels[0] = qp_strdup(label0);
    source->labels[1] = NULL;
    source->num_labels = 1;

    DEBUG("read\nlibsndfile \"%s\" with %d sound channel(s), "
        "at rate %d Hz with %zu values, %g seconds of sound\n",
        rd->filename,
        info.channels, info.samplerate,
        count, count/rate);
    return 0; /* success */
  }

  QP_WARN("No sound data found in file \"%s\"\n", rd->filename);
  return -1; /* fail no data in file, caller cleans up */
}
示例#21
0
文件: cosby.c 项目: nicknassar/cosby
/* free up those resources */
void free_audio_buffer(SNDFILE *in_file) {
  sf_close(in_file);
  fftw_free(audio_buffer);
}
示例#22
0
int main(int argc, char *argv[]) {

  /* initialize Madagascar */
  sf_init(argc, argv);

  Logger::instance().init("serial-fwi");

  FwiParams &params = FwiParams::instance();

  std::vector<float> dobs(params.ns * params.nt * params.ng); /* observed data */
  std::vector<float> cg(params.nz * params.nx, 0);    /* conjugate gradient */
  std::vector<float> g0(params.nz * params.nx, 0);    /* gradient at previous step */
  std::vector<float> wlt(params.nt); /* ricker wavelet */
  std::vector<float> objval(params.niter, 0); /* objective/misfit function */

  /* initialize wavelet */
  rickerWavelet(&wlt[0], params.nt, params.fm, params.dt, params.amp);

  ShotPosition allSrcPos(params.szbeg, params.sxbeg, params.jsz, params.jsx, params.ns, params.nz);
  ShotPosition allGeoPos(params.gzbeg, params.gxbeg, params.jgz, params.jgx, params.ng, params.nz);

  // read velocity
  Velocity v0 = SfVelocityReader::read(params.vinit, params.nx, params.nz);

  // read observed data
  ShotDataReader::serialRead(params.shots, &dobs[0], params.ns, params.nt, params.ng);

  EnquistAbc2d fmMethod(params.dt, params.dx, params.dz);
  Velocity vel = fmMethod.expandDomain(v0);

  float obj0 = 0;
  for (int iter = 0; iter < params.niter; iter++) {
    boost::timer::cpu_timer timer;
    std::vector<float> g1(params.nz * params.nx, 0);    /* gradient at curret step */
    std::vector<float> derr(params.ns * params.ng * params.nt, 0); /* residual/error between synthetic and observation */
    std::vector<float> illum(params.nz * params.nx, 0); /* illumination of the source wavefield */
    Velocity vtmp = vel;  /* temporary velocity computed with epsil */

    fmMethod.bindVelocity(vel);

    /**
     * calculate local objective function & derr & illum & g1(gradient)
     */
    float obj = cal_obj_derr_illum_grad(params, &derr[0], &illum[0], &g1[0], &wlt[0], &dobs[0], fmMethod, allSrcPos, allGeoPos);

    DEBUG() << format("sum_derr %f, sum_illum %f, sum_g1 %f") % sum(derr) % sum(illum) % sum(g1);
    objval[iter] = iter == 0 ? obj0 = obj, 1.0 : obj / obj0;

    float epsil = 0;
    float beta = 0;
    sf_floatwrite(&illum[0], params.nz * params.nx, params.illums);

    scale_gradient(&g1[0], &vel.dat[0], &illum[0], params.nz, params.nx, params.precon);
    bell_smoothz(&g1[0], &illum[0], params.rbell, params.nz, params.nx);
    bell_smoothx(&illum[0], &g1[0], params.rbell, params.nz, params.nx);
    sf_floatwrite(&g1[0], params.nz * params.nx, params.grads);

    DEBUG() << format("before beta: sum_g0: %f, sum_g1: %f, sum_cg: %f") % sum(g0) % sum(g1) % sum(cg);
    beta = iter == 0 ? 0.0 : cal_beta(&g0[0], &g1[0], &cg[0], params.nz, params.nx);

    cal_conjgrad(&g1[0], &cg[0], beta, params.nz, params.nx);
    epsil = cal_epsilon(&vel.dat[0], &cg[0], params.nz, params.nx);
    cal_vtmp(&vtmp.dat[0], &vel.dat[0], &cg[0], epsil, params.nz, params.nx);

    std::swap(g1, g0); // let g0 be the previous gradient

    fmMethod.bindVelocity(vtmp);
    float alpha = calVelUpdateStepLen(params, &wlt[0], &dobs[0], &derr[0], epsil, fmMethod, allSrcPos, allGeoPos);

    update_vel(&vel.dat[0], &cg[0], alpha, params.nz, params.nx);

    sf_floatwrite(&vel.dat[0], params.nz * params.nx, params.vupdates);

    // output important information at each FWI iteration
    INFO() << format("iteration %d obj=%f  beta=%f  epsil=%f  alpha=%f") % (iter + 1) % obj % beta % epsil % alpha;
//    INFO() << timer.format(2);

  } /// end of iteration

  sf_floatwrite(&objval[0], params.niter, params.objs);

  sf_close();

  return 0;
}
示例#23
0
int main(int argc, char *argv[])
{
    v27ter_rx_state_t *rx;
    v27ter_tx_state_t *tx;
    bert_results_t bert_results;
    int16_t gen_amp[BLOCK_LEN];
    int16_t amp[BLOCK_LEN];
    SNDFILE *inhandle;
    SNDFILE *outhandle;
    int outframes;
    int samples;
    int tep;
    int test_bps;
    int noise_level;
    int signal_level;
    int bits_per_test;
    int line_model_no;
    int block_no;
    int log_audio;
    int channel_codec;
    int rbs_pattern;
    int opt;
    logging_state_t *logging;

    channel_codec = MUNGE_CODEC_NONE;
    rbs_pattern = 0;
    test_bps = 4800;
    tep = FALSE;
    line_model_no = 0;
    decode_test_file = NULL;
    use_gui = FALSE;
    noise_level = -70;
    signal_level = -13;
    bits_per_test = 50000;
    log_audio = FALSE;
    while ((opt = getopt(argc, argv, "b:B:c:d:glm:n:r:s:t")) != -1)
    {
        switch (opt)
        {
        case 'b':
            test_bps = atoi(optarg);
            if (test_bps != 4800  &&  test_bps != 2400)
            {
                fprintf(stderr, "Invalid bit rate specified\n");
                exit(2);
            }
            break;
        case 'B':
            bits_per_test = atoi(optarg);
            break;
        case 'c':
            channel_codec = atoi(optarg);
            break;
        case 'd':
            decode_test_file = optarg;
            break;
        case 'g':
#if defined(ENABLE_GUI)
            use_gui = TRUE;
#else
            fprintf(stderr, "Graphical monitoring not available\n");
            exit(2);
#endif
            break;
        case 'l':
            log_audio = TRUE;
            break;
        case 'm':
            line_model_no = atoi(optarg);
            break;
        case 'n':
            noise_level = atoi(optarg);
            break;
        case 'r':
            rbs_pattern = atoi(optarg);
            break;
        case 's':
            signal_level = atoi(optarg);
            break;
        case 't':
            tep = TRUE;
            break;
        default:
            //usage();
            exit(2);
            break;
        }
    }
    inhandle = NULL;
    outhandle = NULL;

#if defined(HAVE_FENV_H)
    fpe_trap_setup();
#endif

    if (log_audio)
    {
        if ((outhandle = sf_open_telephony_write(OUT_FILE_NAME, 1)) == NULL)
        {
            fprintf(stderr, "    Cannot create audio file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
    }

    if (decode_test_file)
    {
        /* We will decode the audio from a file. */
        tx = NULL;
        if ((inhandle = sf_open_telephony_read(decode_test_file, 1)) == NULL)
        {
            fprintf(stderr, "    Cannot open audio file '%s'\n", decode_test_file);
            exit(2);
        }
    }
    else
    {
        /* We will generate V.27ter audio, and add some noise to it. */
        tx = v27ter_tx_init(NULL, test_bps, tep, v27tergetbit, NULL);
        v27ter_tx_power(tx, signal_level);
        v27ter_tx_set_modem_status_handler(tx, v27ter_tx_status, (void *) tx);
        /* Move the carrier off a bit */
#if defined(WITH_SPANDSP_INTERNALS)
        tx->carrier_phase_rate = dds_phase_ratef(1810.0f);
#endif
        bert_init(&bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
        bert_set_report(&bert, 10000, reporter, NULL);

        if ((line_model = one_way_line_model_init(line_model_no, (float) noise_level, channel_codec, rbs_pattern)) == NULL)
        {
            fprintf(stderr, "    Failed to create line model\n");
            exit(2);
        }
    }

    rx = v27ter_rx_init(NULL, test_bps, v27terputbit, NULL);
    v27ter_rx_set_modem_status_handler(rx, v27ter_rx_status, (void *) rx);
    v27ter_rx_set_qam_report_handler(rx, qam_report, (void *) rx);
    logging = v27ter_rx_get_logging_state(rx);
    span_log_set_level(logging, SPAN_LOG_SHOW_SEVERITY | SPAN_LOG_SHOW_PROTOCOL | SPAN_LOG_FLOW);
    span_log_set_tag(logging, "V.27ter-rx");

#if defined(ENABLE_GUI)
    if (use_gui)
    {
        qam_monitor = qam_monitor_init(2.0f, NULL);
        if (!decode_test_file)
        {
            start_line_model_monitor(129);
            line_model_monitor_line_model_update(line_model->near_filter, line_model->near_filter_len);
        }
    }
#endif

    memset(&latest_results, 0, sizeof(latest_results));
    for (block_no = 0;  ;  block_no++)
    {
        if (decode_test_file)
        {
            samples = sf_readf_short(inhandle, amp, BLOCK_LEN);
#if defined(ENABLE_GUI)
            if (use_gui)
                qam_monitor_update_audio_level(qam_monitor, amp, samples);
#endif
            if (samples == 0)
                break;
        }
        else
        {
            samples = v27ter_tx(tx, gen_amp, BLOCK_LEN);
#if defined(ENABLE_GUI)
            if (use_gui)
                qam_monitor_update_audio_level(qam_monitor, gen_amp, samples);
#endif
            if (samples == 0)
            {
                printf("Restarting on zero output\n");

                /* Push a little silence through, to ensure all the data bits get out of the buffers */
                vec_zeroi16(amp, BLOCK_LEN);
                v27ter_rx(rx, amp, BLOCK_LEN);
                v27ter_rx(rx, amp, BLOCK_LEN);
                v27ter_rx(rx, amp, BLOCK_LEN);

                /* Note that we might get a few bad bits as the carrier shuts down. */
                bert_result(&bert, &bert_results);
                fprintf(stderr, "Final result %ddBm0/%ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, noise_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
                fprintf(stderr, "Last report  %ddBm0/%ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, noise_level, latest_results.total_bits, latest_results.bad_bits, latest_results.resyncs);
                /* See if bit errors are appearing yet. Also check we are getting enough bits out of the receiver. The last regular report
                   should be error free, though the final report will generally contain bits errors as the carrier was dying. The total
                   number of bits out of the receiver should be at least the number we sent. Also, since BERT sync should have occurred
                   rapidly at the start of transmission, the last report should have occurred at not much less than the total number of
                   bits we sent. */
                if (bert_results.total_bits < bits_per_test
                    ||
                    latest_results.total_bits < bits_per_test - 100
                    ||
                    latest_results.bad_bits != 0)
                {
                    break;
                }
                memset(&latest_results, 0, sizeof(latest_results));
                signal_level--;
                v27ter_tx_restart(tx, test_bps, tep);
                v27ter_tx_power(tx, signal_level);
                v27ter_rx_restart(rx, test_bps, FALSE);
                bert_init(&bert, bits_per_test, BERT_PATTERN_ITU_O152_11, test_bps, 20);
                bert_set_report(&bert, 10000, reporter, NULL);
                one_way_line_model_release(line_model);
                if ((line_model = one_way_line_model_init(line_model_no, (float) noise_level, channel_codec, 0)) == NULL)
                {
                    fprintf(stderr, "    Failed to create line model\n");
                    exit(2);
                }
            }

            if (log_audio)
            {
                outframes = sf_writef_short(outhandle, gen_amp, samples);
                if (outframes != samples)
                {
                    fprintf(stderr, "    Error writing audio file\n");
                    exit(2);
                }
            }
            one_way_line_model(line_model, amp, gen_amp, samples);
        }
#if defined(ENABLE_GUI)
        if (use_gui  &&  !decode_test_file)
            line_model_monitor_line_spectrum_update(amp, samples);
#endif
        v27ter_rx(rx, amp, samples);
    }
    if (!decode_test_file)
    {
        bert_result(&bert, &bert_results);
        fprintf(stderr, "At completion:\n");
        fprintf(stderr, "Final result %ddBm0/%ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, noise_level, bert_results.total_bits, bert_results.bad_bits, bert_results.resyncs);
        fprintf(stderr, "Last report  %ddBm0/%ddBm0, %d bits, %d bad bits, %d resyncs\n", signal_level, noise_level, latest_results.total_bits, latest_results.bad_bits, latest_results.resyncs);
        one_way_line_model_release(line_model);
        if (signal_level > -43)
        {
            printf("Tests failed.\n");
            exit(2);
        }

        printf("Tests passed.\n");
    }
#if defined(ENABLE_GUI)
    if (use_gui)
        qam_wait_to_end(qam_monitor);
#endif
    if (decode_test_file)
    {
        if (sf_close(inhandle))
        {
            fprintf(stderr, "    Cannot close audio file '%s'\n", decode_test_file);
            exit(2);
        }
    }
    if (log_audio)
    {
        if (sf_close(outhandle))
        {
            fprintf(stderr, "    Cannot close audio file '%s'\n", OUT_FILE_NAME);
            exit(2);
        }
    }
    return  0;
}
示例#24
0
	/* Collect read stats */
	printf ("    Read  %-5s  from %s : ", "int", subtype) ;
	fflush (stdout) ;

	clock_time = 0 ;
	op_count = 0 ;
	start_clock = clock () ;

	while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION))
	{	if (! (file = sf_open (filename, SFM_READ, &sfinfo)))
		{	printf ("Error : not able to open file : %s\n", filename) ;
			perror ("") ;
			exit (1) ;
			} ;

		for (k = 0 ; k < BLOCK_COUNT ; k++)
		{	if ((retval = sf_read_int (file, int_data, item_count)) != item_count)
			{	printf ("Error : write returned %d (should have been %d)\n", retval, item_count) ;
				exit (1) ;
				} ;
			} ;

		sf_close (file) ;

		clock_time = clock () - start_clock ;
		op_count ++ ;
		} ;

	performance = (1.0 * item_count) * BLOCK_COUNT * op_count ;
	performance *= (1.0 * CLOCKS_PER_SEC) / clock_time  ;
	printf ("%6.2f%% of raw read\n", 100.0 * performance / read_rate) ;

	unlink (filename) ;

} /* calc_int_performance */
static void
calc_float_performance (int format, double read_rate, double write_rate)
{	SNDFILE *file ;
	SF_INFO	sfinfo ;
	clock_t start_clock, clock_time ;
	double	performance ;
	int k, item_count, retval, op_count ;
	const char* subtype ;
	float *float_data ;
	char *filename ;

	filename = "benchmark.dat" ;
	subtype = get_subtype_str (format & SF_FORMAT_SUBMASK) ;

	float_data = data ;
	item_count = BUFFER_SIZE ;
	for (k = 0 ; k < item_count ; k++)
		float_data [k] = 1.0 * sin (2 * M_PI * k / 32000.0) ;

	/* Collect write stats */
	printf ("    Write %-5s   to  %s : ", "float", subtype) ;
	fflush (stdout) ;

	sfinfo.channels = 1 ;
	sfinfo.format = format ;
	sfinfo.frames = 1 ;
	sfinfo.samplerate = 32000 ;

	clock_time = 0 ;
	op_count = 0 ;
	start_clock = clock () ;

	while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION))
	{	if (! (file = sf_open (filename, SFM_WRITE, &sfinfo)))
		{	printf ("Error : not able to open file : %s\n", filename) ;
			perror ("") ;
			exit (1) ;
			} ;

		/* Turn off the addition of a PEAK chunk. */
		sf_command (file, SFC_SET_ADD_PEAK_CHUNK, NULL, SF_FALSE) ;

		for (k = 0 ; k < BLOCK_COUNT ; k++)
		{	if ((retval = sf_write_float (file, float_data, item_count)) != item_count)
			{	printf ("Error : sf_write_short returned %d (should have been %d)\n", retval, item_count) ;
				exit (1) ;
				} ;
			} ;

		sf_close (file) ;

		clock_time = clock () - start_clock ;
		op_count ++ ;
		} ;

	performance = (1.0 * BUFFER_SIZE) * BLOCK_COUNT * op_count ;
	performance *= (1.0 * CLOCKS_PER_SEC) / clock_time  ;
	printf ("%6.2f%% of raw write\n", 100.0 * performance / write_rate) ;

	/* Collect read stats */
	printf ("    Read  %-5s  from %s : ", "float", subtype) ;
	fflush (stdout) ;

	clock_time = 0 ;
	op_count = 0 ;
	start_clock = clock () ;

	while (clock_time < (CLOCKS_PER_SEC * TEST_DURATION))
	{	if (! (file = sf_open (filename, SFM_READ, &sfinfo)))
		{	printf ("Error : not able to open file : %s\n", filename) ;
			perror ("") ;
			exit (1) ;
			} ;

		for (k = 0 ; k < BLOCK_COUNT ; k++)
		{	if ((retval = sf_read_float (file, float_data, item_count)) != item_count)
			{	printf ("Error : write returned %d (should have been %d)\n", retval, item_count) ;
				exit (1) ;
				} ;
			} ;

		sf_close (file) ;

		clock_time = clock () - start_clock ;
		op_count ++ ;
		} ;

	performance = (1.0 * item_count) * BLOCK_COUNT * op_count ;
	performance *= (1.0 * CLOCKS_PER_SEC) / clock_time  ;
	printf ("%6.2f%% of raw read\n", 100.0 * performance / read_rate) ;

	unlink (filename) ;

} /* calc_float_performance */
int main(int argc, char **argv)
{
    size_t frameCount = 256;
    size_t maxFramesPerRead = 1;
    size_t maxFramesPerWrite = 1;
    int i;
    for (i = 1; i < argc; i++) {
        char *arg = argv[i];
        if (arg[0] != '-')
            break;
        switch (arg[1]) {
        case 'c':   // FIFO frame count
            frameCount = atoi(&arg[2]);
            break;
        case 'r':   // maximum frame count per read from FIFO
            maxFramesPerRead = atoi(&arg[2]);
            break;
        case 'w':   // maximum frame count per write to FIFO
            maxFramesPerWrite = atoi(&arg[2]);
            break;
        default:
            fprintf(stderr, "%s: unknown option %s\n", argv[0], arg);
            goto usage;
        }
    }

    if (argc - i != 2) {
usage:
        fprintf(stderr, "usage: %s [-c#] in.wav out.wav\n", argv[0]);
        return EXIT_FAILURE;
    }
    char *inputFile = argv[i];
    char *outputFile = argv[i+1];

    SF_INFO sfinfoin;
    memset(&sfinfoin, 0, sizeof(sfinfoin));
    SNDFILE *sfin = sf_open(inputFile, SFM_READ, &sfinfoin);
    if (sfin == NULL) {
        perror(inputFile);
        return EXIT_FAILURE;
    }
    // sf_readf_short() does conversion, so not strictly necessary to check the file format.
    // But I want to do "cmp" on input and output files afterwards,
    // and it is easier if they are all the same format.
    // Enforcing that everything is 16-bit is convenient for this.
    if ((sfinfoin.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_SUBMASK)) !=
            (SF_FORMAT_WAV | SF_FORMAT_PCM_16)) {
        fprintf(stderr, "%s: unsupported format\n", inputFile);
        sf_close(sfin);
        return EXIT_FAILURE;
    }
    size_t frameSize = sizeof(short) * sfinfoin.channels;
    short *inputBuffer = new short[sfinfoin.frames * sfinfoin.channels];
    sf_count_t actualRead = sf_readf_short(sfin, inputBuffer, sfinfoin.frames);
    if (actualRead != sfinfoin.frames) {
        fprintf(stderr, "%s: unexpected EOF or error\n", inputFile);
        sf_close(sfin);
        return EXIT_FAILURE;
    }
    sf_close(sfin);

    short *outputBuffer = new short[sfinfoin.frames * sfinfoin.channels];
    size_t framesWritten = 0;
    size_t framesRead = 0;
    struct audio_utils_fifo fifo;
    short *fifoBuffer = new short[frameCount * sfinfoin.channels];
    audio_utils_fifo_init(&fifo, frameCount, frameSize, fifoBuffer);
    int fifoWriteCount = 0, fifoReadCount = 0;
    int fifoFillLevel = 0, minFillLevel = INT_MAX, maxFillLevel = INT_MIN;
    for (;;) {
        size_t framesToWrite = sfinfoin.frames - framesWritten;
        size_t framesToRead = sfinfoin.frames - framesRead;
        if (framesToWrite == 0 && framesToRead == 0) {
            break;
        }

        if (framesToWrite > maxFramesPerWrite) {
            framesToWrite = maxFramesPerWrite;
        }
        framesToWrite = rand() % (framesToWrite + 1);
        ssize_t actualWritten = audio_utils_fifo_write(&fifo,
                &inputBuffer[framesWritten * sfinfoin.channels], framesToWrite);
        if (actualWritten < 0 || (size_t) actualWritten > framesToWrite) {
            fprintf(stderr, "write to FIFO failed\n");
            break;
        }
        framesWritten += actualWritten;
        if (actualWritten > 0) {
            fifoWriteCount++;
        }
        fifoFillLevel += actualWritten;
        if (fifoFillLevel > maxFillLevel) {
            maxFillLevel = fifoFillLevel;
            if (maxFillLevel > (int) frameCount)
                abort();
        }

        if (framesToRead > maxFramesPerRead) {
            framesToRead = maxFramesPerRead;
        }
        framesToRead = rand() % (framesToRead + 1);
        ssize_t actualRead = audio_utils_fifo_read(&fifo,
                &outputBuffer[framesRead * sfinfoin.channels], framesToRead);
        if (actualRead < 0 || (size_t) actualRead > framesToRead) {
            fprintf(stderr, "read from FIFO failed\n");
            break;
        }
        framesRead += actualRead;
        if (actualRead > 0) {
            fifoReadCount++;
        }
        fifoFillLevel -= actualRead;
        if (fifoFillLevel < minFillLevel) {
            minFillLevel = fifoFillLevel;
            if (minFillLevel < 0)
                abort();
        }
    }
    printf("FIFO non-empty writes: %d, non-empty reads: %d\n", fifoWriteCount, fifoReadCount);
    printf("fill=%d, min=%d, max=%d\n", fifoFillLevel, minFillLevel, maxFillLevel);
    audio_utils_fifo_deinit(&fifo);
    delete[] fifoBuffer;

    SF_INFO sfinfoout;
    memset(&sfinfoout, 0, sizeof(sfinfoout));
    sfinfoout.samplerate = sfinfoin.samplerate;
    sfinfoout.channels = sfinfoin.channels;
    sfinfoout.format = sfinfoin.format;
    SNDFILE *sfout = sf_open(outputFile, SFM_WRITE, &sfinfoout);
    if (sfout == NULL) {
        perror(outputFile);
        return EXIT_FAILURE;
    }
    sf_count_t actualWritten = sf_writef_short(sfout, outputBuffer, framesRead);
    delete[] inputBuffer;
    delete[] outputBuffer;
    delete[] fifoBuffer;
    if (actualWritten != (sf_count_t) framesRead) {
        fprintf(stderr, "%s: unexpected error\n", outputFile);
        sf_close(sfout);
        return EXIT_FAILURE;
    }
    sf_close(sfout);
    return EXIT_SUCCESS;
}
示例#26
0
static void
channel_test (void)
{	static float	float_data [1024] ;
	static float	read_float [1024] ;
	static int		read_int [1024] ;
	static short	read_short [1024] ;
	unsigned int	ch, k, position = 0 ;

	gen_windowed_sine_float (float_data, ARRAY_LEN (float_data), 0.9) ;

	for (ch = 1 ; ch <= 8 ; ch++)
	{	SNDFILE	*file ;
		SF_INFO	wsfinfo, rsfinfo ;
		sf_count_t wframes = ARRAY_LEN (float_data) / ch ;
		double	maxdiff ;
		char	filename [256] ;

		snprintf (filename, sizeof (filename), "chan_%d.wav", ch) ;
		print_test_name (__func__, filename) ;

		sf_info_setup (&wsfinfo, SF_FORMAT_WAV | SF_FORMAT_FLOAT, 48000, ch) ;
		sf_info_clear (&rsfinfo) ;

		/* Write the test file. */
		file = test_open_file_or_die (filename, SFM_WRITE, &wsfinfo, SF_FALSE, __LINE__) ;
		test_writef_float_or_die (file, 0, float_data, wframes, __LINE__) ;
		sf_close (file) ;

		/* Read it as float and test. */
		file = test_open_file_or_die (filename, SFM_READ, &rsfinfo, SF_FALSE, __LINE__) ;
		exit_if_true (rsfinfo.frames == 0,
				"\n\nLine %d : Frames in file %" PRId64 ".\n\n", __LINE__, rsfinfo.frames) ;
		exit_if_true (wframes != rsfinfo.frames,
				"\n\nLine %d : Wrote %" PRId64 ", read %" PRId64 " frames.\n\n", __LINE__, wframes, rsfinfo.frames) ;

		sf_command (file, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE) ;

		test_readf_float_or_die (file, 0, read_float, rsfinfo.frames, __LINE__) ;
		compare_float_or_die (float_data, read_float, ch * rsfinfo.frames, __LINE__) ;

		/* Read it as short and test. */
		test_seek_or_die (file, 0, SEEK_SET, 0, ch, __LINE__) ;
		test_readf_short_or_die (file, 0, read_short, rsfinfo.frames, __LINE__) ;

		for (k = 0 ; k < ARRAY_LEN (read_float) ; k++)
			read_float [k] = read_short [k] * (0.9 / 0x8000) ;

		maxdiff = max_diff (float_data, read_float, ch * rsfinfo.frames, &position) ;
		exit_if_true (maxdiff > 0.5, "\n\nLine %d : Max diff is %f at index %u\n\n", __LINE__, maxdiff, position) ;

		/* Read it as int and test. */
		test_seek_or_die (file, 0, SEEK_SET, 0, ch, __LINE__) ;
		test_readf_int_or_die (file, 0, read_int, rsfinfo.frames, __LINE__) ;

		for (k = 0 ; k < ARRAY_LEN (read_float) ; k++)
			read_float [k] = read_int [k] * (0.9 / 0x80000000) ;

		maxdiff = max_diff (float_data, read_float, ch * rsfinfo.frames, &position) ;
		exit_if_true (maxdiff > 0.5, "\n\nLine %d : Max diff is %f at index %u\n\n", __LINE__, maxdiff, position) ;

		sf_close (file) ;
		unlink (filename) ;
		printf ("ok\n") ;
		} ;

	return ;
} /* channel_test */
示例#27
0
SndFileReader::~SndFileReader()
{
	sf_close(m_sndfile);
}
示例#28
0
/// Reads the specified data from the aliased file, using libsndfile,
/// and converts it to the given sample format.
///
/// @param data   The buffer to read the sample data into.
/// @param format The format to convert the data into
/// @param start  The offset within the block to begin reading
/// @param len    The number of samples to read
int PCMAliasBlockFile::ReadData(samplePtr data, sampleFormat format,
                                sampleCount start, sampleCount len)
{
    SF_INFO info;

    if(!mAliasedFileName.IsOk()) { // intentionally silenced
        memset(data,0,SAMPLE_SIZE(format)*len);
        return len;
    }

    wxLogNull *silence=0;
    if(mSilentAliasLog)silence= new wxLogNull();

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

    wxFile f;   // will be closed when it goes out of scope
    SNDFILE *sf = NULL;

    if (f.Exists(mAliasedFileName.GetFullPath())) { // Don't use Open if file does not exits
        if (f.Open(mAliasedFileName.GetFullPath())) {
            // Even though there is an sf_open() that takes a filename, use the one that
            // takes a file descriptor since wxWidgets can open a file with a Unicode name and
            // libsndfile can't (under Windows).
            ODManager::LockLibSndFileMutex();
            sf = sf_open_fd(f.fd(), SFM_READ, &info, FALSE);
            ODManager::UnlockLibSndFileMutex();
        }
    }

    if (!sf) {
        memset(data,0,SAMPLE_SIZE(format)*len);
        if(silence) delete silence;
        mSilentAliasLog=TRUE;

        // Set a marker to display an error message for the silence
        if (!wxGetApp().ShouldShowMissingAliasedFileWarning())
            wxGetApp().MarkAliasedFilesMissingWarning(this);
        return len;
    }

    if(silence) delete silence;
    mSilentAliasLog=FALSE;

    ODManager::LockLibSndFileMutex();
    sf_seek(sf, mAliasStart + start, SEEK_SET);
    ODManager::UnlockLibSndFileMutex();
    samplePtr buffer = NewSamples(len * info.channels, floatSample);

    int framesRead = 0;

    if (format == int16Sample &&
            !sf_subtype_more_than_16_bits(info.format)) {
        // Special case: if the file is in 16-bit (or less) format,
        // and the calling method wants 16-bit data, go ahead and
        // read 16-bit data directly.  This is a pretty common
        // case, as most audio files are 16-bit.
        ODManager::LockLibSndFileMutex();
        framesRead = sf_readf_short(sf, (short *)buffer, len);
        ODManager::UnlockLibSndFileMutex();
        for (int i = 0; i < framesRead; i++)
            ((short *)data)[i] =
                ((short *)buffer)[(info.channels * i) + mAliasChannel];
    }
    else {
        // Otherwise, let libsndfile handle the conversion and
        // scaling, and pass us normalized data as floats.  We can
        // then convert to whatever format we want.
        ODManager::LockLibSndFileMutex();
        framesRead = sf_readf_float(sf, (float *)buffer, len);
        ODManager::UnlockLibSndFileMutex();
        float *bufferPtr = &((float *)buffer)[mAliasChannel];
        CopySamples((samplePtr)bufferPtr, floatSample,
                    (samplePtr)data, format,
                    framesRead, true, info.channels);
    }

    DeleteSamples(buffer);
    ODManager::LockLibSndFileMutex();
    sf_close(sf);
    ODManager::UnlockLibSndFileMutex();
    return framesRead;
}
示例#29
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;
}