Beispiel #1
0
//BOOL OSndStreamWAV::Write(PBYTE pbData,DWORD dwNumBytes, double dUpSampleRatio, double dScale )
BOOL OSndStreamWAV::Write(PBYTE pbData,DWORD dwNumBytes )
{

	if ( sf_write_short( m_pSndFile, (short*)pbData, dwNumBytes / 2 ) == dwNumBytes )
		return TRUE;
	return FALSE;
}
int prSFWrite(struct VMGlobals *g, int numArgsPushed)
{
	PyrSlot *a, *b;

	a = g->sp - 1;
	b = g->sp;

	SNDFILE *file = (SNDFILE*)slotRawPtr(&slotRawObject(a)->slots[0]);

	if (!isKindOfSlot(b, class_rawarray)) return errWrongType;

	switch (slotRawObject(b)->obj_format) {
		case obj_int16 :
			sf_write_short(file, (short*)slotRawInt8Array(b)->b, slotRawObject(b)->size);
			break;
		case obj_int32 :
			sf_write_int(file, (int*)slotRawInt8Array(b)->b, slotRawObject(b)->size);
			break;
		case obj_float :
			sf_write_float(file, (float*)slotRawInt8Array(b)->b, slotRawObject(b)->size);
			break;
		case obj_double :
			sf_write_double(file, (double*)slotRawInt8Array(b)->b, slotRawObject(b)->size);
			break;
		default:
			error("sample format not supported.\n");
			return errFailed;
	}

	return errNone;
}
Beispiel #3
0
int main(int argc, char *argv[])
{
	printf("Wav Write Test\n");
	if (argc != 2) {
		fprintf(stderr, "Expecting wav file as argument\n");
		return 1;
	}

	short samples[len];
  	memset(samples, 0, len);
	printf("\n Getting the Samples");
	getSamples(samples);
        printf("\n Got the Samples. Writing to File\n");	
	// Write to a new file
	SF_INFO sfinfo_w ;
    	sfinfo_w.channels = 1;
    	sfinfo_w.samplerate = 16000;
    	sfinfo_w.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;
	
	SNDFILE *sndFile_w = sf_open(argv[1], SFM_WRITE, &sfinfo_w);
	sf_count_t count_w = sf_write_short(sndFile_w, samples, len) ;
    	sf_write_sync(sndFile_w);
    	sf_close(sndFile_w);

	return 0;
}
Beispiel #4
0
int CWAV::SaveDataChunk(BYTE*	pbtDataPtr, DWORD dwNumBytes)
{
	// Write chunk to disk
	return (int)sf_write_short(	m_pSndFile, 
							(SHORT*)pbtDataPtr,
							(sf_count_t)( dwNumBytes / sizeof( SHORT ) ) * sizeof( SHORT ) );
}	
Beispiel #5
0
void
writeSynthesizedVoice (dsd_opts * opts, dsd_state * state)
{
    int n;
    short aout_buf[160];
    short *aout_buf_p;

//  for(n=0; n<160; n++)
//    printf("%d ", ((short*)(state->audio_out_temp_buf))[n]);
//  printf("\n");

    aout_buf_p = aout_buf;
    state->audio_out_temp_buf_p = state->audio_out_temp_buf;

    for (n = 0; n < 160; n++)
    {
        if (*state->audio_out_temp_buf_p > (float) 32767)
        {
            *state->audio_out_temp_buf_p = (float) 32767;
        }
        else if (*state->audio_out_temp_buf_p < (float) -32768)
        {
            *state->audio_out_temp_buf_p = (float) -32768;
        }
        *aout_buf_p = (short) *state->audio_out_temp_buf_p;
        aout_buf_p++;
        state->audio_out_temp_buf_p++;
    }

    sf_write_short(opts->wav_out_f, aout_buf, 160);
    /*

    int n;
    short aout_buf[160];
    short *aout_buf_p;
    ssize_t result;

    aout_buf_p = aout_buf;
    state->audio_out_temp_buf_p = state->audio_out_temp_buf;
    for (n = 0; n < 160; n++)
      {
        if (*state->audio_out_temp_buf_p > (float) 32760)
          {
            *state->audio_out_temp_buf_p = (float) 32760;
          }
        else if (*state->audio_out_temp_buf_p < (float) -32760)
          {
            *state->audio_out_temp_buf_p = (float) -32760;
          }
        *aout_buf_p = (short) *state->audio_out_temp_buf_p;
        aout_buf_p++;
        state->audio_out_temp_buf_p++;
      }

    result = write (opts->wav_out_fd, aout_buf, 320);
    fflush (opts->wav_out_f);
    state->wav_out_bytes += 320;
    */
}
Beispiel #6
0
static void
large_free_test (const char *filename, int format, size_t chunk_size)
{	SNDFILE 		* file ;
	SF_INFO			sfinfo ;
	SF_CHUNK_INFO	chunk_info ;
	char chunk_data [20002] ;
	short audio [16] ;
	int	err ;

	print_test_name (__func__, filename) ;

	exit_if_true (sizeof (chunk_data) <= chunk_size, "\n\nLine %d : sizeof (data) < chunk_size\n\n", __LINE__) ;

	memset (chunk_data, 53, sizeof (chunk_data)) ;
	chunk_data [chunk_size] = 0 ;

	sfinfo.samplerate	= 44100 ;
	sfinfo.channels		= 1 ;
	sfinfo.frames		= 0 ;
	sfinfo.format		= format ;

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

	/* Set up the chunk to write. */
	memset (&chunk_info, 0, sizeof (chunk_info)) ;
	snprintf (chunk_info.id, sizeof (chunk_info.id), "free") ;
	chunk_info.id_size = 4 ;
	chunk_info.data = chunk_data ;
	chunk_info.datalen = chunk_size ;

	err = sf_set_chunk (file, &chunk_info) ;
	exit_if_true (
		err != SF_ERR_NO_ERROR,
		"\n\nLine %d : sf_set_chunk returned for testdata : %s\n\n", __LINE__, sf_error_number (err)
		) ;

	memset (chunk_info.data, 0, chunk_info.datalen) ;

	/* Add some audio data. */
	memset (audio, 0, sizeof (audio)) ;
	sf_write_short (file, audio, ARRAY_LEN (audio)) ;

	sf_close (file) ;

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

	exit_if_true (
		sfinfo.frames != ARRAY_LEN (audio),
		"\n\nLine %d : Incorrect sample count (%d should be %d)\n", __LINE__, (int) sfinfo.frames, (int) ARRAY_LEN (audio)
		) ;

	if (chunk_size < 512)
		check_log_buffer_or_die (file, __LINE__) ;

	sf_close (file) ;

	unlink (filename) ;
	puts ("ok") ;
} /* large_free_test */
static void
headerless_test (const char * filename, int format, int expected)
{	static	short	buffer [BUFFER_SIZE] ;
	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	int			k ;

	format &= SF_FORMAT_SUBMASK ;

	print_test_name (__func__, filename) ;

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

	sfinfo.samplerate	= 8000 ;
	sfinfo.frames		= 0 ;
	sfinfo.channels		= 1 ;
	sfinfo.format		= SF_FORMAT_RAW | format ;

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

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

	sf_close (file) ;

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

	/* We should be able to detect these so clear sfinfo. */
	memset (&sfinfo, 0, sizeof (sfinfo)) ;

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

	if (sfinfo.format != expected)
	{	printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, expected, sfinfo.format) ;
		exit (1) ;
		} ;

	if (sfinfo.frames < BUFFER_SIZE)
	{	printf ("Line %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, BUFFER_SIZE, SF_COUNT_TO_LONG (sfinfo.frames)) ;
		exit (1) ;
		} ;

	if (sfinfo.channels != 1)
	{	printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ;
		exit (1) ;
		} ;

	check_log_buffer_or_die (file, __LINE__) ;

	sf_close (file) ;

	printf ("ok\n") ;
	unlink (filename) ;
} /* headerless_test */
Beispiel #8
0
static int encode(struct aufilt_st *st, int16_t *sampv, size_t *sampc)
{
	struct sndfile_st *sf = (struct sndfile_st *)st;

	sf_write_short(sf->enc, sampv, *sampc);

	return 0;
}
// --- Write ---
bool SndFileHandler::m_write(MediumFrame *f)
{
	if (f == NULL)
		return false;

	sf_count_t written = sf_write_short(s_file, f->samples, f->len);

	return (written > 0);
}
void SoundFile::write(const Int16* data, std::size_t sampleCount)
{
    if (m_file && data && sampleCount)
    {
        // Write small chunks instead of everything at once,
        // to avoid a stack overflow in libsndfile (happens only with OGG format)
        while (sampleCount > 0)
        {
            std::size_t count = sampleCount > 10000 ? 10000 : sampleCount;
            sf_write_short(m_file, data, count);
            data += count;
            sampleCount -= count;
        }
    }
}
Beispiel #11
0
void
ags_sndfile_write(AgsPlayable *playable, signed short *buffer, guint buffer_length)
{
  AgsSndfile *sndfile;
  sf_count_t multi_frames, retval;

  sndfile = AGS_SNDFILE(playable);

  multi_frames = buffer_length * sndfile->info->channels;

  retval = sf_write_short(sndfile->file, buffer, multi_frames);

  if(retval > multi_frames){
    g_warning("retval > multi_frames");
    //    sf_seek(sndfile->file, (multi_frames - retval), SEEK_CUR);
  }
}
Beispiel #12
0
void
test_write_short_or_die (SNDFILE *file, int pass, short *test, sf_count_t items, int line_num)
{	sf_count_t count ;

	if ((count = sf_write_short (file, test, items)) != items)
	{	printf ("\n\nLine %d", line_num) ;
		if (pass > 0)
			printf (" (pass %d)", pass) ;
		printf (" : sf_write_short failed with short write (%ld => %ld).\n",
						SF_COUNT_TO_LONG (items), SF_COUNT_TO_LONG (count)) ;
		fflush (stdout) ;
		puts (sf_strerror (file)) ;
		exit (1) ;
		} ;

	return ;
} /* test_write_short */
Beispiel #13
0
int 
main (void) 
{	SNDFILE	*file ; 
	SF_INFO	sfinfo ; 
	int		k ; 
	short	*buffer ; 
	 
	if (! (buffer = malloc (2 * SAMPLE_COUNT * sizeof (short)))) 
	{	printf ("Malloc failed.\n") ; 
		exit (0) ; 
		} ; 

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

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

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

	sf_close (file) ; 
	return	 0 ; 
} /* main */ 
Beispiel #14
0
static	void	
stdout_test	(char *str, int typemajor, int count)
{	static	short	data [BUFFER_LEN] ;

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

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

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

	return ;
} /* stdout_test */
Beispiel #15
0
void
create_short_sndfile (const char *filename, int format, int channels)
{	short data [2 * 3 * 4 * 5 * 6 * 7] = { 0, } ;
	SNDFILE *file ;
	SF_INFO sfinfo ;

	sfinfo.samplerate = 44100 ;
	sfinfo.channels = channels ;
	sfinfo.format = format ;

	if ((file = sf_open (filename, SFM_WRITE, &sfinfo)) == NULL)
	{	printf ("Error (%s, %d) : sf_open failed : %s\n", __FILE__, __LINE__, sf_strerror (file)) ;
		exit (1) ;
		} ;

	sf_write_short (file, data, ARRAY_LEN (data)) ;

	sf_close (file) ;
} /* create_short_sndfile */
Beispiel #16
0
////////////////////////////////////////////////////////////
/// Sauvegarde un tableau d'�chantillons dans un fichier audio
///
/// \param Filename : Nom du fichier audio � charger
/// \param Samples :  Tableau d'�chantillons
///
////////////////////////////////////////////////////////////
void SaveSound(const std::string& Filename, const std::vector<ALshort>& Samples)
{
    // On renseigne les param�tres du fichier � cr�er
    SF_INFO FileInfos;
    FileInfos.channels   = 1;
    FileInfos.samplerate = 44100;
    FileInfos.format     = SF_FORMAT_PCM_16 | SF_FORMAT_WAV;

    // On ouvre le fichier en �criture
    SNDFILE* File = sf_open(Filename.c_str(), SFM_WRITE, &FileInfos);
    if (!File)
    {
        std::cerr << "Impossible de cr�er le fichier audio" << std::endl;
        return;
    }

    // Ecriture des �chantillons audio
    sf_write_short(File, &Samples[0], Samples.size());

    // Fermeture du fichier
    sf_close(File);
}
Beispiel #17
0
	void CaptureThread::writeAudioBufferToFile( int bufferWriteSize )
	{
		//
		//	Apply noise reduction filter
		//
//		float outputBuffer[ BUFFERSIZE ];
//		//applyNoiseReduction( outputBuffer, bufferWriteSize );


//		DaisyFilter *iirFilter = DaisyFilter::SinglePoleIIRFilter(0.3f);
//		float input = 0;
////_noiseReductionActive = true;

//		//float outBuffer[BUFFERSIZE];
//		//ALchar outBuffer[BUFFERSIZE];
//		QByteArray* outBuffer= new QByteArray( _buffer, BUFFERSIZE );
		
//		//for( int i = 0; i < bufferWriteSize ; i++ )
//		//{
//		//	//outBuffer[i] = (float)_buffer[i];
//		//	float aux = (short)_buffer[i]; // Cast to float directly doesn't convert correctly
//		//	if( _noiseReductionActive )
//		//	{
//		//		//outBuffer[i] = iirFilter->Calculate( aux );
//		//	}
//		//	else
//		//	{
//		//		outBuffer[i] = aux;
//		//	}
//		//}
#if defined( __WIN32__ ) || defined( _WIN32 )
		fwrite( _buffer, bufferWriteSize, 1, _pFile );
//		fwrite( *outBuffer, bufferWriteSize, 1, _pFile );
//		_bufferList.append( outBuffer );
#else
                sf_write_short( _pFile, (short *)_buffer, BUFFERSIZE );
#endif
		emit signalSampleCaptured();
	}
