Esempio n. 1
0
static void 
encode_file (char *infilename, char *outfilename, int filetype)
{	static float buffer [BUFFER_LEN] ;
	
	SNDFILE		*infile, *outfile ;
	SF_INFO		sfinfo ;
	int			k, readcount ;
	
	printf ("    %s -> %s ", infilename, outfilename) ;
	fflush (stdout) ;

	k = 16 - strlen (outfilename) ;
	PUT_DOTS (k) ;

	if (! (infile = sf_open (infilename, SFM_READ, &sfinfo)))
	{	printf ("Error : could not open file : %s\n", infilename) ;
		puts (sf_strerror (NULL)) ;
		exit (1) ;
		}

	sfinfo.format = filetype ;
	
	if (! sf_format_check (&sfinfo))
	{	sf_close (infile) ;
		printf ("Invalid encoding\n") ;
		return ;
		} ;
		
	if (! (outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)))
	{	printf ("Error : could not open file : %s\n", outfilename) ;
		puts (sf_strerror (NULL)) ;
		exit (1) ;
		} ;
		
	while ((readcount = sf_read_float (infile, buffer, BUFFER_LEN)) > 0)
		sf_write_float (outfile, buffer, BUFFER_LEN) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	printf ("ok\n") ;

	return ;			
} /* encode_file */
Esempio n. 2
0
int
main (void)
{	SF_FORMAT_INFO	info ;
	SF_INFO 		sfinfo ;
	char buffer [128] ;
	int format, major_count, subtype_count, m, s ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	buffer [0] = 0 ;
	sf_command (NULL, SFC_GET_LIB_VERSION, buffer, sizeof (buffer)) ;
	if (strlen (buffer) < 1)
	{	printf ("Line %d: could not retrieve lib version.\n", __LINE__) ;
		exit (1) ;
		} ;
	printf ("Version : %s\n\n", buffer) ;

	sf_command (NULL, SFC_GET_FORMAT_MAJOR_COUNT, &major_count, sizeof (int)) ;
	sf_command (NULL, SFC_GET_FORMAT_SUBTYPE_COUNT, &subtype_count, sizeof (int)) ;

	sfinfo.channels = 1 ;
	for (m = 0 ; m < major_count ; m++)
	{	info.format = m ;
		sf_command (NULL, SFC_GET_FORMAT_MAJOR, &info, sizeof (info)) ;
		printf ("%s  (extension \"%s\")\n", info.name, info.extension) ;

		format = info.format ;

		for (s = 0 ; s < subtype_count ; s++)
		{	info.format = s ;
			sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &info, sizeof (info)) ;

			format = (format & SF_FORMAT_TYPEMASK) | info.format ;

			sfinfo.format = format ;
			if (sf_format_check (&sfinfo))
				printf ("   %s\n", info.name) ;
			} ;
		puts ("") ;
		} ;
	puts ("") ;

	return 0 ;
} /* main */
Esempio n. 3
0
gboolean
ags_sndfile_rw_open(AgsPlayable *playable, gchar *name,
		    gboolean create)
{
  AgsSndfile *sndfile;
  sf_count_t multi_frames;
  
  sndfile = AGS_SNDFILE(playable);

  sndfile->info->frames = 0;
  sndfile->info->seekable = 0;
  sndfile->info->sections = 0;

  g_message("export to: %s\n  samplerate: %d\n  channels: %d\n  format: %x\0",
	    name,
	    sndfile->info->samplerate,
	    sndfile->info->channels,
	    sndfile->info->format);

  if(!sf_format_check(sndfile->info)){
    g_warning("invalid format");
  }

  if((AGS_SNDFILE_VIRTUAL & (sndfile->flags)) == 0){
    if(name != NULL){
      sndfile->file = (SNDFILE *) sf_open(name, SFM_RDWR, sndfile->info);
    }
  }else{
    sndfile->file = (SNDFILE *) sf_open_virtual(ags_sndfile_virtual_io, SFM_RDWR, sndfile->info, sndfile);
  }

  multi_frames = sndfile->info->frames * sndfile->info->channels;
  //  sf_command(sndfile->file, SFC_FILE_TRUNCATE, &(multi_frames), sizeof(multi_frames));
  //  sf_command (sndfile, SFC_SET_SCALE_INT_FLOAT_WRITE, NULL, SF_TRUE);
  //  sf_seek(sndfile->file, 0, SEEK_SET);

  //  sndfile->info->frames = multi_frames;

  if(sndfile->file == NULL)
    return(FALSE);
  else
    return(TRUE);
}
Esempio n. 4
0
RTC::ReturnCode_t WavRecord::onActivated(RTC::UniqueId ec_id)
{
  RTC_DEBUG(("onActivated start"));
  RTC_INFO(("Wave File Name: %s\n", WaveFileName));
  sfinfo.samplerate = m_rate;
  sfinfo.channels = m_channels;
  sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
  if (sf_format_check(&sfinfo) == 0) {
    RTC_DEBUG(("invalid format"));
    return RTC::RTC_ERROR;
  }
  sfw = sf_open(WaveFileName, SFM_WRITE, &sfinfo);
  if (sfw == NULL) {
    RTC_DEBUG(("unable to open file: %s", WaveFileName));
    return RTC::RTC_ERROR;
  }
  is_active = true;
  RTC_DEBUG(("onActivated finish"));
  return RTC::RTC_OK;
}
Esempio n. 5
0
int
main (void)
{	SF_FORMAT_INFO	info ;
	SF_INFO 		sfinfo ;
	int format, major_count, subtype_count, m, s ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	printf ("Version : %s\n\n", sf_version_string ()) ;

	sf_command (NULL, SFC_GET_FORMAT_MAJOR_COUNT, &major_count, sizeof (int)) ;
	sf_command (NULL, SFC_GET_FORMAT_SUBTYPE_COUNT, &subtype_count, sizeof (int)) ;

	sfinfo.channels = 1 ;
	for (m = 0 ; m < major_count ; m++)
	{	info.format = m ;
		sf_command (NULL, SFC_GET_FORMAT_MAJOR, &info, sizeof (info)) ;
		printf ("%s  (extension \"%s\")\n", info.name, info.extension) ;

		format = info.format ;

		for (s = 0 ; s < subtype_count ; s++)
		{	info.format = s ;
			sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &info, sizeof (info)) ;

			format = (format & SF_FORMAT_TYPEMASK) | info.format ;

			sfinfo.format = format ;
			if (sf_format_check (&sfinfo))
				printf ("   %s\n", info.name) ;
			} ;
		puts ("") ;
		} ;
	puts ("") ;

	return 0 ;
} /* main */
Esempio n. 6
0
OGGFileAudioSink::OGGFileAudioSink(const std::string& filename, int out_count) : _count(out_count)
{
	_sfinfo.samplerate = 8000;
	_sfinfo.channels = 1;
//	_sfinfo.format = SF_FORMAT_AU | SF_FORMAT_FLOAT;
	_sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;
//	_sfinfo.frames = 0x7FFFFFFF;
	int valid_format = sf_format_check(&_sfinfo);
	if(!valid_format)
		std::cerr << "invalid format" << std::endl;
	if(filename == "stdout")
	{
	 	_f = sf_open_fd(1, SFM_WRITE, &_sfinfo, false);

	}
	else
	{
	 	_f = sf_open(filename.c_str(), SFM_WRITE, &_sfinfo);
	}
	if(!_f)
	{
		std::cerr << "sf_open failed" << std::cerr;
	}
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])

{

	//--------------------------------------------
	// VARIABLES
	//--------------------------------------------

	//--
	// samples and rate
	//--
	
	// NOTE: this includes the samples array pointer, number of channels and samples, and rate
	
	void *X; 
	
	int n, ch, r, e;
	
	//--
	// output file name
	//--
	
	char *f;
	
	int len;
	
	//--
	// format and encoding
	//--
	
	int fmt_code, enc_code;
	
	//--
	// libsndfile structures
	//--
		
	SNDFILE *out_file;

	SF_INFO out_info;
	
	
	mxClassID cls;

	//--------------------------------------------
	// INPUT
	//--------------------------------------------

	// TODO: add some check on the number of channels and samples
	
	//--------------------------------
	// samples and rate
	//--------------------------------

	X = mxGetPr(prhs[0]);
	
	cls = mxGetClassID(prhs[0]);

	n = mxGetN(prhs[0]);
	
	ch = mxGetM(prhs[0]); 

	r = (int) mxGetScalar(prhs[1]);

	//--------------------------------
	// output file
	//--------------------------------

	len = mxGetM(prhs[2]) * mxGetN(prhs[2]) + 1;

	f = mxCalloc(len, sizeof(char));

	mxGetString(prhs[2], f, len);
	
	//--------------------------------
	// format and encoding
	//--------------------------------
	
	// NOTE: although we could extract the format from the file name it it easier in MATLAB
	
	fmt_code = (int) mxGetScalar(prhs[3]);
	
	enc_code = (int) mxGetScalar(prhs[4]);
	
	//--------------------------------------------
	// COMPUTATION
	//--------------------------------------------

	//--------------------------------
	// fill info structure
	//--------------------------------
	
	out_info.frames = n;
	
	out_info.channels = ch;
			
	out_info.samplerate = r;
	
	out_info.sections = 1;
	
	out_info.seekable = 1;
	
	// NOTE: look at 'sndfile.h' for the meanings of these
	
	switch (fmt_code) {
		
		case 0:
			fmt_code = SF_FORMAT_WAV; break;
					
		case 1:
			fmt_code = SF_FORMAT_AIFF; break;
			
		case 2:
			fmt_code = SF_FORMAT_AU; break;
			
		case 3:
			fmt_code = SF_FORMAT_W64; break;
			
		case 4:
			fmt_code = SF_FORMAT_FLAC; break;
			
		default:
			mexErrMsgTxt("Unsupported major file format.");

	}
	
	// NOTE: look at 'sndfile.h' for the meanings of these
	
	switch (enc_code) {
		
		case 0:
			if (fmt_code == SF_FORMAT_AU) {
				mexErrMsgTxt("Unsupported encoding for major file format.");
			}
			enc_code = SF_FORMAT_PCM_U8; break;

		case 1:
			if ((fmt_code == SF_FORMAT_WAV) || (fmt_code == SF_FORMAT_WAV)) {
				mexErrMsgTxt("Unsupported encoding for major file format.");
			}
			enc_code = SF_FORMAT_PCM_S8; break;
			
		case 2:
			enc_code = SF_FORMAT_PCM_16; break;
			
		case 3:
			enc_code = SF_FORMAT_PCM_24; break;
			
		case 4:
			enc_code = SF_FORMAT_PCM_32; break;
			
		case 5:
			enc_code = SF_FORMAT_FLOAT; break;
			
		case 6:
			enc_code = SF_FORMAT_DOUBLE; break;
			
		case 7:
			enc_code = SF_FORMAT_ULAW; break;
			
		case 8:
			enc_code = SF_FORMAT_ALAW; break;
			
		case 9:
			if ((fmt_code == SF_FORMAT_AIFF) || (fmt_code == SF_FORMAT_AU)) {
				mexErrMsgTxt("Unsupported encoding for major file format.");
			}
			enc_code = SF_FORMAT_IMA_ADPCM; break;

		case 10:
			if ((fmt_code == SF_FORMAT_AIFF) || (fmt_code == SF_FORMAT_AU)) {
				mexErrMsgTxt("Unsupported encoding for major file format.");
			}
			enc_code = SF_FORMAT_MS_ADPCM; break;
			
		case 11:
			if (fmt_code == SF_FORMAT_AU) {
				mexErrMsgTxt("Unsupported encoding for major file format.");
			}
			enc_code = SF_FORMAT_GSM610; 
			break;
			
		default:
			mexErrMsgTxt("Unsupported encoding.");
			
	}
	
	out_info.format = fmt_code | enc_code;
	
	if (!sf_format_check(&out_info)) mexErrMsgTxt("failed format check.");
	
	//--------------------------------
	// create output file
	//--------------------------------
	
	//--
	// open output file (create if needed)
	//--
	
	out_file = sf_open (f, SFM_WRITE, &out_info);
	
	if (out_file == NULL) {
		
		// grab log buffer (very informative about errors)
		
		char  buffer [2048] ;
        sf_command (out_file, SFC_GET_LOG_INFO, buffer, sizeof (buffer)) ;		
		mexPrintf("%s\n", buffer);
			
		// there must be an error, display it, and break.
		
		mexErrMsgTxt(sf_error_number(sf_error(out_file))) ;
		
	}
		
	//--
	// write samples to output file
	//--
	
	// NOTE: set normalization to true, this assumes samples are in the -1 to 1 range
	
	switch (cls){
		
		case (mxDOUBLE_CLASS):
	
			sf_command (out_file, SFC_SET_NORM_DOUBLE, NULL, SF_TRUE);
	
			sf_writef_double (out_file, (double *) X, n);
			
			break;
			
		case (mxSINGLE_CLASS):
			
			sf_command (out_file, SFC_SET_NORM_FLOAT, NULL, SF_TRUE);
	
			sf_writef_float (out_file, (float *) X, n);
			
			break;
			
		default:
			
			mexErrMsgTxt("Unsupported class.\n");
			
	}

	
	//--
	// close file
	//--

	sf_close (out_file);

}
Esempio n. 8
0
static void
update_seek_double_test	(const char *filename, int filetype)
{	SNDFILE *outfile, *infile ;
	SF_INFO sfinfo ;
    sf_count_t frames ;
    double buffer [8] ;
	int k ;

	print_test_name ("update_seek_double_test", filename) ;

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

	/* Create sound outfile with no data. */
	sfinfo.format = filetype | SF_FORMAT_DOUBLE ;
	sfinfo.samplerate = 48000 ;
	sfinfo.channels = 2 ;

	if (sf_format_check (&sfinfo) == SF_FALSE)
		sfinfo.channels = 1 ;

	outfile = test_open_file_or_die (filename, SFM_WRITE, &sfinfo, SF_TRUE, __LINE__) ;
	sf_close (outfile) ;

	/* Open again for read/write. */
	outfile = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, SF_TRUE, __LINE__) ;

	/*
	** In auto header update mode, seeking to the end of the file with
    ** SEEK_SET will fail from the 2nd seek on.  seeking to 0, SEEK_END
	** will seek to 0 anyway
	*/
	if (sf_command (outfile, SFC_SET_UPDATE_HEADER_AUTO, NULL, SF_TRUE) == 0)
    {	printf ("\n\nError : sf_command (SFC_SET_UPDATE_HEADER_AUTO) return error : %s\n\n", sf_strerror (outfile)) ;
		exit (1) ;
		} ;

	/* Now write some frames. */
	frames = ARRAY_LEN (buffer) / sfinfo.channels ;

	for (k = 0 ; k < 6 ; k++)
	{	test_seek_or_die (outfile, k * frames, SEEK_SET, k * frames, sfinfo.channels, __LINE__) ;
		test_seek_or_die (outfile, 0, SEEK_END, k * frames, sfinfo.channels, __LINE__) ;

		/* Open file again and make sure no errors in log buffer. */
		infile = test_open_file_or_die (filename, SFM_READ, &sfinfo, SF_TRUE, __LINE__) ;
		check_log_buffer_or_die (infile, __LINE__) ;
		sf_close (infile) ;

		if (sfinfo.frames != k * frames)
		{	printf ("\n\nLine %d : Incorrect sample count (%ld should be %ld)\n", __LINE__, SF_COUNT_TO_LONG (sfinfo.frames), SF_COUNT_TO_LONG (k + frames)) ;
			dump_log_buffer (infile) ;
			exit (1) ;
			} ;

		if ((k & 1) == 0)
			test_write_double_or_die (outfile, k, buffer, sfinfo.channels * frames, __LINE__) ;
		else
			test_writef_double_or_die (outfile, k, buffer, frames, __LINE__) ;
		} ;

	sf_close (outfile) ;
	unlink (filename) ;

	puts ("ok") ;
	return ;
} /* update_seek_double_test */
Esempio n. 9
0
static	void
format_tests	(void)
{	SF_FORMAT_INFO format_info ;
	SF_INFO		sfinfo ;
	const char	*last_name ;
	int 		k, count ;

	print_test_name ("format_tests", "(null)") ;

	/* Clear out SF_INFO struct and set channels > 0. */
	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	sfinfo.channels = 1 ;

	/* First test simple formats. */

	sf_command (NULL, SFC_GET_SIMPLE_FORMAT_COUNT, &count, sizeof (int)) ;

	if (count < 0 || count > 30)
	{	printf ("Line %d: Weird count.\n", __LINE__) ;
		exit (1) ;
		} ;

	format_info.format = 0 ;
	sf_command (NULL, SFC_GET_SIMPLE_FORMAT, &format_info, sizeof (format_info)) ;

	last_name = format_info.name ;
	for (k = 1 ; k < count ; k ++)
	{	format_info.format = k ;
		sf_command (NULL, SFC_GET_SIMPLE_FORMAT, &format_info, sizeof (format_info)) ;
		if (strcmp (last_name, format_info.name) >= 0)
		{	printf ("\n\nLine %d: format names out of sequence `%s' < `%s'.\n", __LINE__, last_name, format_info.name) ;
			exit (1) ;
			} ;
		sfinfo.format = format_info.format ;

		if (! sf_format_check (&sfinfo))
		{	printf ("\n\nLine %d: sf_format_check failed.\n", __LINE__) ;
			printf ("        Name : %s\n", format_info.name) ;
			printf ("        Format      : 0x%X\n", sfinfo.format) ;
			printf ("        Channels    : 0x%X\n", sfinfo.channels) ;
			printf ("        Sample Rate : 0x%X\n", sfinfo.samplerate) ;
			exit (1) ;
			} ;
		last_name = format_info.name ;
		} ;
	format_info.format = 666 ;
	sf_command (NULL, SFC_GET_SIMPLE_FORMAT, &format_info, sizeof (format_info)) ;

	/* Now test major formats. */
	sf_command (NULL, SFC_GET_FORMAT_MAJOR_COUNT, &count, sizeof (int)) ;

	if (count < 0 || count > 30)
	{	printf ("Line %d: Weird count.\n", __LINE__) ;
		exit (1) ;
		} ;

	format_info.format = 0 ;
	sf_command (NULL, SFC_GET_FORMAT_MAJOR, &format_info, sizeof (format_info)) ;

	last_name = format_info.name ;
	for (k = 1 ; k < count ; k ++)
	{	format_info.format = k ;
		sf_command (NULL, SFC_GET_FORMAT_MAJOR, &format_info, sizeof (format_info)) ;
		if (strcmp (last_name, format_info.name) >= 0)
		{	printf ("\n\nLine %d: format names out of sequence (%d) `%s' < `%s'.\n", __LINE__, k, last_name, format_info.name) ;
			exit (1) ;
			} ;

		last_name = format_info.name ;
		} ;
	format_info.format = 666 ;
	sf_command (NULL, SFC_GET_FORMAT_MAJOR, &format_info, sizeof (format_info)) ;

	/* Now test subtype formats. */
	sf_command (NULL, SFC_GET_FORMAT_SUBTYPE_COUNT, &count, sizeof (int)) ;

	if (count < 0 || count > 30)
	{	printf ("Line %d: Weird count.\n", __LINE__) ;
		exit (1) ;
		} ;

	format_info.format = 0 ;
	sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &format_info, sizeof (format_info)) ;

	last_name = format_info.name ;
	for (k = 1 ; k < count ; k ++)
	{	format_info.format = k ;
		sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &format_info, sizeof (format_info)) ;
		} ;
	format_info.format = 666 ;
	sf_command (NULL, SFC_GET_FORMAT_SUBTYPE, &format_info, sizeof (format_info)) ;


	printf ("ok\n") ;
} /* format_tests */
Esempio n. 10
0
void export_cue_libsndfile(struct cue *cue, const char *cwd) {

    SNDFILE *source, *dest;
    SF_INFO srcinfo, dstinfo;
    char trackno_str[4], *dest_name, *src_path;
    uint64_t nframes;
    int64_t cnt;
    unsigned i;
    short *frames;


    asprintf(&src_path, "%s/%s", cwd, cue->filename);
    printf("Now exporting \"%s\".\n", src_path);
    source = sf_open(src_path, SFM_READ, &srcinfo);
    free(src_path);
    if(srcinfo.format & SF_FORMAT_SUBMASK != SF_FORMAT_PCM_16) {
        fprintf(stderr, "Not 16-bit format. Sorry.\n");
        sf_close(source);
        return;
    }
    memcpy(&dstinfo, &srcinfo, sizeof(SF_INFO));
    /*
    dstinfo.format = SF_FORMAT_OGG 
                   | SF_FORMAT_VORBIS 
                   | (srcinfo.format & SF_FORMAT_ENDMASK);
    */
    dstinfo.format = SF_FORMAT_AIFF 
                   | SF_FORMAT_PCM_16
                   | SF_ENDIAN_BIG;
 
    if(!sf_format_check(&dstinfo)) {
        fprintf(stderr, "Output file format is invalid :"
                " sf_format_check() returned FALSE.\n");
        sf_close(source);
        return;
    }

    unsigned blksiz;
    for(blksiz = 1<<16 ; ; blksiz>>=1) {
        frames = malloc(sizeof(short)*dstinfo.channels*blksiz);
        if(frames) break; /* Don't put in condition. It's a do...while. */
    }

    for(i=0 ; i<cue->numtracks ; ++i) {
        asprintf(&dest_name, "%s/%u - %s.aiff", 
                cwd, cue->tracks[i].trackno, 
                strchr(cue->tracks[i].title, ':') ? "__Illegal_Title__" 
                                                 : cue->tracks[i].title);
        dest = sf_open(dest_name, SFM_WRITE, &dstinfo);
        sf_set_string(dest, SF_STR_TITLE, cue->tracks[i].title);
        sf_set_string(dest, SF_STR_ARTIST, cue->tracks[i].performer);
        sf_set_string(dest, SF_STR_ALBUM, cue->title);
        sprintf(trackno_str, "%u", cue->tracks[i].trackno);
        sf_set_string(dest, SF_STR_TRACKNUMBER, trackno_str);
        /* stuff */
        nframes = srcinfo.samplerate*cue->tracks[i].index_ms/1000;
        sf_seek(source, nframes, SEEK_SET);
        if(i==cue->numtracks-1) {
            for(;;) {
                clear_console_screen();
                printf("Converting track %u/%u :\n"
                        "to %s\n"
                        "(reading to end of file)\n"
                        "From \"%s\"", 
                        i+1, cue->numtracks, dest_name, cue->filename);
                cnt = sf_readf_short(source, frames, blksiz);
                if(cnt <= 0)
                    break;
                sf_writef_short(dest, frames, cnt);
            }
        } else {
            nframes = (srcinfo.samplerate*cue->tracks[i+1].index_ms/1000)
                -nframes-srcinfo.samplerate*2;
            for(cnt=0 ; cnt<nframes ; cnt += blksiz) {
                clear_console_screen();
                printf("Converting track %u/%u :\n"
                        "to %s\n"
                        "(%lf%%)\n"
                        "From \"%s\"", 
                        i+1, cue->numtracks, dest_name,
                        100.0*(double)cnt/(double)nframes, cue->filename);
                sf_readf_short(source, frames, blksiz);
                sf_writef_short(dest, frames, blksiz);
            }
            cnt -= blksiz;
            sf_readf_short(source, frames, nframes-cnt);
            sf_writef_short(dest, frames, nframes-cnt);
        }
        sf_close(dest);
        free(dest_name);
    }
    puts("Done. Now cleaning up.");
    sf_close(source);
    free(frames);
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
	int ret;
	char* file_name = NULL;
	char* dev = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program comp_filter_exp;		/* The compiled filter expression */
	char filter_exp[] = "ether dst 91:E0:F0:00:0e:80";	/* The filter expression */
	struct pcap_pkthdr header;	/* header pcap gives us */
	const u_char* packet;		/* actual packet */

	signal(SIGINT, sigint_handler);

	int c;
	while((c = getopt(argc, argv, "hi:f:")) > 0) 
	{
		switch (c) 
		{
		case 'h': 
			help();
			break;
		case 'i':
			dev = strdup(optarg);
			break;
		case 'f':
			file_name = strdup(optarg);
			break;
		default:
          		fprintf(stderr, "Unrecognized option!\n");
		}
	}

	if ((NULL == dev) || (NULL == file_name))
		help();

	if (create_socket())
	{
		fprintf(stderr, "Socket creation failed.\n");
		return (errno);
	}

	report_domain_status();

	fprintf(stdout,"Waiting for talker...\n");
	await_talker();	

#ifdef DEBUG
	fprintf(stdout,"Send ready-msg...\n");
#endif
	send_ready();
		
#ifdef LIBSND
	SF_INFO* sf_info = (SF_INFO*)malloc(sizeof(SF_INFO));

	memset(sf_info, 0, sizeof(SF_INFO));
	
	sf_info->samplerate = SAMPLES_PER_SECOND;
	sf_info->channels = CHANNELS;
	sf_info->format = SF_FORMAT_WAV | SF_FORMAT_PCM_24;

	if (0 == sf_format_check(sf_info))
	{
		fprintf(stderr, "Wrong format.");
		return -1;
	}
			
	if (NULL == (snd_file = sf_open(file_name, SFM_WRITE, sf_info)))
	{
		fprintf(stderr, "Could not create file.");
		return -1;
	}
	fprintf(stdout,"Created file called %s\n", file_name);	
#endif

#ifdef PCAP		
	/** session, get session handler */
	/* take promiscuous vs. non-promiscuous sniffing? (0 or 1) */
	handle = pcap_open_live(dev, BUFSIZ, 1, -1, errbuf);
	if (NULL == handle) 
	{
		fprintf(stderr, "Could not open device %s: %s\n", dev, errbuf);
		return -1;
	}

#ifdef DEBUG
	fprintf(stdout,"Got session handler.\n");
#endif
	/* compile and apply filter */
	if (-1 == pcap_compile(handle, &comp_filter_exp, filter_exp, 0, PCAP_NETMASK_UNKNOWN))
	{
		fprintf(stderr, "Could not parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return -1;
	}

	if (-1 == pcap_setfilter(handle, &comp_filter_exp)) 
	{
		fprintf(stderr, "Could not install filter %s: %s\n", filter_exp, pcap_geterr(handle));
		return -1;
	}

#ifdef DEBUG
	fprintf(stdout,"Compiled and applied filter.\n");
#endif

	/** loop forever and call callback-function for every received packet */
	pcap_loop(handle, -1, pcap_callback, NULL);
#endif

	return 0;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
	int ret;

	char* dev = NULL;
	char errbuf[PCAP_ERRBUF_SIZE];
	struct bpf_program comp_filter_exp;		/** The compiled filter expression */
	char filter_exp[] = "ether dst 91:E0:F0:00:0e:80";	/** The filter expression */
	struct pcap_pkthdr header;	/** header pcap gives us */
	const u_char* packet;		/** actual packet */
	
	signal(SIGINT, shutdown_all);
	
	int c;
	while((c = getopt(argc, argv, "hi:")) > 0) 
	{
		switch (c) 
		{
		case 'h': 
			help();
			break;
		case 'i':
			dev = strdup(optarg);
			break;
		default:
          		fprintf(stderr, "Unrecognized option!\n");
		}
	}

	if (NULL == dev) {
		help();
	}

	if (create_socket()) {
		fprintf(stderr, "Socket creation failed.\n");
		return (errno);
	}

	send_process('D'); /** report domain status */

	init_jack();
	
	fprintf(stdout,"Waiting for talker...\n");
	await_talker();	

	send_process('R'); /** send_ready */

#ifdef LIBSND
	char* filename = "listener.wav";
	SF_INFO* sf_info = (SF_INFO*)malloc(sizeof(SF_INFO));

	memset(sf_info, 0, sizeof(SF_INFO));

	sf_info->samplerate = SAMPLES_PER_SECOND;
	sf_info->channels = CHANNELS;
	sf_info->format = SF_FORMAT_WAV | SF_FORMAT_PCM_24;

	if (0 == sf_format_check(sf_info)) {
		fprintf(stderr, "Wrong format.\n");
		shutdown_all(0);
		return -1;
	}

	if (NULL == (snd_file = sf_open(filename, SFM_WRITE, sf_info))) {
		fprintf(stderr, "Could not create file %s.\n", filename);
		shutdown_all(0);
		return -1;
	}
#endif

	/** session, get session handler */
	handle = pcap_open_live(dev, BUFSIZ, 1, -1, errbuf);
	if (NULL == handle) {
		fprintf(stderr, "Could not open device %s: %s.\n", dev, errbuf);
		shutdown_all(0);
		return -1;
	}

	/** compile and apply filter */
	if (-1 == pcap_compile(handle, &comp_filter_exp, filter_exp, 0, PCAP_NETMASK_UNKNOWN)) {
		fprintf(stderr, "Could not parse filter %s: %s.\n", filter_exp, pcap_geterr(handle));
		shutdown_all(0);
		return -1;
	}

	if (-1 == pcap_setfilter(handle, &comp_filter_exp)) {
		fprintf(stderr, "Could not install filter %s: %s.\n", filter_exp, pcap_geterr(handle));
		shutdown_all(0);
		return -1;
	}
	
	/** loop forever and call callback-function for every received packet */
	pcap_loop(handle, -1, pcap_callback, NULL);

	usleep(-1);
	return 0;
}
Esempio n. 13
0
static switch_status_t sndfile_file_open(switch_file_handle_t *handle, const char *path)
{
	sndfile_context *context;
	int mode = 0;
	char *ext;
	struct format_map *map = NULL;
	switch_status_t status = SWITCH_STATUS_SUCCESS;
	char *alt_path = NULL, *last, *ldup = NULL;
	size_t alt_len = 0;
	int rates[4] = { 8000, 16000, 32000, 48000 };
	int i;
	sf_count_t frames = 0;
#ifdef WIN32
	char ps = '/';
#else
	char ps = '/';
#endif

	if ((ext = strrchr(path, '.')) == 0) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Format\n");
		return SWITCH_STATUS_GENERR;
	}
	ext++;

	if (switch_test_flag(handle, SWITCH_FILE_FLAG_READ)) {
		mode += SFM_READ;
	}

	if (switch_test_flag(handle, SWITCH_FILE_FLAG_WRITE)) {
		if (switch_test_flag(handle, SWITCH_FILE_WRITE_APPEND) || switch_test_flag(handle, SWITCH_FILE_WRITE_OVER) || handle->offset_pos) {
			mode += SFM_RDWR;
		} else {
			mode += SFM_WRITE;
		}
	}

	if (!mode) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Invalid Mode!\n");
		return SWITCH_STATUS_GENERR;
	}

	if ((context = switch_core_alloc(handle->memory_pool, sizeof(*context))) == 0) {
		return SWITCH_STATUS_MEMERR;
	}

	map = switch_core_hash_find(globals.format_hash, ext);

	if (mode & SFM_WRITE) {
		context->sfinfo.channels = handle->channels;
		context->sfinfo.samplerate = handle->samplerate;
		if (handle->samplerate == 8000 || handle->samplerate == 16000 ||
			handle->samplerate == 24000 || handle->samplerate == 32000 || handle->samplerate == 48000 ||
			handle->samplerate == 11025 || handle->samplerate == 22050 || handle->samplerate == 44100) {
			context->sfinfo.format |= SF_FORMAT_PCM_16;
		}
	}

	if (map) {
		context->sfinfo.format |= map->format;
	}

	if (!strcmp(ext, "r8") || !strcmp(ext, "raw")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "r16")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_16;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 16000;
	} else if (!strcmp(ext, "r24")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_24;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 24000;
	} else if (!strcmp(ext, "r32")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_PCM_32;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 32000;
	} else if (!strcmp(ext, "gsm")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_GSM610;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "ul") || !strcmp(ext, "ulaw")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_ULAW;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "al") || !strcmp(ext, "alaw")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_ALAW;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "vox")) {
		context->sfinfo.format = SF_FORMAT_RAW | SF_FORMAT_VOX_ADPCM;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "adpcm")) {
		context->sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_IMA_ADPCM;
		context->sfinfo.channels = 1;
		context->sfinfo.samplerate = 8000;
	} else if (!strcmp(ext, "oga")) {
		context->sfinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;
		context->sfinfo.samplerate = handle->samplerate;
	}

	if ((mode & SFM_WRITE) && sf_format_check(&context->sfinfo) == 0) {
		switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error : file format is invalid (0x%08X).\n", context->sfinfo.format);
		return SWITCH_STATUS_GENERR;
	}

	alt_len = strlen(path) + 10;
	switch_zmalloc(alt_path, alt_len);

	switch_copy_string(alt_path, path, alt_len);

	/* This block attempts to add the sample rate to the path
	   if the sample rate is already present in the path it does nothing
	   and reverts to the original file name.
	 */
	if ((last = strrchr(alt_path, ps))) {
		last++;
#ifdef WIN32
		if (strrchr(last, '\\')) {
			last = strrchr(alt_path, '\\');	/* do not swallow a back slash if they are intermixed under windows */
			last++;
		}
#endif
		ldup = strdup(last);
		switch_assert(ldup);
		switch_snprintf(last, alt_len - (last - alt_path), "%d%s%s", handle->samplerate, SWITCH_PATH_SEPARATOR, ldup);
		if ((context->handle = sf_open(alt_path, mode, &context->sfinfo))) {
			path = alt_path;
		} else {
			/* Try to find the file at the highest rate possible if we can't find one that matches the exact rate.
			   If we don't find any, we will default back to the original file name.
			 */
			for (i = 3; i >= 0; i--) {
				switch_snprintf(last, alt_len - (last - alt_path), "%d%s%s", rates[i], SWITCH_PATH_SEPARATOR, ldup);
				if ((context->handle = sf_open(alt_path, mode, &context->sfinfo))) {
					path = alt_path;
					break;
				}
			}
		}
	}

	if (!context->handle) {
		if ((context->handle = sf_open(path, mode, &context->sfinfo)) == 0) {
			switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_ERROR, "Error Opening File [%s] [%s]\n", path, sf_strerror(context->handle));
			status = SWITCH_STATUS_GENERR;
			goto end;
		}
	}
	//switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "Opening File [%s] rate %dhz\n", path, context->sfinfo.samplerate);
	handle->samples = (unsigned int) context->sfinfo.frames;
	handle->samplerate = context->sfinfo.samplerate;
	handle->channels = (uint8_t) context->sfinfo.channels;
	handle->format = context->sfinfo.format;
	handle->sections = context->sfinfo.sections;
	handle->seekable = context->sfinfo.seekable;
	handle->speed = 0;
	handle->private_info = context;

	if (handle->offset_pos) {
		frames = handle->offset_pos;
		handle->offset_pos = 0;
	}

	if (switch_test_flag(handle, SWITCH_FILE_WRITE_APPEND)) {
		handle->pos = sf_seek(context->handle, frames, SEEK_END);
	} else if (switch_test_flag(handle, SWITCH_FILE_WRITE_OVER)) {
		handle->pos = sf_seek(context->handle, frames, SEEK_SET);
	} else {		
		sf_command(context->handle, SFC_FILE_TRUNCATE, &frames, sizeof(frames));
	}


  end:

	switch_safe_free(alt_path);
	switch_safe_free(ldup);

	return status;
}
Esempio n. 14
0
int
main (int argc, char * argv [])
{	char 		*progname, *infilename, *outfilename ;
	SNDFILE	 	*infile = NULL, *outfile = NULL ;
	SF_INFO	 	sfinfo ;
	int			k, outfilemajor, outfileminor = 0, infileminor ;

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

	if (argc < 3 || argc > 5)
	{	print_usage (progname) ;
		return 1 ;
		} ;

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

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

	if (infilename [0] == '-')
	{	printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
		print_usage (progname) ;
		return 1 ;
		} ;

	if (outfilename [0] == '-')
	{	printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
		print_usage (progname) ;
		return 1 ;
		} ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (! strcmp (argv [k], "-pcms8"))
		{	outfileminor = SF_FORMAT_PCM_S8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcmu8"))
		{	outfileminor = SF_FORMAT_PCM_U8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm16"))
		{	outfileminor = SF_FORMAT_PCM_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm24"))
		{	outfileminor = SF_FORMAT_PCM_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm32"))
		{	outfileminor = SF_FORMAT_PCM_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-float32"))
		{	outfileminor = SF_FORMAT_FLOAT ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ulaw"))
		{	outfileminor = SF_FORMAT_ULAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alaw"))
		{	outfileminor = SF_FORMAT_ALAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ima-adpcm"))
		{	outfileminor = SF_FORMAT_IMA_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ms-adpcm"))
		{	outfileminor = SF_FORMAT_MS_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-gsm610"))
		{	outfileminor = SF_FORMAT_GSM610 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw12"))
		{	outfileminor = SF_FORMAT_DWVW_12 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw16"))
		{	outfileminor = SF_FORMAT_DWVW_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw24"))
		{	outfileminor = SF_FORMAT_DWVW_24 ;
			continue ;
			} ;

		printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
		exit (1) ;
		} ;

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

	infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if ((sfinfo.format = guess_output_file_type (outfilename, sfinfo.format)) == 0)
	{	printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
		return 1 ;
		} ;

	outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;

	if (outfileminor == 0)
		outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if (outfileminor != 0)
		sfinfo.format = outfilemajor | outfileminor ;
	else
		sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;

	if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_PCM_16 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
					break ;

			case SF_FORMAT_PCM_S8 :
			case SF_FORMAT_PCM_U8 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
					break ;
			} ;

	if (sf_format_check (&sfinfo) == 0)
	{	printf ("Error : output file format is invalid (0x%08X).\n", sfinfo.format) ;
		return 1 ;
		} ;

	/* Open the output file. */
	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Copy the metadata */
	copy_metadata (outfile, infile) ;

	if ((outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT) ||
				(infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT))
		copy_data_fp (outfile, infile, sfinfo.channels) ;
	else
		copy_data_int (outfile, infile, sfinfo.channels) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Esempio n. 15
0
Edje_Sound_Encode *
_edje_multisense_encode(const char *filename, Edje_Sound_Sample *sample, double quality EINA_UNUSED)
{
   SF_INFO sfinfo;
   SNDFILE* sfile;
   Edje_Sound_Encode *enc_info;
   
   enc_info = calloc(1, sizeof(Edje_Sound_Encode));
   if (!enc_info)
     {
        ERR("while allocating memory to load file ");
        exit(-1);
     }
   memset (&sfinfo, 0, sizeof (SF_INFO));
   
   enc_info->encoded = EINA_FALSE;
   enc_info->comp_type = "RAW PCM";
   
   // Open wav file using sndfile
   sfile = sf_open (filename, SFM_READ, &sfinfo);
   if (!sfile)
     {
        ERR("Unable to open audio file: %s", filename);
        exit(-1);
     }

   if (!sf_format_check(&sfinfo))
     {
        ERR("Unknown file, not a valid audio file");
        exit(-1);
     }

   if (sample->compression == EDJE_SOUND_SOURCE_TYPE_INLINE_COMP)
     {
        sf_close(sfile);
#ifdef HAVE_LIBFLAC
        //encode provided wav file to flac
        enc_info->file = _edje_multisense_encode_to_flac((char *)filename, sfinfo);
        if (enc_info->file)
          {
             enc_info->comp_type = "FLAC";
             enc_info->encoded = EINA_TRUE;
          }
#else
        WRN("WARNING: Unable to encode sound %s to FLAC compression",
            sample->name);
#endif
     }
   else if (sample->compression == EDJE_SOUND_SOURCE_TYPE_INLINE_LOSSY)
     {
        sf_close(sfile);
#ifdef HAVE_VORBIS
        //encode provided wav file to ogg-vorbis
        enc_info->file = _edje_multisense_encode_to_ogg_vorbis((char *)filename,
                                                               quality, sfinfo);
        if (enc_info->file)
          {
             enc_info->comp_type = "OGG-VORBIS";
             enc_info->encoded = EINA_TRUE;
          }
#else
        WRN("WARNING: Unable to encode sound %s to Ogg-Vorbis",
            sample->name);
#endif
     }
   else
     eina_stringshare_replace(&enc_info->file, filename);
   return enc_info;
}
Esempio n. 16
0
void* diskWriterDriver_thread( void* param )
{

		Object* __object = ( Object* )param;
	DiskWriterDriver *pDriver = ( DiskWriterDriver* )param;
		EventQueue::get_instance()->push_event( EVENT_PROGRESS, 0 );
		pDriver->setBpm( Hydrogen::get_instance()->getSong()->__bpm );
		pDriver->audioEngine_process_checkBPMChanged();
	__INFOLOG( "DiskWriterDriver thread start" );

	// always rolling, no user interaction
	pDriver->m_transport.m_status = TransportInfo::ROLLING;

	SF_INFO soundInfo;
	soundInfo.samplerate = pDriver->m_nSampleRate;
//	soundInfo.frames = -1;//getNFrames();		///\todo: da terminare
	soundInfo.channels = 2;
	//default format
	int sfformat = 0x010000; //wav format (default)
	int bits = 0x0002; //16 bit PCM (default)
	//sf_format switch
	if( pDriver->m_sFilename.endsWith(".aiff") || pDriver->m_sFilename.endsWith(".AIFF") ){
		sfformat =  0x020000; //Apple/SGI AIFF format (big endian)
	}
	if( pDriver->m_sFilename.endsWith(".flac") || pDriver->m_sFilename.endsWith(".FLAC") ){
		sfformat =  0x170000; //FLAC lossless file format
	}
	if( ( pDriver->m_nSampleDepth == 8 ) && ( pDriver->m_sFilename.endsWith(".aiff") || pDriver->m_sFilename.endsWith(".AIFF") ) ){
		bits = 0x0001; //Signed 8 bit data works with aiff
	}
	if( ( pDriver->m_nSampleDepth == 8 ) && ( pDriver->m_sFilename.endsWith(".wav") || pDriver->m_sFilename.endsWith(".WAV") ) ){
		bits = 0x0005; //Unsigned 8 bit data needed for Microsoft WAV format
	}
	if( pDriver->m_nSampleDepth == 16 ){
		bits = 0x0002; //Signed 16 bit data
	}
	if( pDriver->m_nSampleDepth == 24 ){
		bits = 0x0003; //Signed 24 bit data
	}
	if( pDriver->m_nSampleDepth == 32 ){
		bits = 0x0004; ////Signed 32 bit data
	}

	soundInfo.format =  sfformat|bits;

//	#ifdef HAVE_OGGVORBIS

	//ogg vorbis option
	if( pDriver->m_sFilename.endsWith( ".ogg" ) | pDriver->m_sFilename.endsWith( ".OGG" ) )
		soundInfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS;

//	#endif


///formats
//          SF_FORMAT_WAV          = 0x010000,     /* Microsoft WAV format (little endian). */
//          SF_FORMAT_AIFF         = 0x020000,     /* Apple/SGI AIFF format (big endian). */
//          SF_FORMAT_AU           = 0x030000,     /* Sun/NeXT AU format (big endian). */
//          SF_FORMAT_RAW          = 0x040000,     /* RAW PCM data. */
//          SF_FORMAT_PAF          = 0x050000,     /* Ensoniq PARIS file format. */
//          SF_FORMAT_SVX          = 0x060000,     /* Amiga IFF / SVX8 / SV16 format. */
//          SF_FORMAT_NIST         = 0x070000,     /* Sphere NIST format. */
//          SF_FORMAT_VOC          = 0x080000,     /* VOC files. */
//          SF_FORMAT_IRCAM        = 0x0A0000,     /* Berkeley/IRCAM/CARL */
//          SF_FORMAT_W64          = 0x0B0000,     /* Sonic Foundry's 64 bit RIFF/WAV */
//          SF_FORMAT_MAT4         = 0x0C0000,     /* Matlab (tm) V4.2 / GNU Octave 2.0 */
//          SF_FORMAT_MAT5         = 0x0D0000,     /* Matlab (tm) V5.0 / GNU Octave 2.1 */
//          SF_FORMAT_PVF          = 0x0E0000,     /* Portable Voice Format */
//          SF_FORMAT_XI           = 0x0F0000,     /* Fasttracker 2 Extended Instrument */
//          SF_FORMAT_HTK          = 0x100000,     /* HMM Tool Kit format */
//          SF_FORMAT_SDS          = 0x110000,     /* Midi Sample Dump Standard */
//          SF_FORMAT_AVR          = 0x120000,     /* Audio Visual Research */
//          SF_FORMAT_WAVEX        = 0x130000,     /* MS WAVE with WAVEFORMATEX */
//          SF_FORMAT_SD2          = 0x160000,     /* Sound Designer 2 */
//          SF_FORMAT_FLAC         = 0x170000,     /* FLAC lossless file format */
//          SF_FORMAT_CAF          = 0x180000,     /* Core Audio File format */
//	    SF_FORMAT_OGG
///bits
//          SF_FORMAT_PCM_S8       = 0x0001,       /* Signed 8 bit data */
//          SF_FORMAT_PCM_16       = 0x0002,       /* Signed 16 bit data */
//          SF_FORMAT_PCM_24       = 0x0003,       /* Signed 24 bit data */
//          SF_FORMAT_PCM_32       = 0x0004,       /* Signed 32 bit data */
///used for ogg
//          SF_FORMAT_VORBIS

	if ( !sf_format_check( &soundInfo ) ) {
		__ERRORLOG( "Error in soundInfo" );
		return 0;
	}


	SNDFILE* m_file = sf_open( pDriver->m_sFilename.toLocal8Bit(), SFM_WRITE, &soundInfo );

	float *pData = new float[ pDriver->m_nBufferSize * 2 ];	// always stereo

	float *pData_L = pDriver->m_pOut_L;
	float *pData_R = pDriver->m_pOut_R;


		Hydrogen* engine = Hydrogen::get_instance();

	std::vector<PatternList*> *pPatternColumns = Hydrogen::get_instance()->getSong()->get_pattern_group_vector();
	int nColumns = pPatternColumns->size();

	int nPatternSize;
		int validBpm = engine->getSong()->__bpm;
		float oldBPM = 0;
		float ticksize = 0;
		for ( int patternposition = 0; patternposition < nColumns; ++patternposition ) {
				PatternList *pColumn = ( *pPatternColumns )[ patternposition ];
		if ( pColumn->size() != 0 ) {
			nPatternSize = pColumn->get( 0 )->get_length();
		} else {
			nPatternSize = MAX_NOTES;
				}

				ticksize = pDriver->m_nSampleRate * 60.0 /  engine->getSong()->__bpm / engine->getSong()->__resolution;
				// check pattern bpm if timeline bpm is in use
				Timeline* pTimeline = engine->getTimeline();
				if(Preferences::get_instance()->getUseTimelineBpm() ){
						if( pTimeline->m_timelinevector.size() >= 1 ){

								for ( int t = 0; t < pTimeline->m_timelinevector.size(); t++){
										if(pTimeline->m_timelinevector[t].m_htimelinebeat == patternposition &&
											pTimeline->m_timelinevector[t].m_htimelinebpm != validBpm){
												validBpm =  pTimeline->m_timelinevector[t].m_htimelinebpm;
										}

								}
						}
						pDriver->setBpm(validBpm);
						ticksize = pDriver->m_nSampleRate * 60.0 / validBpm / Hydrogen::get_instance()->getSong()->__resolution;
						pDriver->audioEngine_process_checkBPMChanged();
						engine->setPatternPos(patternposition);

						// delay needed time to calculate all rubberband samples
						if( Preferences::get_instance()->getRubberBandBatchMode() && validBpm != oldBPM ){
								EventQueue::get_instance()->push_event( EVENT_RECALCULATERUBBERBAND, -1);
								int sleepTime = Preferences::get_instance()->getRubberBandCalcTime()+1;
								while ((sleepTime = sleep(sleepTime)) > 0);
						}
						oldBPM = validBpm;

				}
				else
				{
						ticksize = pDriver->m_nSampleRate * 60.0 /  Hydrogen::get_instance()->getSong()->__bpm / Hydrogen::get_instance()->getSong()->__resolution;
						//pDriver->m_transport.m_nTickSize = ticksize;
				}


				 //here we have the pattern length in frames dependent from bpm and samplerate
				unsigned patternLengthInFrames = ticksize * nPatternSize;

				unsigned frameNumber = 0;
				int lastRun = 0;
				while ( frameNumber < patternLengthInFrames ) {

						int usedBuffer = pDriver->m_nBufferSize;

						//this will calculate the the size from -last- (end of pattern) used frame buffer,
						//which is mostly smaller than pDriver->m_nBufferSize
						if( patternLengthInFrames - frameNumber <  pDriver->m_nBufferSize ){
								lastRun = patternLengthInFrames - frameNumber;
								usedBuffer = lastRun;
						};

						frameNumber += usedBuffer;
						int ret = pDriver->m_processCallback( usedBuffer, NULL );

						for ( unsigned i = 0; i < usedBuffer; i++ ) {
								if(pData_L[i] > 1){
										pData[i * 2] = 1;
								}
								else if(pData_L[i] < -1){
										pData[i * 2] = -1;
								}else
								{
										pData[i * 2] = pData_L[i];
								}

								if(pData_R[i] > 1){
										pData[i * 2 + 1] = 1;
								}
								else if(pData_R[i] < -1){
										pData[i * 2 + 1] = -1;
								}else
								{
										pData[i * 2 + 1] = pData_R[i];
								}
						}
						int res = sf_writef_float( m_file, pData, usedBuffer );
						if ( res != ( int )usedBuffer ) {
								__ERRORLOG( "Error during sf_write_float" );
						}
				}

				// this progress bar methode is not exact but ok enough to give users a usable visible progress feedback
				float fPercent = ( float )(patternposition +1) / ( float )nColumns * 100.0;
				EventQueue::get_instance()->push_event( EVENT_PROGRESS, ( int )fPercent );
		}

	delete[] pData;
	pData = NULL;

	sf_close( m_file );

	__INFOLOG( "DiskWriterDriver thread end" );

	pthread_exit( NULL );

	return NULL;
}
Esempio n. 17
0
int
main (int argc, char * argv [])
{	const char	*progname, *infilename, *outfilename ;
	SNDFILE		*infile = NULL, *outfile = NULL ;
	SF_INFO		sfinfo ;
	int			k, outfilemajor, outfileminor = 0, infileminor ;
	int			override_sample_rate = 0 ; /* assume no sample rate override. */

	progname = program_name (argv [0]) ;

	if (argc < 3 || argc > 5)
	{	usage_exit (progname) ;
		return 1 ;
		} ;

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

	if (strcmp (infilename, outfilename) == 0)
	{	printf ("Error : Input and output filenames are the same.\n\n") ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	if (strlen (infilename) > 1 && infilename [0] == '-')
	{	printf ("Error : Input filename (%s) looks like an option.\n\n", infilename) ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	if (outfilename [0] == '-')
	{	printf ("Error : Output filename (%s) looks like an option.\n\n", outfilename) ;
		usage_exit (progname) ;
		return 1 ;
		} ;

	for (k = 1 ; k < argc - 2 ; k++)
	{	if (! strcmp (argv [k], "-pcms8"))
		{	outfileminor = SF_FORMAT_PCM_S8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcmu8"))
		{	outfileminor = SF_FORMAT_PCM_U8 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm16"))
		{	outfileminor = SF_FORMAT_PCM_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm24"))
		{	outfileminor = SF_FORMAT_PCM_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-pcm32"))
		{	outfileminor = SF_FORMAT_PCM_32 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-float32"))
		{	outfileminor = SF_FORMAT_FLOAT ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ulaw"))
		{	outfileminor = SF_FORMAT_ULAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-alaw"))
		{	outfileminor = SF_FORMAT_ALAW ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ima-adpcm"))
		{	outfileminor = SF_FORMAT_IMA_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-ms-adpcm"))
		{	outfileminor = SF_FORMAT_MS_ADPCM ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-gsm610"))
		{	outfileminor = SF_FORMAT_GSM610 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw12"))
		{	outfileminor = SF_FORMAT_DWVW_12 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw16"))
		{	outfileminor = SF_FORMAT_DWVW_16 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-dwvw24"))
		{	outfileminor = SF_FORMAT_DWVW_24 ;
			continue ;
			} ;
		if (! strcmp (argv [k], "-vorbis"))
		{	outfileminor = SF_FORMAT_VORBIS ;
			continue ;
			} ;

		if (strstr (argv [k], "-override-sample-rate=") == argv [k])
		{	const char *ptr ;

			ptr = argv [k] + strlen ("-override-sample-rate=") ;
			override_sample_rate = atoi (ptr) ;
			continue ;
			} ;

		printf ("Error : Not able to decode argunment '%s'.\n", argv [k]) ;
		exit (1) ;
		} ;

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

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

	/* Update sample rate if forced to something else. */
	if (override_sample_rate)
		sfinfo.samplerate = override_sample_rate ;

	infileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if ((sfinfo.format = sfe_file_type_of_ext (outfilename, sfinfo.format)) == 0)
	{	printf ("Error : Not able to determine output file type for %s.\n", outfilename) ;
		return 1 ;
		} ;

	outfilemajor = sfinfo.format & (SF_FORMAT_TYPEMASK | SF_FORMAT_ENDMASK) ;

	if (outfileminor == 0)
		outfileminor = sfinfo.format & SF_FORMAT_SUBMASK ;

	if (outfileminor != 0)
		sfinfo.format = outfilemajor | outfileminor ;
	else
		sfinfo.format = outfilemajor | (sfinfo.format & SF_FORMAT_SUBMASK) ;

	if ((sfinfo.format & SF_FORMAT_TYPEMASK) == SF_FORMAT_XI)
		switch (sfinfo.format & SF_FORMAT_SUBMASK)
		{	case SF_FORMAT_PCM_16 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_16 ;
					break ;

			case SF_FORMAT_PCM_S8 :
			case SF_FORMAT_PCM_U8 :
					sfinfo.format = outfilemajor | SF_FORMAT_DPCM_8 ;
					break ;
			} ;

	if (sf_format_check (&sfinfo) == 0)
	{	printf ("Error : output file format is invalid (0x%08X).\n", sfinfo.format) ;
		return 1 ;
		} ;

	/* Open the output file. */
	if ((outfile = sf_open (outfilename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Not able to open output file %s : %s\n", outfilename, sf_strerror (NULL)) ;
		return 1 ;
		} ;

	/* Copy the metadata */
	copy_metadata (outfile, infile, sfinfo.channels) ;

	if ((outfileminor == SF_FORMAT_DOUBLE) || (outfileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_DOUBLE) || (infileminor == SF_FORMAT_FLOAT)
			|| (infileminor == SF_FORMAT_VORBIS) || (outfileminor == SF_FORMAT_VORBIS))
		sfe_copy_data_fp (outfile, infile, sfinfo.channels) ;
	else
		sfe_copy_data_int (outfile, infile, sfinfo.channels) ;

	sf_close (infile) ;
	sf_close (outfile) ;

	return 0 ;
} /* main */
Esempio n. 18
0
//-----------------------------------------------------------------------------
// name: writeWavFile()
// desc: This function takes an array of floats and writes the data to a .wav file.
//-----------------------------------------------------------------------------
void writeWavFile(float *audio, int sample_rate, int numChannels, int numFrames,
		int numOutChannels, char *outFileName) {
	int i;

	SNDFILE *outfile;
	SF_INFO sfinfo_out;

	memset(&sfinfo_out, 0, sizeof(SF_INFO));
	sfinfo_out.samplerate = sample_rate;
	sfinfo_out.channels = numChannels;
	sfinfo_out.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
	if (!sf_format_check(&sfinfo_out)) {
		printf("error: incorrect audio file format\n");
		return;
	}

	if ((outfile = sf_open(outFileName, SFM_WRITE, &sfinfo_out)) == NULL) {
		printf("error, couldn't open the file\n");
		return;
	}

	// get the number of samples in the input audio
	int inputLength = numChannels * numFrames;

	// mono input to mono output
	if (numChannels == 1 && numOutChannels == 1) {
		// allocate the appropriate number of samples in the output audio
		float *output = (float *) malloc(sizeof(float) * inputLength);
		for (i = 0; i < inputLength; i++) {
			output[i] = audio[i];
		}
		sf_writef_float(outfile, output, inputLength);
		free(output);
	}
	// sTEREO INPUT to MONO OUTPUT
	else if (numChannels == 2 && numOutChannels == 1) {
		// Allocate the appropriate number of samples in the output audio
		float *output = (float *) malloc(sizeof(float) * inputLength / 2);
		for (i = 0; i < inputLength / 2; i++) {
			output[i] = (audio[2 * i] + audio[2 * i + 1]) / 2;
		}
		sf_writef_float(outfile, output, inputLength / 2);
		free(output);
	}
	// MONO INPUT to STEREO OUTPUT
	else if (numChannels == 1 && numOutChannels == 2) {
		// Allocate the appropriate number of samples in the output audio
		float *output = (float *) malloc(sizeof(float) * inputLength * 2);
		for (i = 0; i < inputLength; i++) {
			output[2 * i] = audio[i];
			output[2 * i + 1] = audio[i];
		}
		sf_writef_float(outfile, output, inputLength);
		free(output);
	}
	// STEREO INPUT to STEREO OUTPUT
	else if (numChannels == 2 && numOutChannels == 2) {
		// Allocate the appropriate number of samples in the output audio
		float *output = (float *) malloc(sizeof(float) * inputLength);
		for (i = 0; i < inputLength; i++) {
			output[i] = audio[i];
		}
		sf_writef_float(outfile, output, inputLength / 2);
		free(output);
	}
	sf_close(outfile);
}
Esempio n. 19
0
const char*
_edje_multisense_encode_to_flac(char *snd_path, SF_INFO sfinfo)
{
   unsigned int total_samples = 0; /* can use a 32-bit number due to WAVE size limitations */
   FLAC__bool ok = 1;
   FLAC__StreamEncoder *encoder = 0;
   FLAC__StreamEncoderInitStatus init_status;
   FLAC__StreamMetadata *metadata[2];
   FLAC__StreamMetadata_VorbisComment_Entry entry;
   SNDFILE *sfile;
   sf_count_t size;
   char *tmp;

   sfile = sf_open(snd_path, SFM_READ, &sfinfo);
   if (!sfile) return NULL;
   if (!sf_format_check(&sfinfo))
     {
        sf_close(sfile);
        return NULL;
     }
   size = sf_seek(sfile, 0, SEEK_END);
   sf_seek(sfile, 0, SEEK_SET);
   tmp = malloc(strlen(snd_path) + 1 + 5);
   if (!tmp)
     {
        sf_close(sfile);
        return NULL;
     }
   strcpy(tmp, snd_path);
   snd_path = tmp;
   strcat(snd_path, ".flac");

   total_samples = size;

   /* allocate the encoder */
   if ((encoder = FLAC__stream_encoder_new()) == NULL)
     {
        ERR("ERROR: Creating FLAC encoder\n");
        free(snd_path);
        sf_close(sfile);
        return NULL;
     }

   /* Verify it's own encoded output. This will slow the encoding process. */
   ok &= FLAC__stream_encoder_set_verify(encoder, 1);

   //Levels range from 0 (fastest, least compression) to 8 (slowest, most compression).
   //A value larger than 8 will be treated as 8.
   //5 is used for good compression and moderate compression/decompression speed.
   ok &= FLAC__stream_encoder_set_compression_level(encoder, 5);
   ok &= FLAC__stream_encoder_set_channels(encoder, sfinfo.channels);
   ok &= FLAC__stream_encoder_set_bits_per_sample(encoder, 16);
   ok &= FLAC__stream_encoder_set_sample_rate(encoder, sfinfo.samplerate);
   ok &= FLAC__stream_encoder_set_total_samples_estimate(encoder, total_samples);

   /* now add some metadata; we'll add some tags and a padding block */
   if (ok)
     {
        if ((metadata[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == NULL
            || (metadata[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == NULL
            || !FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "Encoder", "flac")
            || !FLAC__metadata_object_vorbiscomment_append_comment(metadata[0], entry, 0))
          {
             ERR("ERROR: out of memory error or tag error\n");
             ok = 0;
          }
        metadata[1]->length = 16; /* set the padding length */
        ok = FLAC__stream_encoder_set_metadata(encoder, metadata, 2);
     }

   /* initialize encoder */
   if (ok)
     {
        init_status = FLAC__stream_encoder_init_file(encoder, snd_path, NULL,
                                                     (void *)(long)(total_samples));
        if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
          {
             ERR("ERROR: unable to initialize FLAC encoder: %s\n",
                 FLAC__StreamEncoderInitStatusString[init_status]);
             ok = 0;
          }
     }
   
   /* read blocks of samples from WAVE file and feed to encoder */
   while (ok)
     {
        FLAC__int32 readbuffer[READBUF * 2];
        sf_count_t count;
        int i;
        
        count = sf_readf_int(sfile, readbuffer, READBUF);
        if (count <= 0) break;
        for (i = 0; i < (count * sfinfo.channels); i++)
          readbuffer[i] = readbuffer[i] >> 16;
        ok = FLAC__stream_encoder_process_interleaved(encoder, readbuffer,
                                                      count);
     }

   FLAC__stream_encoder_finish(encoder);
   /* now that encoding is finished, the metadata can be freed */
   FLAC__metadata_object_delete(metadata[0]);
   FLAC__metadata_object_delete(metadata[1]);

   FLAC__stream_encoder_delete(encoder);
   sf_close(sfile);
   return (snd_path);
}
Esempio n. 20
0
const char *
_edje_multisense_encode_to_ogg_vorbis(char *snd_path, double quality, SF_INFO sfinfo)
{
   ogg_stream_state os; /* take physical pages, weld into a logical stream of packets */
   ogg_page og; /* one Ogg bitstream page.  Vorbis packets are inside */
   ogg_packet op; /* one raw packet of data for decode */
   vorbis_info vi; /* struct that stores all the static vorbis bitstream settings */
   vorbis_comment vc; /* struct that stores all the user comments */
   vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
   vorbis_block vb; /* local working space for packet->PCM decode */
   int eos = 0, ret;
   char *tmp;
   SNDFILE *sfile;
   FILE *fout;

   sfile = sf_open(snd_path, SFM_READ, &sfinfo);
   if (!sfile) return NULL;
   if (!sf_format_check(&sfinfo))
     {
        sf_close(sfile);
        return NULL;
     }
   tmp = malloc(strlen(snd_path) + 1 + 4);
   if (!tmp)
     {
        sf_close(sfile);
        return NULL;
     }
   strcpy(tmp, snd_path);
   snd_path = tmp;
   strcat(snd_path, ".ogg");
   fout = fopen(snd_path, "wb");
   if (!fout)
     {
        free(snd_path);
        sf_close(sfile);
        return NULL;
     }

   /********** Encode setup ************/
   vorbis_info_init(&vi);
   ret = vorbis_encode_init(&vi, sfinfo.channels, sfinfo.samplerate, 
                            -1, (long)(quality * 1000), -1);
   if (ret == OV_EFAULT) printf("OV_EFAULT\n");
   if (ret == OV_EINVAL) printf("OV_EINVAL\n");
   if (ret == OV_EIMPL) printf("OV_EIMPL\n");

   if (ret)
     {
        fclose(fout);
        free(snd_path);
        sf_close(sfile);
        return NULL;
     }

   /* add a comment */
   vorbis_comment_init(&vc);
   vorbis_comment_add_tag(&vc, "", "");

   /* set up the analysis state and auxiliary encoding storage */
   vorbis_analysis_init(&vd, &vi);
   vorbis_block_init(&vd, &vb);

   srand(time(NULL));
   ogg_stream_init(&os, rand());

   ogg_packet header;
   ogg_packet header_comm;
   ogg_packet header_code;

   vorbis_analysis_headerout(&vd, &vc, &header, &header_comm, &header_code);
   ogg_stream_packetin(&os, &header); /* automatically placed in its own page */
   ogg_stream_packetin(&os, &header_comm);
   ogg_stream_packetin(&os, &header_code);

   while (!eos)
     {
        int result = ogg_stream_flush(&os, &og);
        if (!result) break;
        fwrite(og.header, 1, og.header_len, fout);
        fwrite(og.body, 1, og.body_len, fout);
     }

   while (!eos)
     {
        int i, ch;
        float readbuffer[READBUF * 2];
        sf_count_t count;
        
        count = sf_readf_float(sfile, readbuffer, READBUF);

        if (!count)
          vorbis_analysis_wrote(&vd, 0);
        else
          {
             float **buffer = vorbis_analysis_buffer(&vd, count);
             
             /* uninterleave samples */
             for (i = 0; i < count; i++)
               {
                  for (ch = 0; ch < sfinfo.channels; ch++)
                    buffer[ch][i]= readbuffer[(i * sfinfo.channels) + ch];
               }
             vorbis_analysis_wrote(&vd, i);
          }
        while (vorbis_analysis_blockout(&vd, &vb) == 1)
          {
             vorbis_analysis(&vb, NULL);
             vorbis_bitrate_addblock(&vb);

             while (vorbis_bitrate_flushpacket(&vd, &op))
               {
                  ogg_stream_packetin(&os, &op);
                  while (!eos)
                    {
                       int result = ogg_stream_pageout(&os, &og);
                       if (!result) break;
                       fwrite(og.header, 1, og.header_len, fout);
                       fwrite(og.body, 1, og.body_len, fout);
                       if (ogg_page_eos(&og)) eos = 1;
                    }
               }
          }
     }
   ogg_stream_clear(&os);
   vorbis_block_clear(&vb);
   vorbis_dsp_clear(&vd);
   vorbis_comment_clear(&vc);
   vorbis_info_clear(&vi);
   sf_close(sfile);
   fclose (fout);
   return snd_path;
}
Esempio n. 21
0
bool PCMExporter::Export(const wxString & filename)
{

  mFileName = filename;
  //Unless it has been changed, use the project rate
  if(!mOutRate) 
    mOutRate = mProject->GetRate();
  
  wxWindow    *parent = mProject;
  TrackList   *tracks = mProject->GetTracks();

  wxString     formatStr;
  SF_INFO      info;
  SNDFILE     *sf = NULL;
  int          err;

   formatStr = sf_header_name(mSoundFileFormat & SF_FORMAT_TYPEMASK);

   // Use libsndfile to export file

   info.samplerate = mOutRate;
   info.frames = (unsigned int)((m_t1 - m_t0)*(double)mOutRate + 0.5);
   info.channels = mChannels;
   info.format = mSoundFileFormat;
   info.sections = 1;
   info.seekable = 0;

   // If we can't export exactly the format they requested,
   // try the default format for that header type...
   if (!sf_format_check(&info))
      info.format = (info.format & SF_FORMAT_TYPEMASK);
   if (!sf_format_check(&info)) {
      wxMessageBox(_("Cannot export audio in this format."));
      return false;
   }

   sf = sf_open((const char *)mFileName, SFM_WRITE, &info);
   if (!sf) {
      wxMessageBox(wxString::Format(_("Cannot export audio to %s"),
                                    (const char *)mFileName));
      return false;
   }

   //Determine what format the track is currently in, to avoid
   //multiple conversions.
   sampleFormat format;
   if (sf_subtype_more_than_16_bits(info.format))
      format = floatSample;
   else
      format = int16Sample;

   int maxBlockLen = 44100 * 5;

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

   int numWaveTracks;
   WaveTrack **waveTracks;
   tracks->GetWaveTracks(mExportSelection, &numWaveTracks, &waveTracks);



  
   Mixer *mixer = new Mixer(numWaveTracks, waveTracks,
                            tracks->GetTimeTrack(),
                            m_t0, m_t1,
                            info.channels, maxBlockLen, true,
                            mInRate, format);

   while(!cancelling) {
      sampleCount numSamples = mixer->Process(maxBlockLen);

      if (numSamples == 0)
         break;
      
      samplePtr mixed = mixer->GetBuffer();

      if (format == int16Sample)
         sf_writef_short(sf, (short *)mixed, numSamples);
      else
         sf_writef_float(sf, (float *)mixed, numSamples);

      if (!progress && wxGetElapsedTime(false) > 500) {

         wxString message;

         if (mExportSelection)
            message =
                wxString::
                Format(_("Exporting the selected audio as a %s file"),
                       (const char *) formatStr);
         else
            message =
                wxString::
                Format(_("Exporting the entire project as a %s file"),
                       (const char *) formatStr);

         progress =
             new wxProgressDialog(_("Export"),
                                  message,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         int progressvalue = int (1000 * ((mixer->MixGetCurrentTime()-m_t0) /
                                          (m_t1-m_t0)));
         cancelling = !progress->Update(progressvalue);
      }
   }

   delete mixer;

   delete[] waveTracks;                            

   err = sf_close(sf);

   if (err) {
      char buffer[1000];
      sf_error_str(sf, buffer, 1000);
      wxMessageBox(wxString::Format
                   (_("Error (file may not have been written): %s"),
                    buffer));
   }

#ifdef __WXMAC__

   FSSpec spec;

   wxMacFilename2FSSpec(fName, &spec);

   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = sf_header_mactype(mSoundFileFormat & SF_FORMAT_TYPEMASK);
      finfo.fdCreator = AUDACITY_CREATOR;

      FSpSetFInfo(&spec, &finfo);
   }
#endif

   if (progress)
      delete progress;

   return true;
}
Esempio n. 22
0
bool ExportPCM(AudacityProject *project,
               bool stereo, wxString fName,
               bool selectionOnly, double t0, double t1)
{
   double       rate = project->GetRate();
   wxWindow    *parent = project;
   TrackList   *tracks = project->GetTracks();
   int          format = ReadExportFormatPref();
   int          formatBits = ReadExportFormatBitsPref();
   wxString     formatStr;
   SF_INFO      info;
   SNDFILE     *sf;
   int          err;

   formatStr = sf_header_name(format & SF_FORMAT_TYPEMASK);

   // Use libsndfile to export file

   info.samplerate = (unsigned int)(rate + 0.5);
   info.samples = (unsigned int)((t1 - t0)*rate + 0.5);
   info.channels = stereo? 2: 1;
   info.pcmbitwidth = formatBits;
   info.format = format;
   info.sections = 1;
   info.seekable = 0;

   // If we can't export exactly the format they requested,
   // try the default format for that header type, and try
   // 16-bit samples.
   if (!sf_format_check(&info))
      info.format = (info.format & SF_FORMAT_TYPEMASK);
   if (!sf_format_check(&info))
      info.pcmbitwidth = 16;
   if (!sf_format_check(&info)) {
      wxMessageBox(_("Cannot export audio in this format."));
      return false;
   }

   sf = sf_open_write((const char *)fName, &info);
   if (!sf) {
      wxMessageBox(wxString::Format(_("Cannot export audio to %s"),
                                    (const char *)fName));
      return false;
   }

   double timeStep = 10.0;      // write in blocks of 10 secs

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

   double t = t0;

   while (t < t1 && !cancelling) {

      double deltat = timeStep;
      if (t + deltat > t1)
         deltat = t1 - t;

      sampleCount numSamples = int (deltat * rate + 0.5);

      Mixer *mixer = new Mixer(stereo ? 2 : 1, numSamples, true, rate);
      wxASSERT(mixer);
      mixer->Clear();

      TrackListIterator iter(tracks);
      VTrack *tr = iter.First();
      while (tr) {
         if (tr->GetKind() == VTrack::Wave) {
            if (tr->GetSelected() || !selectionOnly) {
               if (tr->GetChannel() == VTrack::MonoChannel)
                  mixer->MixMono((WaveTrack *) tr, t, t + deltat);
               if (tr->GetChannel() == VTrack::LeftChannel)
                  mixer->MixLeft((WaveTrack *) tr, t, t + deltat);
               if (tr->GetChannel() == VTrack::RightChannel)
                  mixer->MixRight((WaveTrack *) tr, t, t + deltat);
            }
         }
         tr = iter.Next();
      }

      sampleType *mixed = mixer->GetBuffer();

      sf_writef_short(sf, mixed, numSamples);

      t += deltat;

      if (!progress && wxGetElapsedTime(false) > 500) {

         wxString message;

         if (selectionOnly)
            message =
                wxString::
                Format(_("Exporting the selected audio as a %s file"),
                       (const char *) formatStr);
         else
            message =
                wxString::
                Format(_("Exporting the entire project as a %s file"),
                       (const char *) formatStr);

         progress =
             new wxProgressDialog(_("Export"),
                                  message,
                                  1000,
                                  parent,
                                  wxPD_CAN_ABORT |
                                  wxPD_REMAINING_TIME | wxPD_AUTO_HIDE);
      }
      if (progress) {
         cancelling =
             !progress->Update(int (((t - t0) * 1000) / (t1 - t0) + 0.5));
      }

      delete mixer;
   }

   err = sf_close(sf);

   if (err) {
      char buffer[1000];
      sf_error_str(sf, buffer, 1000);
      wxMessageBox(wxString::Format
                   (_("Error (file may not have been written): %s"),
                    buffer));
   }

#ifdef __WXMAC__

   FSSpec spec;

   wxMacFilename2FSSpec(fName, &spec);

   FInfo finfo;
   if (FSpGetFInfo(&spec, &finfo) == noErr) {
      finfo.fdType = sf_header_mactype(format & SF_FORMAT_TYPEMASK);
      finfo.fdCreator = AUDACITY_CREATOR;

      FSpSetFInfo(&spec, &finfo);
   }
#endif

   if (progress)
      delete progress;

   return true;
}