Beispiel #18
0
sf_count_t WriteWaveFile::WriteShort(short *ptr, sf_count_t items)
{
  return (sf_write_short(sffile, ptr, items));
}
Beispiel #19
0
static void
wav_subchunk_test (size_t chunk_size)
{	SNDFILE 		* file ;
	SF_INFO			sfinfo ;
	SF_CHUNK_INFO	chunk_info ;
	char filename [256] ;
	char chunk_data [10240] ;
	short audio [16] ;
	int	err, value ;

	snprintf (filename, sizeof (filename), "subchunk_%04d.wav", (int) chunk_size) ;
	print_test_name (__func__, filename) ;

	exit_if_true (sizeof (chunk_data) < chunk_size, "\n\nLine %d : sizeof (data) < chunk_size\n\n", __LINE__) ;

	memset (chunk_data, 53, sizeof (chunk_data)) ;
	chunk_data [chunk_size] = 0 ;

	/* Fill in the chunk data. */
	value = MAKE_MARKER ('a', 'd', 't', 'l') ;
	memcpy (chunk_data, &value, sizeof (value)) ;
	value = MAKE_MARKER ('n', 'o', 't', 'e') ;
	memcpy (chunk_data + 4, &value, sizeof (value)) ;
	value = H2LE_32 (chunk_size - 12) ;
	memcpy (chunk_data + 8, &value, sizeof (value)) ;

	sfinfo.samplerate	= 44100 ;
	sfinfo.channels		= 1 ;
	sfinfo.frames		= 0 ;
	sfinfo.format		= SF_FORMAT_WAV | SF_FORMAT_PCM_16 ;

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

	/* Set up the chunk to write. */
	memset (&chunk_info, 0, sizeof (chunk_info)) ;
	snprintf (chunk_info.id, sizeof (chunk_info.id), "LIST") ;
	chunk_info.id_size = 4 ;
	chunk_info.data = chunk_data ;
	chunk_info.datalen = chunk_size ;

	err = sf_set_chunk (file, &chunk_info) ;
	exit_if_true (
		err != SF_ERR_NO_ERROR,
		"\n\nLine %d : sf_set_chunk returned for testdata : %s\n\n", __LINE__, sf_error_number (err)
		) ;

	memset (chunk_info.data, 0, chunk_info.datalen) ;

	/* Add some audio data. */
	memset (audio, 0, sizeof (audio)) ;
	sf_write_short (file, audio, ARRAY_LEN (audio)) ;

	sf_close (file) ;

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

	exit_if_true (
		sfinfo.frames != ARRAY_LEN (audio),
		"\n\nLine %d : Incorrect sample count (%d should be %d)\n", __LINE__, (int) sfinfo.frames, (int) ARRAY_LEN (audio)
		) ;

	if (chunk_size < 512)
		check_log_buffer_or_die (file, __LINE__) ;

	sf_close (file) ;

	unlink (filename) ;
	puts ("ok") ;
} /* wav_subchunk_test */
static void
old_test (void)
{	static	short	buffer [BUFFER_SIZE] ;
	SNDFILE		*file ;
	SF_INFO		sfinfo ;
	int			k, filetype ;
	const char	*filename = "headerless.wav" ;

	print_test_name (__func__, "") ;

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

	filetype = SF_FORMAT_WAV | SF_FORMAT_PCM_16 ;

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

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

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

	sf_close (file) ;

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

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

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

	if (sfinfo.format != filetype)
	{	printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, filetype, sfinfo.format) ;
		exit (1) ;
		} ;

	if (sfinfo.frames < BUFFER_SIZE)
	{	printf ("Line %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, BUFFER_SIZE, SF_COUNT_TO_LONG (sfinfo.frames)) ;
		exit (1) ;
		} ;

	if (sfinfo.channels != 1)
	{	printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ;
		exit (1) ;
		} ;

	check_log_buffer_or_die (file, __LINE__) ;

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

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

	sf_close (file) ;

	printf ("ok\n") ;
	unlink (filename) ;
} /* old_test */
Beispiel #21
0
int main(int argc, char *argv[]) {

    if(alcIsExtensionPresent(NULL, "ALC_SOFT_loopback") == ALC_FALSE) {
        fputs("Your OpenAL implementation doesn't support the "
              "\"ALC_SOFT_loopback\" extension, required for this test. "
              "Sorry.\n", stderr);
        exit(EXIT_FAILURE);
    }
    ALCint alc_major, alc_minor;
    alcGetIntegerv(NULL, ALC_MAJOR_VERSION, 1, &alc_major);
    alcGetIntegerv(NULL, ALC_MINOR_VERSION, 1, &alc_minor);
    if(alc_major<1 || (alc_major==1 && alc_minor<1))
        fputs("Warning : ALC_SOFT_loopback has been written against "
              "the OpenAL 1.1 specification.\n", stderr);

#define HELPER(X) X = alcGetProcAddress(NULL, #X)
    HELPER(alcLoopbackOpenDeviceSOFT);
    HELPER(alcIsRenderFormatSupportedSOFT);
    HELPER(alcRenderSamplesSOFT);
#undef  HELPER
#define HELPER(X) X = alcGetEnumValue(NULL, #X)
    HELPER(ALC_BYTE_SOFT);
    HELPER(ALC_UNSIGNED_BYTE_SOFT);
    HELPER(ALC_SHORT_SOFT);
    HELPER(ALC_UNSIGNED_SHORT_SOFT);
    HELPER(ALC_INT_SOFT);
    HELPER(ALC_UNSIGNED_INT_SOFT);
    HELPER(ALC_FLOAT_SOFT);
    HELPER(ALC_MONO_SOFT);
    HELPER(ALC_STEREO_SOFT);
    HELPER(ALC_QUAD_SOFT);
    HELPER(ALC_5POINT1_SOFT);
    HELPER(ALC_6POINT1_SOFT);
    HELPER(ALC_7POINT1_SOFT);
    HELPER(ALC_FORMAT_CHANNELS_SOFT);
    HELPER(ALC_FORMAT_TYPE_SOFT);
#undef  HELPER

    ALCdevice *loopback_device = alcLoopbackOpenDeviceSOFT(NULL);
    if(!loopback_device) {
        fputs("Could not open loopback device.\n", stderr);
        exit(EXIT_FAILURE);
    }
    if(alcIsRenderFormatSupportedSOFT(loopback_device, 
            22050, ALC_STEREO_SOFT, ALC_SHORT_SOFT) == ALC_FALSE) 
    {
        fputs("The loopback device does not support the "
              "required render format.\n", stderr);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }

    ALCint attrlist[11] = {
        ALC_MONO_SOURCES, 0,
        ALC_STEREO_SOURCES, 255,
        ALC_FREQUENCY, 22050,
        ALC_FORMAT_CHANNELS_SOFT, ALC_STEREO_SOFT,
        ALC_FORMAT_TYPE_SOFT, ALC_SHORT_SOFT,
        0
    };
    ALCcontext *ctx = alcCreateContext(loopback_device, attrlist);
    alcMakeContextCurrent(ctx);
    alGetError(); /* Clear the error state */

    if(argc<=1) {
        fprintf(stderr, "Usage : %s <small_oggfile>\n", argv[0]);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }

    SF_INFO sndinfo;
    SNDFILE *snd = sf_open(argv[1], SFM_READ, &sndinfo);
    if(!snd) {
        fprintf(stderr, "Failed to open \"%s\" : %s\n", 
                argv[1], sf_strerror(snd));
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }
    if(sndinfo.channels != 2) {
        fprintf(stderr, "The source sound file has %d channels "
                "(exactly 2 are required).\n", sndinfo.channels);
        alcCloseDevice(loopback_device);
        exit(EXIT_FAILURE);
    }
    short *data = malloc(sndinfo.frames*2*sizeof(short));
    printf("Reading from '%s'...\n", argv[1]);
    sf_readf_short(snd, data, sndinfo.frames);
    sf_close(snd);

    ALuint audio_buffer;
    alGenBuffers(1, &audio_buffer);
    alBufferData(audio_buffer, AL_FORMAT_STEREO16, data,
            sndinfo.frames*2*sizeof(short), sndinfo.samplerate);
    free(data);

    ALuint audio_source;
    alGenSources(1, &audio_source);
    alSourcei(audio_source, AL_BUFFER, audio_buffer);

    unsigned num_frames = sndinfo.frames;
    ALCshort *rendered_samples = malloc(num_frames*2*sizeof(ALCshort));
    sndinfo.samplerate = 22050;
    sndinfo.channels = 2;
    sndinfo.format = SF_FORMAT_OGG | SF_FORMAT_VORBIS | SF_ENDIAN_FILE;
    snd = sf_open("rendered.ogg", SFM_WRITE, &sndinfo);

    alSourcePlay(audio_source);

    puts("Rendering frames...");
    unsigned chunk_size = 4096, off;
    for(off=0 ; off<(num_frames-chunk_size)*2 ; off+=2*chunk_size)
        alcRenderSamplesSOFT(loopback_device, rendered_samples+off, chunk_size);

    puts("Writing to 'rendered.ogg'...");
    sf_write_short(snd, rendered_samples, off-s);
    sf_close(snd);
    free(rendered_samples);

    alDeleteSources(1, &audio_source);
    alDeleteBuffers(1, &audio_buffer);
    alcCloseDevice(loopback_device);
    alcMakeContextCurrent(NULL);
    alcDestroyContext(ctx);

    exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
	SNDFILE* sndfile = NULL;
	SF_INFO sfinfo;
	mpg123_handle *mh = NULL;
	unsigned char* buffer = NULL;
	size_t buffer_size = 0;
	size_t done = 0;
	int  channels = 0, encoding = 0;
	long rate = 0;
	int  err  = MPG123_OK;
	off_t samples = 0;

	if (argc!=3) usage();
	printf( "Input file: %s\n", argv[1]);
	printf( "Output file: %s\n", argv[2]);
	
	err = mpg123_init();
	if( err != MPG123_OK || (mh = mpg123_new(NULL, &err)) == NULL
	    /* Let mpg123 work with the file, that excludes MPG123_NEED_MORE messages. */
	    || mpg123_open(mh, argv[1]) != MPG123_OK
	    /* Peek into track and get first output format. */
	    || mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK )
	{
		fprintf( stderr, "Trouble with mpg123: %s\n",
		         mh==NULL ? mpg123_plain_strerror(err) : mpg123_strerror(mh) );
		cleanup(mh);
		return -1;
	}

	if(encoding != MPG123_ENC_SIGNED_16)
	{ /* Signed 16 is the default output format anyways; it would actually by only different if we forced it.
	     So this check is here just for this explanation. */
		cleanup(mh);
		fprintf(stderr, "Bad encoding: 0x%x!\n", encoding);
		return -2;
	}
	/* Ensure that this output format will not change (it could, when we allow it). */
	mpg123_format_none(mh);
	mpg123_format(mh, rate, channels, encoding);

	/* Buffer could be almost any size here, mpg123_outblock() is just some recommendation.
	   Important, especially for sndfile writing, is that the size is a multiple of sample size. */
	buffer_size = mpg123_outblock( mh );
	buffer = malloc( buffer_size );

	bzero(&sfinfo, sizeof(sfinfo) );
	sfinfo.samplerate = rate;
	sfinfo.channels = channels;
	sfinfo.format = SF_FORMAT_WAV|SF_FORMAT_PCM_16;
	printf("Creating 16bit WAV with %i channels and %liHz.\n", channels, rate);

	sndfile = sf_open(argv[2], SFM_WRITE, &sfinfo);
	if(sndfile == NULL){ fprintf(stderr, "Cannot open output file!\n"); cleanup(mh); return -2; }

	do
	{
		err = mpg123_read( mh, buffer, buffer_size, &done );
		sf_write_short( sndfile, (short*)buffer, done/sizeof(short) );
		samples += done/sizeof(short);
		/* We are not in feeder mode, so MPG123_OK, MPG123_ERR and MPG123_NEW_FORMAT are the only possibilities.
		   We do not handle a new format, MPG123_DONE is the end... so abort on anything not MPG123_OK. */
	} while (err==MPG123_OK);

	if(err != MPG123_DONE)
	fprintf( stderr, "Warning: Decoding ended prematurely because: %s\n",
	         err == MPG123_ERR ? mpg123_strerror(mh) : mpg123_plain_strerror(err) );

	sf_close( sndfile );

	samples /= channels;
	printf("%li samples written.\n", (long)samples);
	cleanup(mh);
	return 0;
}
Beispiel #23
0
int main(int argc, char *argv[])
{
	SNDFILE* sndfile = NULL;
	SF_INFO sfinfo;
	mpg123_handle *mh = NULL;
	unsigned char* buffer = NULL;
	size_t buffer_size = 0;
	size_t done = 0;
	int  channels = 0, encoding = 0;
	long rate = 0;
	int  err  = MPG123_OK;
	off_t samples = 0;

	if (argc<3) usage();
	printf( "Input file: %s\n", argv[1]);
	printf( "Output file: %s\n", argv[2]);
	
	err = mpg123_init();
	if(err != MPG123_OK || (mh = mpg123_new(NULL, &err)) == NULL)
	{
		fprintf(stderr, "Basic setup goes wrong: %s", mpg123_plain_strerror(err));
		cleanup(mh);
		return -1;
	}

	/* Simple hack to enable floating point output. */
	if(argc >= 4 && !strcmp(argv[3], "f32")) mpg123_param(mh, MPG123_ADD_FLAGS, MPG123_FORCE_FLOAT, 0.);

	    /* Let mpg123 work with the file, that excludes MPG123_NEED_MORE messages. */
	if(    mpg123_open(mh, argv[1]) != MPG123_OK
	    /* Peek into track and get first output format. */
	    || mpg123_getformat(mh, &rate, &channels, &encoding) != MPG123_OK )
	{
		fprintf( stderr, "Trouble with mpg123: %s\n", mpg123_strerror(mh) );
		cleanup(mh);
		return -1;
	}

	if(encoding != MPG123_ENC_SIGNED_16 && encoding != MPG123_ENC_FLOAT_32)
	{ /* Signed 16 is the default output format anyways; it would actually by only different if we forced it.
	     So this check is here just for this explanation. */
		cleanup(mh);
		fprintf(stderr, "Bad encoding: 0x%x!\n", encoding);
		return -2;
	}
	/* Ensure that this output format will not change (it could, when we allow it). */
	mpg123_format_none(mh);
	mpg123_format(mh, rate, channels, encoding);

	bzero(&sfinfo, sizeof(sfinfo) );
	sfinfo.samplerate = rate;
	sfinfo.channels = channels;
	sfinfo.format = SF_FORMAT_WAV|(encoding == MPG123_ENC_SIGNED_16 ? SF_FORMAT_PCM_16 : SF_FORMAT_FLOAT);
	printf("Creating WAV with %i channels and %liHz.\n", channels, rate);

	sndfile = sf_open(argv[2], SFM_WRITE, &sfinfo);
	if(sndfile == NULL){ fprintf(stderr, "Cannot open output file!\n"); cleanup(mh); return -2; }

	/* Buffer could be almost any size here, mpg123_outblock() is just some recommendation.
	   Important, especially for sndfile writing, is that the size is a multiple of sample size. */
	buffer_size = argc >= 5 ? atol(argv[4]) : mpg123_outblock(mh);
	buffer = malloc( buffer_size );

	do
	{
		sf_count_t more_samples;
		err = mpg123_read( mh, buffer, buffer_size, &done );
		more_samples = encoding == MPG123_ENC_SIGNED_16
			? sf_write_short(sndfile, (short*)buffer, done/sizeof(short))
			: sf_write_float(sndfile, (float*)buffer, done/sizeof(float));
		if(more_samples < 0 || more_samples*mpg123_encsize(encoding) != done)
		{
			fprintf(stderr, "Warning: Written number of samples does not match the byte count we got from libmpg123: %li != %li\n", (long)(more_samples*mpg123_encsize(encoding)), (long)done);
		}
		samples += more_samples;
		/* We are not in feeder mode, so MPG123_OK, MPG123_ERR and MPG123_NEW_FORMAT are the only possibilities.
		   We do not handle a new format, MPG123_DONE is the end... so abort on anything not MPG123_OK. */
	} while (err==MPG123_OK);

	if(err != MPG123_DONE)
	fprintf( stderr, "Warning: Decoding ended prematurely because: %s\n",
	         err == MPG123_ERR ? mpg123_strerror(mh) : mpg123_plain_strerror(err) );

	sf_close( sndfile );

	samples /= channels;
	printf("%li samples written.\n", (long)samples);
	cleanup(mh);
	return 0;
}
static void
vio_test (const char *fname, int format)
{	static VIO_DATA vio_data ;
	static short data [256] ;

	SF_VIRTUAL_IO vio ;
	SNDFILE * file ;
	SF_INFO sfinfo ;

	print_test_name ("virtual i/o test", fname) ;

	/* Set up pointers to the locally defined functions. */
	vio.get_filelen = vfget_filelen ;
	vio.seek = vfseek ;
	vio.read = vfread ;
	vio.write = vfwrite ;
	vio.tell = vftell ;

	/* Set virtual file offset and length to zero. */
	vio_data.offset = 0 ;
	vio_data.length = 0 ;

	memset (&sfinfo, 0, sizeof (sfinfo)) ;
	sfinfo.format = format ;
	sfinfo.channels = 2 ;
	sfinfo.samplerate = 44100 ;

	if ((file = sf_open_virtual (&vio, SFM_WRITE, &sfinfo, &vio_data)) == NULL)
	{	printf ("\n\nLine %d : sf_open_write failed with error : ", __LINE__) ;
		fflush (stdout) ;
		puts (sf_strerror (NULL)) ;
		exit (1) ;
		} ;

	if (vfget_filelen (&vio_data) < 0)
	{	printf ("\n\nLine %d : vfget_filelen returned negative length.\n\n", __LINE__) ;
		exit (1) ;
		} ;

	gen_short_data (data, ARRAY_LEN (data), 0) ;
	sf_write_short (file, data, ARRAY_LEN (data)) ;

	gen_short_data (data, ARRAY_LEN (data), 1) ;
	sf_write_short (file, data, ARRAY_LEN (data)) ;

	gen_short_data (data, ARRAY_LEN (data), 2) ;
	sf_write_short (file, data, ARRAY_LEN (data)) ;

	sf_close (file) ;

	/* Now test read. */
	memset (&sfinfo, 0, sizeof (sfinfo)) ;

	vio_data.offset = 0 ;

	if ((file = sf_open_virtual (&vio, SFM_READ, &sfinfo, &vio_data)) == NULL)
	{	printf ("\n\nLine %d : sf_open_write failed with error : ", __LINE__) ;
		fflush (stdout) ;
		puts (sf_strerror (NULL)) ;

		dump_data_to_file (fname, vio_data.data, vio_data.length) ;
		exit (1) ;
		} ;


	sf_read_short (file, data, ARRAY_LEN (data)) ;
	check_short_data (data, ARRAY_LEN (data), 0, __LINE__) ;

	sf_read_short (file, data, ARRAY_LEN (data)) ;
	check_short_data (data, ARRAY_LEN (data), 1, __LINE__) ;

	sf_read_short (file, data, ARRAY_LEN (data)) ;
	check_short_data (data, ARRAY_LEN (data), 2, __LINE__) ;

	sf_close (file) ;

	puts ("ok") ;
} /* vio_test */
Beispiel #25
0
	void CaptureThread::stopCapture()
	{
		qDebug() << "[CaptureThread::stopCapture()]";
		if( _pCaptureDevice && _capturing )
		{
			//
			// Stop capture
			//
			_capturing = false;
			_captureMutex.lock();
			alcCaptureStop( _pCaptureDevice );

			//
			// Check if any Samples haven't been consumed yet
			//
			alcGetIntegerv( _pCaptureDevice, ALC_CAPTURE_SAMPLES, 1, &_iSamplesAvailable) ;
#if defined( __WIN32__ ) || defined( _WIN32 )
			int sampleSize = BUFFERSIZE / _sWaveHeader.wfex.nBlockAlign;
#else
                        int sampleSize = BUFFERSIZE / _nBlockAlign;
#endif
			while( _iSamplesAvailable )
			{
#if defined( __WIN32__ ) || defined( _WIN32 )
				if( _iSamplesAvailable > ( sampleSize ) )
				{
					alcCaptureSamples( _pCaptureDevice, _buffer, sampleSize );
					//
					//	Write to file
					//
					writeAudioBufferToFile( BUFFERSIZE );
					//fwrite( outputBuffer, BUFFERSIZE, 1, _pFile );
					//fwrite( _buffer, BUFFERSIZE, 1, _pFile );
					_iSamplesAvailable -= sampleSize;
					_iDataSize += BUFFERSIZE;
				}
				else
				{
					qDebug() << "[CaptureThread::stopCapture()]"<< " ----------- last sample size: " << _iSamplesAvailable;
					alcCaptureSamples(_pCaptureDevice, _buffer, _iSamplesAvailable);
					//
					//	Write to file
					//
					int writeSize = _iSamplesAvailable * _sWaveHeader.wfex.nBlockAlign;
					writeAudioBufferToFile( writeSize );
					//fwrite(_buffer, _iSamplesAvailable * _sWaveHeader.wfex.nBlockAlign, 1, _pFile);
					_iDataSize += writeSize;
					_iSamplesAvailable = 0;
				}
#else
				if( _iSamplesAvailable > sampleSize )
				{
					alcCaptureSamples( _pCaptureDevice, _buffer, sampleSize );					
					sf_write_short( _pFile, (short *)_buffer, BUFFERSIZE );
					_iSamplesAvailable -= sampleSize;
					_iDataSize += BUFFERSIZE;
				}
				else
				{
					sf_write_short( _pFile, (short *)_buffer, BUFFERSIZE);
					_iDataSize += _iSamplesAvailable * _nBlockAlign;
					_iSamplesAvailable = 0;
				}
#endif
			}

			_captureMutex.unlock();

#if defined( __WIN32__ ) || defined( _WIN32 )
			// Fill in Size information in Wave Header
			fseek( _pFile, 4, SEEK_SET );
			_iSize = _iDataSize + sizeof(WAVEHEADER) - 8;
			fwrite(&_iSize, 4, 1, _pFile);
			fseek(_pFile, 42, SEEK_SET);
			fwrite(&_iDataSize, 4, 1, _pFile);

			fclose( _pFile );
#else
			sf_close( _pFile ) ;
			terminate();
#endif
			emit signalCaptureEnded();
			emit captureVolume( 0 );
		}
	}
		int WriteToFile() {
			return sf_write_short(sf, &(readbuf[0]), num_samples);
		}
static	
void	lossy_comp_test_short (char *str, char *filename, int typemajor, int typeminor, double margin)
{	SNDFILE			*file ;
	SF_INFO			sfinfo ;
	int				k, m, seekpos ;
	unsigned int	datalen ;
	short			*orig, *data ;

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

	orig = (short*) orig_buffer ;
	data = (short*) test_buffer ;
	gen_signal (orig_buffer, datalen) ;
	for (k = 0 ; k < datalen ; k++)
		orig [k] = (short) (orig_buffer [k]) ;
		
	sfinfo.samplerate  = 11025 ;
	sfinfo.samples     = 123456789 ;	/* Ridiculous value. */
	sfinfo.channels    = 1 ;
	sfinfo.pcmbitwidth = 16 ;
	sfinfo.format 	   = (typemajor | typeminor) ;

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

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

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

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

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

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

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

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

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

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

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

	sf_close (file) ;

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

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

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

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

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

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

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

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

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

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

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


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

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

	return 0;
} /* main */
Beispiel #29
0
int extract(const char * p_filename)
{
	MODULE * module;
	int i;
	signed short ** s = NULL;
	
 	module = Player_Load(p_filename, 64, 0);
	if (!module) {
		printf("Player_Load: %s\n", MikMod_strerror(MikMod_errno));
		return 1;
	}

	printf("Filename:        %s\n",    p_filename);
	printf("Songname:        %s\n",    module->songname);
	printf("No. of channels: %d\n",    module->numchn);
	printf("No. of insts:    %d\n",    module->numins);
	printf("No. of samps:    %d\n",    module->numsmp);
	
	// Init MikMod Interop
	printf("SampleExIOP:     ");
	
	s = VC1_GetSamples();
	if(!s) {
		s = VC2_GetSamples();
		if(!s) {
			printf("Error\n");
			return 2;
		}
		printf("VC2 (HQ)\n");
	} else {
		printf("VC1 (Default)\n");
	}
	
	printf("Saving Samples ...\n");
	for(i = 0; i < module->numsmp; i++) {
		char fn[256];
		SF_INFO sfi;
		SNDFILE * sf;
				
		if(!module->samples[i].length) continue;
				
		sprintf(fn, "%02d.wav", i);
		
		memset(&sfi, 0, sizeof(SF_INFO));
		sfi.samplerate = 22500;
		sfi.channels = module->samples[i].flags & SF_STEREO ? 2 : 1;
		sfi.format = SF_FORMAT_WAV;
		if(module->samples[i].flags & SF_16BITS) {
			sfi.format |= SF_FORMAT_PCM_16;
		} else {
			sfi.format |= SF_FORMAT_PCM_S8;
		}
		
		sf = sf_open(fn, SFM_WRITE, &sfi);
		
		sf_write_short(sf, s[module->samples[i].handle], (int)module->samples[i].length);
		
		sf_close(sf);
		
		printf("%03d: %-40s (%06d nsmps [* = %p]) | %02d | %c | %s | %s\n", 
			i, 
			module->samples[i].samplename, 
			(int)module->samples[i].length, 
			s[module->samples[i].handle],
			module->samples[i].flags & SF_16BITS     ? 16 : 8,
			module->samples[i].flags & SF_STEREO     ? 'S' : 'M', 
			module->samples[i].flags & SF_BIG_ENDIAN ? "BE" : "LE",
			module->samples[i].flags & SF_LOOP       ? "Loop" : "NoLoop");
		
		/**
		 * Test RAW Output
		 
		int j;
		FILE * f;
		char fn[256];
				
		sprintf(fn, "%02d.raw", i);
		f = fopen(fn, "wb");
		for(j = 0; j < module->samples[i].length; j++) {
			if(module->samples[i].inflags & SF_16BITS) {
				signed short * sss = (signed short *)s[module->samples[i].handle];
				
				if(module->samples[i].inflags & SF_STEREO) {
					fwrite(&sss[j], 2, 1, f);
				} else {
					fwrite(&sss[j], 1, 1, f);
				}
			} else {
				signed char * ssc = (signed char *)s[module->samples[i].handle];
				
				fwrite(&ssc[(j * 2)+1], 1, 1, f);
				if(module->samples[i].inflags & SF_STEREO) {
					j++;
					fwrite(&ssc[(j * 2)+1], 1, 1, f);
				}
			}
		}
		fclose(f);
		 */
		 
		
	}
	
	
	Player_Free(module);
	
	
	return 0;
}
Beispiel #30
0
void cued_rip_to_file(rip_context_t *rip)
{
    SF_INFO sfinfo;
    PIT(SNDFILE, sfObj);
    PIT(int16_t, pbuf);
    lsn_t currSector, offsetSectors;
    int wordsToWrite, wordsWritten, i;

    int offsetWords = rip->offsetWords;
    track_t track = rip->currentTrack;

    memset(&sfinfo, 0x00, sizeof(sfinfo));
    sfinfo.samplerate = 44100;
    sfinfo.channels = rip->channels;
    sfinfo.format = SF_FORMAT_PCM_16 | rip->soundFileFormat;

    offsetSectors = offsetWords / CD_FRAMEWORDS;
    rip->firstSector += offsetSectors;
    rip->lastSector  += offsetSectors;
    offsetWords %= CD_FRAMEWORDS;

    if (offsetWords < 0) {
        rip->firstSector -= 1;
    } else if (offsetWords > 0) {
        rip->lastSector  += 1;
    }
    // else offsetWords is zero b/c the offset fell on a sector boundary

    currSector = rip->firstSector;

#ifdef CUED_HAVE_PARANOIA

    if (ripUseParanoia) {
        lsn_t seekSector, prc;

        if (currSector < 0 && !ripReadPregap) {
            seekSector = 0;
        } else {
            seekSector = currSector;
        }

        // TODO:  paranoia has a problem with reading leadout
        if (seekSector < rip->endOfDiscSector) {
            prc = cdio_paranoia_seek(rip->paranoiaRipObj, seekSector, SEEK_SET);
            cdio2_paranoia_msg(rip->paranoiaCtlObj, "paranoia seek");
            if (-1 == prc) {
                cdio_error("paranoia returned \"%d\" during seek to \"%d\"; skipping track %02d", prc, seekSector, track);

                return;
            }
        }
    }

#endif // CUED_HAVE_PARANOIA

    if (ripExtract) {

        // does not return on error
        (void) format_get_file_path(rip->cdObj, rip->cddbObj,
            rip->fileNamePattern, cued_fmt_to_ext(rip->soundFileFormat), track,
            rip->fileNameBuffer, rip->bufferSize
            );

        sfObj = sf_open(rip->fileNameBuffer, SFM_WRITE, &sfinfo);
        if (!sfObj) {
            cdio_error("sf_open(\"%s\") returned \"%s\"; skipping extraction of track %02d", rip->fileNameBuffer, sf_strerror(sfObj), track);

            return;
        }
    }

    for (;  currSector <= rip->lastSector;  ++currSector) {

        if ((currSector < 0 && !ripReadPregap) || (currSector >= rip->endOfDiscSector && !ripReadLeadout)) {

            // N.B.  assume that if mmcBuf is not NULL, it is >= sizeof(audio_buffer_t)
            if (!rip->mmcBuf) {

                // use twice the audio_buffer_t size for reading 1 sector;
                // this should accomodate any extra headers/sub-channel data
                // requested later in the normal read path
                //
                rip->mmcBuf = (uint8_t *) malloc(2 * sizeof(audio_buffer_t));
                if (rip->mmcBuf) {
                    rip->allocatedSectors = 1;
                } else {
                    cdio2_abort("out of memory allocating overread sector");
                }
            }

            memset(rip->mmcBuf, 0x00, sizeof(audio_buffer_t));
            pbuf = (int16_t *) rip->mmcBuf;

        } else {

            // TODO:  need to update track indices on skip of sector (continue)

            if (ripUseParanoia) {

#ifdef CUED_HAVE_PARANOIA

                pbuf = cdio_paranoia_read_limited(rip->paranoiaRipObj, cdio2_paranoia_callback, rip->retries);
                cdio2_paranoia_msg(rip->paranoiaCtlObj, "read of audio sector");
                if (!pbuf) {
                    cdio_error("paranoia did not return data; skipping extraction of audio sector %d in track %02d", currSector, track);
                    continue;
                }

#endif // CUED_HAVE_PARANOIA

            } else {
                if (DRIVER_OP_SUCCESS == cued_read_audio(rip, currSector, 1, NULL, rip->retries)) {
                    pbuf = (int16_t *) rip->mmcBuf;
                } else {
                    continue;
                }
            }
        }

        wordsToWrite = CD_FRAMEWORDS;

        // N.B. firstSector == lastSector is not possible if offsetWords is non-zero
        //
        if (rip->firstSector == currSector) {
            if (offsetWords < 0) {
                pbuf += CD_FRAMEWORDS + offsetWords;
                wordsToWrite  = -offsetWords;
            } else if (offsetWords > 0) {
                pbuf += offsetWords;
                wordsToWrite -= offsetWords;
            }
        } else if (rip->lastSector == currSector) {
            if (offsetWords < 0) {
                wordsToWrite += offsetWords;
            } else if (offsetWords > 0) {
                wordsToWrite  = offsetWords;    
            }
        }

        if (ripExtract) {
            wordsWritten = sf_write_short(sfObj, pbuf, wordsToWrite);
            if (wordsWritten != wordsToWrite) {

                // probably out of disk space, which is bad, because most things rely on it
                cdio2_abort("failed to write to file \"%s\" due to \"%s\"", rip->fileNameBuffer, sf_strerror(sfObj));
            }
        }

        if (!track && !ripNoisyPregap) {
            for (i = 0;  i < wordsToWrite;  ++i) {
                if (pbuf[i]) {
                    SETF(RIP_F_NOISY_PREGAP, rip->flags);
                    break;
                }
            }
        }
    }

    if (!track && !ripNoisyPregap) {
        SETF(RIP_F_SILENT_PREGAP, rip->flags);
    }

    if (ripExtract) {
        sf_close(sfObj);
    }
}