// ---------------------------------------------------------------------------- bool ofOpenALSoundPlayer::sfReadFile(string path, vector<short> & buffer, vector<float> & fftAuxBuffer){ SF_INFO sfInfo; SNDFILE* f = sf_open(path.c_str(),SFM_READ,&sfInfo); if(!f){ ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer: couldnt read " + path); return false; } buffer.resize(sfInfo.frames*sfInfo.channels); fftAuxBuffer.resize(sfInfo.frames*sfInfo.channels); int subformat = sfInfo.format & SF_FORMAT_SUBMASK ; if (subformat == SF_FORMAT_FLOAT || subformat == SF_FORMAT_DOUBLE){ double scale ; sf_command (f, SFC_CALC_SIGNAL_MAX, &scale, sizeof (scale)) ; if (scale < 1e-10) scale = 1.0 ; else scale = 32700.0 / scale ; sf_count_t samples_read = sf_read_float (f, &fftAuxBuffer[0], fftAuxBuffer.size()); if(samples_read<(int)fftAuxBuffer.size()) ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer: couldnt read " + path); for (int i = 0 ; i < int(fftAuxBuffer.size()) ; i++){ fftAuxBuffer[i] *= scale ; buffer[i] = 32565.0 * fftAuxBuffer[i]; } }else{ sf_count_t frames_read = sf_readf_short(f,&buffer[0],sfInfo.frames); if(frames_read<sfInfo.frames){ ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer: couldnt read buffer for " + path); return false; } sf_seek(f,0,SEEK_SET); frames_read = sf_readf_float(f,&fftAuxBuffer[0],sfInfo.frames); if(frames_read<sfInfo.frames){ ofLog(OF_LOG_ERROR,"ofOpenALSoundPlayer: couldnt read fft buffer for " + path); return false; } } sf_close(f); channels = sfInfo.channels; duration = float(sfInfo.frames) / float(sfInfo.samplerate); samplerate = sfInfo.samplerate; return true; }
void dump_log_buffer (SNDFILE *file) { static char buffer [LOG_BUFFER_SIZE] ; int count ; memset (buffer, 0, LOG_BUFFER_SIZE) ; /* Get the log buffer data. */ count = sf_command (file, SFC_GET_LOG_INFO, buffer, LOG_BUFFER_SIZE) ; if (strlen (buffer) < 1) puts ("Log buffer empty.\n") ; else puts (buffer) ; return ; } /* dump_log_buffer */
std::string AudioFileSndfile::sndfileError(int errorNumber, const std::string& userMessage) const { const std::string libraryMessage = sf_error_number(errorNumber); char logInfo[LOGINFO_MAX_SIZE]; sf_command(_handle.get(), SFC_GET_LOG_INFO, logInfo, LOGINFO_MAX_SIZE); LOG(INFO, "Library error detailed information" << "\n\n" << "Sound file: " << _path << '\n' << "Library reports: " << libraryMessage << '\n' << "Library version: " << sf_version_string() << '\n' << "Library log follows:\n" << logInfo); return userMessage + ": " + libraryMessage; }
static void usage_exit (const char *progname) { char lsf_ver [128] ; const char *cptr ; int k ; if ((cptr = strrchr (progname, '/')) != NULL) progname = cptr + 1 ; if ((cptr = strrchr (progname, '\\')) != NULL) progname = cptr + 1 ; sf_command (NULL, SFC_GET_LIB_VERSION, lsf_ver, sizeof (lsf_ver)) ; printf ("\n" " A Sample Rate Converter using libsndfile for file I/O and Secret \n" " Rabbit Code (aka libsamplerate) for performing the conversion.\n" " It works on any file format supported by libsndfile with any \n" " number of channels (limited only by host memory).\n" "\n" " %s\n" " %s\n" "\n" " Usage : \n" " %s -to <new sample rate> [-c <number>] <input file> <output file>\n" " %s -by <amount> [-c <number>] <input file> <output file>\n" "\n", src_get_version (), lsf_ver, progname, progname) ; puts ( " The optional -c argument allows the converter type to be chosen from\n" " the following list :" "\n" ) ; for (k = 0 ; (cptr = src_get_name (k)) != NULL ; k++) printf (" %d : %s%s\n", k, cptr, k == DEFAULT_CONVERTER ? " (default)" : "") ; puts ("\n" " The --no-normalize option disables clipping check and normalization.") ; puts ("") ; exit (1) ; } /* usage_exit */
int main (int argc, char *argv []) { SNDFILE *file ; SF_INFO sfinfo ; SF_BROADCAST_INFO_2K binfo ; const char *progname ; const char * filename = NULL ; int start ; /* Store the program name. */ progname = program_name (argv [0]) ; /* Check if we've been asked for help. */ if (argc <= 2 || strcmp (argv [1], "--help") == 0 || strcmp (argv [1], "-h") == 0) usage_exit (progname, 0) ; if (argv [argc - 1][0] != '-') { filename = argv [argc - 1] ; start = 1 ; } else if (argv [1][0] != '-') { filename = argv [1] ; start = 2 ; } else { printf ("Error : Either the first or the last command line parameter should be a filename.\n\n") ; exit (1) ; } ; /* Get the time in case we need it later. */ memset (&sfinfo, 0, sizeof (sfinfo)) ; if ((file = sf_open (filename, SFM_READ, &sfinfo)) == NULL) { printf ("Error : Open of file '%s' failed : %s\n\n", filename, sf_strerror (file)) ; exit (1) ; } ; memset (&binfo, 0, sizeof (binfo)) ; if (sf_command (file, SFC_GET_BROADCAST_INFO, &binfo, sizeof (binfo)) == 0) memset (&binfo, 0, sizeof (binfo)) ; process_args (file, &binfo, argc - 2, argv + start) ; sf_close (file) ; return 0 ; } /* main */
int string_in_log_buffer (SNDFILE *file, const char *s) { static char buffer [LOG_BUFFER_SIZE] ; int count ; memset (buffer, 0, LOG_BUFFER_SIZE) ; /* Get the log buffer data. */ count = sf_command (file, SFC_GET_LOG_INFO, buffer, LOG_BUFFER_SIZE) ; if (LOG_BUFFER_SIZE - count < 2) { printf ("Possible long log buffer.\n") ; exit (1) ; } /* Look for string */ return strstr (buffer, s) ? SF_TRUE : SF_FALSE ; } /* string_in_log_buffer */
// Write SF control void sf_ctrl(u8 data) { if (data & SPIFL_MASK_EN) // SF enabled { if (sf_state == SF_ST_INACT) // enable SFI sfi_enable(); else // execute command sf_command(data); } else // disable SFI sfi_disable(); // enable JTAG }
/* * Open file in sndfile. */ static int startread(sox_format_t * ft) { priv_t * sf = (priv_t *)ft->priv; unsigned bits_per_sample; sox_encoding_t encoding; sox_rate_t rate; start(ft); sf->sf_file = sf_open_fd(fileno(ft->fp), SFM_READ, sf->sf_info, 1); ft->fp = NULL; /* Transfer ownership of fp to LSF */ drain_log_buffer(ft); if (sf->sf_file == NULL) { memset(ft->sox_errstr, 0, sizeof(ft->sox_errstr)); strncpy(ft->sox_errstr, sf_strerror(sf->sf_file), sizeof(ft->sox_errstr)-1); free(sf->sf_file); return SOX_EOF; } if (!(encoding = sox_enc(sf->sf_info->format, &bits_per_sample))) { lsx_fail_errno(ft, SOX_EFMT, "unsupported sndfile encoding %#x", sf->sf_info->format); return SOX_EOF; } /* Don't believe LSF's rate for raw files */ if ((sf->sf_info->format & SF_FORMAT_TYPEMASK) == SF_FORMAT_RAW && !ft->signal.rate) { lsx_warn("'%s': sample rate not specified; trying 8kHz", ft->filename); rate = 8000; } else rate = sf->sf_info->samplerate; #if 0 if ((sf->sf_info->format & SF_FORMAT_SUBMASK) == SF_FORMAT_FLOAT) sf_command(sf->sf_file, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE); #endif #if 0 /* FIXME */ sox_append_comments(&ft->oob.comments, buf); #endif return check_read_params(ft, (unsigned)sf->sf_info->channels, rate, encoding, bits_per_sample, (off_t)(sf->sf_info->frames * sf->sf_info->channels)); }
int main (int argc, char *argv[]) { static char strbuffer [BUFFER_LEN] ; unsigned int linecount ; char *progname, *infilename ; SNDFILE *infile ; SF_INFO sfinfo ; int k, start, readcount ; progname = strrchr (argv [0], '/') ; progname = progname ? progname + 1 : argv [0] ; if (argc != 2) { print_usage (progname) ; return 1 ; } ; infilename = argv [1] ; if (! (infile = sf_open (infilename, SFM_READ, &sfinfo))) { printf ("Error : Not able to open input file %s.\n", infilename) ; sf_perror (NULL) ; sf_command (NULL, SFC_GET_LOG_INFO, strbuffer, BUFFER_LEN) ; printf (strbuffer) ; return 1 ; } ; start = 0 ; linecount = 24 ; while ((readcount = sf_read_raw (infile, strbuffer, linecount))) { printf ("%08X: ", start) ; for (k = 0 ; k < readcount ; k++) printf ("%02X ", strbuffer [k] & 0xFF) ; for (k = readcount ; k < 16 ; k++) printf (" ") ; printf ("\n") ; start += readcount ; } ; sf_close (infile) ; return 0 ; } /* main */
TReadFileAudioStream::TReadFileAudioStream(string name, long beginFrame): TFileAudioStream(name) { memset(&fInfo, 0, sizeof(fInfo)); char utf8name[512] = {0}; assert(fName.size() < 512); Convert2UTF8(fName.c_str(), utf8name, 512); fFile = sf_open(utf8name, SFM_READ, &fInfo); // Check file if (!fFile) { throw - 1; } if (sf_seek(fFile, beginFrame, SEEK_SET) < 0) { sf_close(fFile); throw - 2; } fFramesNum = long(fInfo.frames); fChannels = long(fInfo.channels); fBeginFrame = beginFrame; // Needed because we later on use sf_readf_short, should be removed is sf_readf_float is used instead. if (fInfo.format & SF_FORMAT_FLOAT) { int arg = SF_TRUE; sf_command(fFile, SFC_SET_SCALE_FLOAT_INT_READ, &arg, sizeof(arg)); } if (fInfo.samplerate != TAudioGlobals::fSampleRate) { printf("Warning : file sample rate different from engine sample rate! lib sr = %ld file sr = %d\n", TAudioGlobals::fSampleRate, fInfo.samplerate); } // Dynamic allocation fMemoryBuffer = new TLocalAudioBuffer<short>(TAudioGlobals::fStreamBufferSize, fChannels); fCopyBuffer = new TLocalAudioBuffer<short>(TAudioGlobals::fStreamBufferSize, fChannels); // Read first buffer directly TBufferedAudioStream::ReadBuffer(fMemoryBuffer, TAudioGlobals::fStreamBufferSize, 0); TAudioBuffer<short>::Copy(fCopyBuffer, 0, fMemoryBuffer, 0, TAudioGlobals::fStreamBufferSize); fReady = true; }
void QcWaveform::doLoad( SNDFILE *new_sf, const SF_INFO &new_info, sf_count_t beg, sf_count_t dur ) { // set up soundfile to scale data in range [-1,1] to int range // when reading floating point data as int sf_command( new_sf, SFC_SET_SCALE_FLOAT_INT_READ, NULL, SF_TRUE ); // check beginning and duration validity if( beg < 0 || dur < 1 || beg + dur > new_info.frames ) { qcErrorMsg("Invalid beginning and/or duration."); sf_close( new_sf ); return; } // cleanup previous state // NOTE we have to delete SoundCacheStream before closing the soundfile, as it might be still // loading it // TODO: should SoundCacheStream open the soundfile on its own? delete _cache; if( sf ) sf_close( sf ); sf = new_sf; sfInfo = new_info; _beg = _rangeBeg = beg; _dur = _rangeDur = dur; _rangeEnd = _rangeBeg + _rangeDur; updateFPP(); _cache = new SoundCacheStream(); connect( _cache, SIGNAL(loadProgress(int)), this, SIGNAL(loadProgress(int)) ); connect( _cache, SIGNAL(loadProgress(int)), this, SLOT(update()) ); connect( _cache, SIGNAL(loadingDone()), this, SIGNAL(loadingDone()) ); connect( _cache, SIGNAL(loadingDone()), this, SLOT(redraw()) ); _cache->load( sf, sfInfo, beg, dur, kMaxFramesPerCacheUnit, kMaxRawFrames ); redraw(); }
bool BufWriteCmd::Stage2() { #ifdef NO_LIBSNDFILE return false; #else SndBuf *buf = World_GetNRTBuf(mWorld, mBufIndex); int framesToEnd = buf->frames - mBufOffset; if (framesToEnd < 0) framesToEnd = 0; mFileInfo.samplerate = (int)buf->samplerate; mFileInfo.channels = buf->channels; SNDFILE* sf = sf_open(mFilename, SFM_WRITE, &mFileInfo); if (!sf) { char str[512]; sprintf(str, "File '%s' could not be opened: %s\n", mFilename, sf_strerror(NULL)); SendFailureWithIntValue(&mReplyAddress, "/b_write", str, mBufIndex); //SendFailure(&mReplyAddress, "/b_write", str); scprintf(str); return false; } if (mNumFrames < 0 || mNumFrames > buf->frames) mNumFrames = buf->frames; if (mNumFrames > framesToEnd) mNumFrames = framesToEnd; sf_command(sf, SFC_SET_CLIPPING, NULL, SF_TRUE); // choose clipping rather than wraparound for integer-format files if (mNumFrames > 0) { sf_writef_float(sf, buf->data + (mBufOffset * buf->channels), mNumFrames); } if(buf->sndfile) sf_close(buf->sndfile); if (mLeaveFileOpen) { buf->sndfile = sf; } else { sf_close(sf); buf->sndfile = 0; } return true; #endif }
int libsndfile_stream_open(const char * filename, s_stream * stream, s_params * params) { libsndfile_context *context; FILE *dummyfile; dummyfile = fopen(filename, "rb"); if (!dummyfile) return 0; else fclose(dummyfile); context = (libsndfile_context *) malloc(sizeof(libsndfile_context)); libsndfile_init_context(context); context->file = sf_open (filename, SFM_READ, &context->sfinfo) ; if (!context->file) { libsndfile_cleanup_context(context); free(context); return 0; } sf_command (context->file, SFC_SET_NORM_DOUBLE, NULL, SF_TRUE) ; s_stream_context_set(stream, (void *)context); /* FIXME: SF_INFO::frames is of type sf_count_t, which is a 32bit integer in some libsndfile version and 64bit on others (like the Mac OS X one), so casting context->sfinfo.frames to int is not totally correct - but necessary, since we do not have a 64bit s_params type. 20030108 kyrah */ s_params_set(s_stream_params(stream), "samplerate", S_INTEGER_PARAM_TYPE, context->sfinfo.samplerate, "frames", S_INTEGER_PARAM_TYPE, (int) context->sfinfo.frames, "channels", S_INTEGER_PARAM_TYPE, context->sfinfo.channels, NULL); return 1; }
/* If byfd is true, try to open the file with sf_open_fd */ int test(const char* filename, int byfd) { SF_INFO info; SNDFILE* file; int fid, flags, st; char buffer [2048]; st = 0; flags = O_RDONLY; #if (defined (WIN32) || defined (_WIN32)) flags |= O_BINARY; #endif info.format = 0; if (byfd) { fid = open(filename, flags); if (fid < 0) { fprintf(stderr, "%s:%s failed opening file %s\n", __FILE__, __func__, filename); return -1; } file = sf_open_fd(fid, SFM_READ, &info, SF_TRUE); } else { file = sf_open(filename, SFM_READ, &info); } if (file == NULL) { fprintf(stderr, "%s:%s failed opening file %s\n", __FILE__, __func__, filename); sf_command (file, SFC_GET_LOG_INFO, buffer, sizeof (buffer)) ; fprintf(stderr, "sndfile error is %s:\n", buffer); close(fid); exit(EXIT_FAILURE); } else { fprintf(stderr, "%s:%s file %s has %d frames \n", __FILE__, __func__, filename, info.frames); } sf_close(file); return st; }
/* Generate a reduced waveform for visualization purposes. */ int AU_WaveGenVisual(AU_Wave *w, int reduce) { int i, j, ch; float *pIn, *pViz; if (reduce <= 0) { AG_SetError("Reduction factor <= 0"); return (-1); } if (w->vizFrames != NULL) { Free(w->vizFrames); w->nVizFrames = 0; } sf_command(w->file, SFC_CALC_SIGNAL_MAX, &w->peak, sizeof(w->peak)); w->nVizFrames = w->nFrames/reduce; if ((w->vizFrames = AG_TryMalloc(w->nVizFrames*sizeof(float))) == NULL) { w->nVizFrames = 0; return (-1); } pViz = &w->vizFrames[0]; for (i = 0; i < w->nVizFrames; i++) { for (ch = 0; ch < w->ch; ch++) *pViz++ = 0.0; } pIn = &w->frames[0]; pViz = &w->vizFrames[0]; for (i = 0; i < w->nVizFrames; i++) { for (j = 0; j < reduce; j++) { for (ch = 0; ch < w->ch; ch++) { pViz[ch] += MAX(w->vizFrames[i], fabs((*pIn++)/w->peak)); } } for (ch = 0; ch < w->ch; ch++) *pViz++ /= reduce; } return (0); }
/* * Drain LSF's wonderful log buffer */ static void drain_log_buffer(sox_format_t * ft) { priv_t * sf = (priv_t *)ft->priv; sf_command(sf->sf_file, SFC_GET_LOG_INFO, sf->log_buffer, LOG_MAX); while (*sf->log_buffer_ptr) { static char const warning_prefix[] = "*** Warning : "; char const * end = strchr(sf->log_buffer_ptr, '\n'); if (!end) end = strchr(sf->log_buffer_ptr, '\0'); if (!strncmp(sf->log_buffer_ptr, warning_prefix, strlen(warning_prefix))) { sf->log_buffer_ptr += strlen(warning_prefix); lsx_warn("`%s': %.*s", ft->filename, (int)(end - sf->log_buffer_ptr), sf->log_buffer_ptr); } else lsx_debug("`%s': %.*s", ft->filename, (int)(end - sf->log_buffer_ptr), sf->log_buffer_ptr); sf->log_buffer_ptr = end; if (*sf->log_buffer_ptr == '\n') ++sf->log_buffer_ptr; } }
static void print_usage (char *progname) { SF_FORMAT_INFO info ; int k ; printf ("\nUsage : %s [encoding] <input file> <output file>\n", progname) ; puts ("\n" " where [encoding] may be one of the following:\n\n" " -pcms8 : force the output to signed 8 bit pcm\n" " -pcmu8 : force the output to unsigned 8 bit pcm\n" " -pcm16 : force the output to 16 bit pcm\n" " -pcm24 : force the output to 24 bit pcm\n" " -pcm32 : force the output to 32 bit pcm\n" " -float32 : force the output to 32 bit floating point" ) ; puts ( " -ulaw : force the output ULAW\n" " -alaw : force the output ALAW\n" " -ima-adpcm : force the output to IMA ADPCM (WAV only)\n" " -ms-adpcm : force the output to MS ADPCM (WAV only)\n" " -gsm610 : force the GSM6.10 (WAV only)\n" " -dwvw12 : force the output to 12 bit DWVW (AIFF only)\n" " -dwvw16 : force the output to 16 bit DWVW (AIFF only)\n" " -dwvw24 : force the output to 24 bit DWVW (AIFF only)\n" ) ; puts ( " The format of the output file is determined by the file extension of the\n" " output file name. The following extensions are currently understood:\n" ) ; for (k = 0 ; k < (int) (sizeof (format_map) / sizeof (format_map [0])) ; k++) { info.format = format_map [k].format ; sf_command (NULL, SFC_GET_FORMAT_INFO, &info, sizeof (info)) ; printf (" %-10s : %s\n", format_map [k].ext, info.name) ; } ; puts ("") ; } /* print_usage */
static float *readaudio_snd(const char *filename, long *sr, const float nbsecs, unsigned int *buflen) { SF_INFO sf_info; sf_info.format=0; SNDFILE *sndfile = sf_open(filename, SFM_READ, &sf_info); if (sndfile == NULL) { return NULL; } /* normalize */ sf_command(sndfile, SFC_SET_NORM_FLOAT, NULL, SF_TRUE); *sr = (long)sf_info.samplerate; //allocate input buffer for signal unsigned int src_frames = (nbsecs <= 0) ? sf_info.frames : (nbsecs*sf_info.samplerate); src_frames = (sf_info.frames < src_frames) ? sf_info.frames : src_frames; float *inbuf = (float*)malloc(src_frames*sf_info.channels*sizeof(float)); /*read frames */ sf_count_t cnt_frames = sf_readf_float(sndfile, inbuf, src_frames); float *buf = (float*)malloc(cnt_frames*sizeof(float)); //average across all channels int i,j,indx=0; for (i=0; i<cnt_frames*sf_info.channels; i+=sf_info.channels) { buf[indx] = 0; for (j=0; j<sf_info.channels; j++) { buf[indx] += inbuf[i+j]; } buf[indx++] /= sf_info.channels; } free(inbuf); *buflen = indx; return buf; }
static void setup_disk_thread (jack_thread_info_t *info) { SF_INFO sf_info; int short_mask; sf_info.samplerate = info->sample_rate; sf_info.channels = info->channels; switch (info->bitdepth) { case 8: short_mask = SF_FORMAT_PCM_U8; break; case 16: short_mask = SF_FORMAT_PCM_16; break; case 24: short_mask = SF_FORMAT_PCM_24; break; case 32: short_mask = SF_FORMAT_PCM_32; break; default: short_mask = SF_FORMAT_PCM_16; break; } sf_info.format = SF_FORMAT_WAV|short_mask; if ((info->sf = sf_open (info->path, SFM_WRITE, &sf_info)) == NULL) { char errstr[256]; sf_error_str (0, errstr, sizeof (errstr) - 1); fprintf (stderr, "cannot open sndfile \"%s\" for output (%s)\n", info->path, errstr); jack_client_close (info->client); exit (1); } sf_command (info->sf, SFC_SET_CLIPPING, NULL, SF_TRUE); info->duration *= sf_info.samplerate; info->can_capture = 0; pthread_create (&info->thread_id, NULL, disk_thread, info); }
QStringList Version::dependencyVersions() { char sndfile_version[128]; sf_command(nullptr, SFC_GET_LIB_VERSION, sndfile_version, sizeof(sndfile_version)); // Null-terminate just in case. sndfile_version[sizeof(sndfile_version) - 1] = '\0'; // WARNING: may be inaccurate since some come from compile-time header // definitions instead of the actual dynamically loaded library). QStringList result; result // Should be accurate. << QString("Qt: %1").arg(qVersion()) #ifdef __BROADCAST__ // Should be accurate. << QString("libshout: %1").arg(shout_version(NULL, NULL, NULL)) #endif << QString("PortAudio: %1 %2").arg(Pa_GetVersion()).arg(Pa_GetVersionText()) // The version of the RubberBand headers Mixxx was compiled with. << QString("RubberBand: %1").arg(RUBBERBAND_VERSION) // The version of the SoundTouch headers Mixxx was compiled with. << QString("SoundTouch: %1").arg(SOUNDTOUCH_VERSION) // The version of the TagLib headers Mixxx was compiled with. << QString("TagLib: %1.%2.%3").arg(QString::number(TAGLIB_MAJOR_VERSION), QString::number(TAGLIB_MINOR_VERSION), QString::number(TAGLIB_PATCH_VERSION)) // The version of the ChromaPrint headers Mixxx was compiled with. << QString("ChromaPrint: %1.%2.%3").arg(QString::number(CHROMAPRINT_VERSION_MAJOR), QString::number(CHROMAPRINT_VERSION_MINOR), QString::number(CHROMAPRINT_VERSION_PATCH)) // Should be accurate. << QString("Vorbis: %1").arg(vorbis_version_string()) // Should be accurate. << QString("libsndfile: %1").arg(sndfile_version) // The version of the FLAC headers Mixxx was compiled with. << QString("FLAC: %1").arg(FLAC__VERSION_STRING) << QString("libmp3lame: %1").arg(get_lame_version()); return result; }
static int sndfile_set_channel_map(struct input_handle* ih, int* st) { int result; int* channel_map = (int*) calloc((size_t) ih->file_info.channels, sizeof(int)); if (!channel_map) return 1; result = sf_command(ih->file, SFC_GET_CHANNEL_MAP_INFO, (void*) channel_map, (int) ((size_t) ih->file_info.channels * sizeof(int))); /* If sndfile found a channel map, set it with * ebur128_set_channel_map */ if (result == SF_TRUE) { int j; for (j = 0; j < ih->file_info.channels; ++j) { switch (channel_map[j]) { case SF_CHANNEL_MAP_INVALID: st[j] = EBUR128_UNUSED; break; case SF_CHANNEL_MAP_MONO: st[j] = EBUR128_CENTER; break; case SF_CHANNEL_MAP_LEFT: st[j] = EBUR128_LEFT; break; case SF_CHANNEL_MAP_RIGHT: st[j] = EBUR128_RIGHT; break; case SF_CHANNEL_MAP_CENTER: st[j] = EBUR128_CENTER; break; case SF_CHANNEL_MAP_REAR_LEFT: st[j] = EBUR128_LEFT_SURROUND; break; case SF_CHANNEL_MAP_REAR_RIGHT: st[j] = EBUR128_RIGHT_SURROUND; break; default: st[j] = EBUR128_UNUSED; break; } } free(channel_map); return 0; } else { free(channel_map); return 1; } }
void check_log_buffer_or_die (SNDFILE *file, int line_num) { static char buffer [LOG_BUFFER_SIZE] ; int count ; memset (buffer, 0, LOG_BUFFER_SIZE) ; /* Get the log buffer data. */ count = sf_command (file, SFC_GET_LOG_INFO, buffer, LOG_BUFFER_SIZE) ; if (LOG_BUFFER_SIZE - count < 2) { printf ("\n\nLine %d : Possible long log buffer.\n", line_num) ; exit (1) ; } /* Look for "Should" */ if (strstr (buffer, "ould")) { printf ("\n\nLine %d : Log buffer contains `ould'. Dumping.\n", line_num) ; puts (buffer) ; exit (1) ; } ; /* Look for "**" */ if (strstr (buffer, "*")) { printf ("\n\nLine %d : Log buffer contains `*'. Dumping.\n", line_num) ; puts (buffer) ; exit (1) ; } ; /* Look for "Should" */ if (strstr (buffer, "nknown marker")) { printf ("\n\nLine %d : Log buffer contains `nknown marker'. Dumping.\n", line_num) ; puts (buffer) ; exit (1) ; } ; return ; } /* check_log_buffer_or_die */
static int instrument_dump (const char *filename) { SNDFILE *file ; SF_INFO sfinfo ; SF_INSTRUMENT inst ; int got_inst, k ; memset (&sfinfo, 0, sizeof (sfinfo)) ; if ((file = sf_open (filename, SFM_READ, &sfinfo)) == NULL) { printf ("Error : Not able to open input file %s.\n", filename) ; fflush (stdout) ; memset (data, 0, sizeof (data)) ; puts (sf_strerror (NULL)) ; return 1 ; } ; got_inst = sf_command (file, SFC_GET_INSTRUMENT, &inst, sizeof (inst)) ; sf_close (file) ; if (got_inst == SF_FALSE) { printf ("Error : File '%s' does not contain instrument data.\n\n", filename) ; return 1 ; } ; printf ("Instrument : %s\n\n", filename) ; printf (" Gain : %d\n", inst.gain) ; printf (" Base note : %d\n", inst.basenote) ; printf (" Velocity : %d - %d\n", (int) inst.velocity_lo, (int) inst.velocity_hi) ; printf (" Key : %d - %d\n", (int) inst.key_lo, (int) inst.key_hi) ; printf (" Loop points : %d\n", inst.loop_count) ; for (k = 0 ; k < inst.loop_count ; k++) printf (" %-2d Mode : %s Start : %6d End : %6d Count : %6d\n", k, str_of_type (inst.loops [k].mode), inst.loops [k].start, inst.loops [k].end, inst.loops [k].count) ; putchar ('\n') ; return 0 ; } /* instrument_dump */
static void broadcast_rdwr_test (const char *filename, int filetype) { SF_BROADCAST_INFO binfo ; SNDFILE *file ; SF_INFO sfinfo ; sf_count_t frames ; print_test_name (__func__, filename) ; create_short_sndfile (filename, filetype, 2) ; memset (&sfinfo, 0, sizeof (sfinfo)) ; memset (&binfo, 0, sizeof (binfo)) ; snprintf (binfo.description, sizeof (binfo.description), "Test description") ; snprintf (binfo.originator, sizeof (binfo.originator), "Test originator") ; snprintf (binfo.originator_reference, sizeof (binfo.originator_reference), "%08x-%08x", (unsigned int) time (NULL), (unsigned int) (~ time (NULL))) ; snprintf (binfo.origination_date, sizeof (binfo.origination_date), "%d/%02d/%02d", 2006, 3, 30) ; snprintf (binfo.origination_time, sizeof (binfo.origination_time), "%02d:%02d:%02d", 20, 27, 0) ; snprintf (binfo.umid, sizeof (binfo.umid), "Some umid") ; binfo.coding_history_size = 0 ; file = test_open_file_or_die (filename, SFM_RDWR, &sfinfo, SF_TRUE, __LINE__) ; frames = sfinfo.frames ; if (sf_command (file, SFC_SET_BROADCAST_INFO, &binfo, sizeof (binfo)) != SF_FALSE) { printf ("\n\nLine %d : sf_command (SFC_SET_BROADCAST_INFO) should have failed but didn't.\n\n", __LINE__) ; exit (1) ; } ; sf_close (file) ; file = test_open_file_or_die (filename, SFM_READ, &sfinfo, SF_TRUE, __LINE__) ; sf_close (file) ; exit_if_true (frames != sfinfo.frames, "\n\nLine %d : Frame count %lld should be %lld.\n", __LINE__, sfinfo.frames, frames) ; unlink (filename) ; puts ("ok") ; } /* broadcast_rdwr_test */
static void broadcast_dump (const char *filename) { SNDFILE *file ; SF_INFO sfinfo ; SF_BROADCAST_INFO bext ; int got_bext ; memset (&sfinfo, 0, sizeof (sfinfo)) ; if ((file = sf_open (filename, SFM_READ, &sfinfo)) == NULL) { printf ("Error : Not able to open input file %s.\n", filename) ; fflush (stdout) ; memset (data, 0, sizeof (data)) ; puts (sf_strerror (NULL)) ; return ; } ; memset (&bext, 0, sizeof (SF_BROADCAST_INFO)) ; got_bext = sf_command (file, SFC_GET_BROADCAST_INFO, &bext, sizeof (bext)) ; sf_close (file) ; if (got_bext == SF_FALSE) { printf ("Error : File '%s' does not contain broadcast information.\n\n", filename) ; return ; } ; printf ("Description : %.*s\n", (int) sizeof (bext.description), bext.description) ; printf ("Originator : %.*s\n", (int) sizeof (bext.originator), bext.originator) ; printf ("Origination ref : %.*s\n", (int) sizeof (bext.originator_reference), bext.originator_reference) ; printf ("Origination date : %.*s\n", (int) sizeof (bext.origination_date), bext.origination_date) ; printf ("Origination time : %.*s\n", (int) sizeof (bext.origination_time), bext.origination_time) ; printf ("BWF version : %d\n", bext.version) ; printf ("UMID : %.*s\n", (int) sizeof (bext.umid), bext.umid) ; printf ("Coding history : %.*s\n", bext.coding_history_size, bext.coding_history) ; } /* broadcast_dump */
/* * Class: org_emmef_sndfile_SoundFile * Method: getSndFileVersion0 * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_org_emmef_sndfile_SoundFileType_getSndFileVersion0(JNIEnv *env, jclass) { initExceptions(env); try { int size= 4; char *walk = 0; bool doContinue = true; while (doContinue) { if (walk != 0) { delete walk; } walk = new char[size]; sf_command(0, SFC_GET_LIB_VERSION, walk, size); int length = 0; while (length < size && walk[length] != '\0') { length++; } if ((size < 1024) && (length == 0 || length + 1 >= size)) { size *= 2; } else { doContinue = false; } } jstring version = env->NewStringUTF(walk); delete walk; return version; } catch (...) { } return 0; }
PRIVATE void access_output_file(GtkWidget *widget, GtkWidget *fs) { Generator *g = gtk_object_get_data(GTK_OBJECT(fs), "Generator"); Data *data = g->data; const char *filename = gtk_file_selection_get_filename(GTK_FILE_SELECTION(fs)); FILE *f; f = fopen(filename, "rb"); if (f != NULL) { fclose(f); if (popup_msgbox("Confirm Overwrite", MSGBOX_YES | MSGBOX_NO, 0, MSGBOX_NO, "The file named %s exists.\nDo you want to overwrite it?", filename) != MSGBOX_YES) { return; } } if (data->filename != NULL) free(data->filename); data->filename = safe_string_dup(filename); data->output = sf_open( filename, SFM_WRITE, &data->setup ); data->frames_recorded = 0; if (data->output == NULL) { popup_msgbox("Could Not Create File", MSGBOX_OK, 0, MSGBOX_OK, "Could not create output file %s.\n" "Recording cancelled.", filename); return; } sf_command( data->output, SFC_SET_NORM_DOUBLE, NULL, SF_TRUE ); gtk_widget_destroy(fs); /* %%% should this be gtk_widget_hide? uber-paranoia */ }
SharedPtr<Decoder> SndFileDecoderFactory::createDecoder(UniquePtr<std::istream> &file) { SF_VIRTUAL_IO vio = { get_filelen, seek, read, write, tell }; SF_INFO sndinfo; SNDFILE *sndfile = sf_open_virtual(&vio, SFM_READ, &sndinfo, file.get()); if(!sndfile) return nullptr; ChannelConfig sconfig; Vector<int> chanmap(sndinfo.channels); if(sf_command(sndfile, SFC_GET_CHANNEL_MAP_INFO, &chanmap[0], chanmap.size()*sizeof(int)) == SF_TRUE) { auto matches = [](const Vector<int> &first, std::initializer_list<int> second) -> bool { if(first.size() != second.size()) return false; return std::mismatch(first.begin(), first.end(), second.begin()).first == first.end(); }; if(matches(chanmap, {SF_CHANNEL_MAP_MONO})) sconfig = ChannelConfig::Mono; else if(matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT})) sconfig = ChannelConfig::Stereo; else if(matches(chanmap, {SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT})) sconfig = ChannelConfig::Rear; else if(matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT, SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT})) sconfig = ChannelConfig::Quad; else if(matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT, SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE, SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT}) || matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT, SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE, SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT})) sconfig = ChannelConfig::X51; else if(matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT, SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE, SF_CHANNEL_MAP_REAR_CENTER, SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT})) sconfig = ChannelConfig::X61; else if(matches(chanmap, {SF_CHANNEL_MAP_LEFT, SF_CHANNEL_MAP_RIGHT, SF_CHANNEL_MAP_CENTER, SF_CHANNEL_MAP_LFE, SF_CHANNEL_MAP_REAR_LEFT, SF_CHANNEL_MAP_REAR_RIGHT, SF_CHANNEL_MAP_SIDE_LEFT, SF_CHANNEL_MAP_SIDE_RIGHT})) sconfig = ChannelConfig::X71; else if(matches(chanmap, {SF_CHANNEL_MAP_AMBISONIC_B_W, SF_CHANNEL_MAP_AMBISONIC_B_X, SF_CHANNEL_MAP_AMBISONIC_B_Y})) sconfig = ChannelConfig::BFormat2D; else if(matches(chanmap, {SF_CHANNEL_MAP_AMBISONIC_B_W, SF_CHANNEL_MAP_AMBISONIC_B_X, SF_CHANNEL_MAP_AMBISONIC_B_Y, SF_CHANNEL_MAP_AMBISONIC_B_Z})) sconfig = ChannelConfig::BFormat3D; else { sf_close(sndfile); return nullptr; } } else if(sf_command(sndfile, SFC_WAVEX_GET_AMBISONIC, 0, 0) == SF_AMBISONIC_B_FORMAT) { if(sndinfo.channels == 3) sconfig = ChannelConfig::BFormat2D; else if(sndinfo.channels == 4) sconfig = ChannelConfig::BFormat3D; else { sf_close(sndfile); return nullptr; } } else if(sndinfo.channels == 1) sconfig = ChannelConfig::Mono; else if(sndinfo.channels == 2) sconfig = ChannelConfig::Stereo; else { sf_close(sndfile); return nullptr; } SampleType stype = SampleType::Int16; switch(sndinfo.format&SF_FORMAT_SUBMASK) { case SF_FORMAT_FLOAT: case SF_FORMAT_DOUBLE: case SF_FORMAT_VORBIS: stype = SampleType::Float32; break; default: stype = SampleType::Int16; break; } return MakeShared<SndFileDecoder>(std::move(file), sndfile, sndinfo, sconfig, stype); }
static void test_float_peak (char *str, char *filename, int typemajor) { SNDFILE *file ; SF_INFO sfinfo ; int k, frames, count ; printf (" test_float_peak : %s ... ", str) ; sfinfo.samplerate = 44100 ; sfinfo.format = (typemajor | SF_FORMAT_FLOAT) ; sfinfo.channels = 4 ; sfinfo.frames = 0 ; frames = BUFFER_LEN / sfinfo.channels ; /* Create some random data with a peak value of 0.66. */ for (k = 0 ; k < BUFFER_LEN ; k++) data [k] = (rand () % 2000) / 3000.0 ; /* Insert some larger peaks a know locations. */ data [4 * (frames / 8) + 0] = (frames / 8) * 0.01 ; /* First channel */ data [4 * (frames / 6) + 1] = (frames / 6) * 0.01 ; /* Second channel */ data [4 * (frames / 4) + 2] = (frames / 4) * 0.01 ; /* Third channel */ data [4 * (frames / 2) + 3] = (frames / 2) * 0.01 ; /* Fourth channel */ if (! (file = sf_open (filename, SFM_WRITE, &sfinfo))) { printf ("Line %d: sf_open_write failed with error : ", __LINE__) ; sf_perror (NULL) ; exit (1) ; } ; /* Write the data in four passed. The data is designed so that peaks will ** be written in the different calls to sf_write_double (). */ for (count = 0 ; count < 4 ; count ++) { if ((k = sf_write_double (file, data + count * BUFFER_LEN / 4, BUFFER_LEN / 4)) != BUFFER_LEN / 4) { printf ("Line %d: sf_write_double # %d failed with short write (%d ->%d)\n", __LINE__, count, BUFFER_LEN / 4, k) ; exit (1) ; } ; } ; sf_close (file) ; if (! (file = sf_open (filename, SFM_READ, &sfinfo))) { printf ("Line %d: sf_open_read failed with error : ", __LINE__) ; sf_perror (NULL) ; exit (1) ; } ; if (sfinfo.format != (typemajor | SF_FORMAT_FLOAT)) { printf ("Line %d: Returned format incorrect (0x%08X => 0x%08X).\n", __LINE__, (typemajor | SF_FORMAT_FLOAT), sfinfo.format) ; exit (1) ; } ; if (sfinfo.frames != frames) { printf ("Line %d: Incorrect number of.frames in file. (%d => %ld)\n", __LINE__, frames, (long) sfinfo.frames) ; exit (1) ; } ; if (sfinfo.channels != 4) { printf ("Line %d: Incorrect number of channels in file.\n", __LINE__) ; exit (1) ; } ; /* Get the log buffer data. */ log_buffer [0] = 0 ; sf_command (file, SFC_GET_LOG_INFO, log_buffer, LOG_BUFFER_SIZE) ; if (strlen (log_buffer) == 0) { printf ("Line %d: Empty log buffer,\n", __LINE__) ; exit (1) ; } ; check_logged_peaks (log_buffer) ; sf_close (file) ; unlink (filename) ; printf ("ok\n") ; } /* test_float_peak */
void World_NonRealTimeSynthesis(struct World *world, WorldOptions *inOptions) { if (inOptions->mLoadGraphDefs) { World_LoadGraphDefs(world); } int bufLength = world->mBufLength; int fileBufFrames = inOptions->mPreferredHardwareBufferFrameSize; if (fileBufFrames <= 0) fileBufFrames = 8192; int bufMultiple = (fileBufFrames + bufLength - 1) / bufLength; fileBufFrames = bufMultiple * bufLength; // batch process non real time audio if (!inOptions->mNonRealTimeOutputFilename) throw std::runtime_error("Non real time output filename is NULL.\n"); SF_INFO inputFileInfo, outputFileInfo; float *inputFileBuf = 0; float *outputFileBuf = 0; int numInputChannels = 0; int numOutputChannels; outputFileInfo.samplerate = inOptions->mPreferredSampleRate; numOutputChannels = outputFileInfo.channels = world->mNumOutputs; sndfileFormatInfoFromStrings(&outputFileInfo, inOptions->mNonRealTimeOutputHeaderFormat, inOptions->mNonRealTimeOutputSampleFormat); world->hw->mNRTOutputFile = sf_open(inOptions->mNonRealTimeOutputFilename, SFM_WRITE, &outputFileInfo); sf_command(world->hw->mNRTOutputFile, SFC_SET_CLIPPING, NULL, SF_TRUE); if (!world->hw->mNRTOutputFile) throw std::runtime_error("Couldn't open non real time output file.\n"); outputFileBuf = (float*)calloc(1, world->mNumOutputs * fileBufFrames * sizeof(float)); if (inOptions->mNonRealTimeInputFilename) { world->hw->mNRTInputFile = sf_open(inOptions->mNonRealTimeInputFilename, SFM_READ, &inputFileInfo); if (!world->hw->mNRTInputFile) throw std::runtime_error("Couldn't open non real time input file.\n"); inputFileBuf = (float*)calloc(1, inputFileInfo.channels * fileBufFrames * sizeof(float)); if (world->mNumInputs != (uint32)inputFileInfo.channels) scprintf("WARNING: input file channels didn't match number of inputs specified in options.\n"); numInputChannels = world->mNumInputs = inputFileInfo.channels; // force it. if (inputFileInfo.samplerate != (int)inOptions->mPreferredSampleRate) scprintf("WARNING: input file sample rate does not equal output sample rate.\n"); } else { world->hw->mNRTInputFile = 0; } FILE *cmdFile; if (inOptions->mNonRealTimeCmdFilename) { #ifdef _WIN32 cmdFile = fopen(inOptions->mNonRealTimeCmdFilename, "rb"); #else cmdFile = fopen(inOptions->mNonRealTimeCmdFilename, "r"); #endif } else cmdFile = stdin; if (!cmdFile) throw std::runtime_error("Couldn't open non real time command file.\n"); OSC_Packet packet; memset(&packet, 0, sizeof(packet)); packet.mData = (char *)malloc(8192); packet.mIsBundle = true; packet.mReplyAddr.mReplyFunc = null_reply_func; int64 schedTime; if (nextOSCPacket(cmdFile, &packet, schedTime)) throw std::runtime_error("command file empty.\n"); int64 prevTime = schedTime; World_SetSampleRate(world, inOptions->mPreferredSampleRate); World_Start(world); int64 oscTime = 0; double oscToSeconds = 1. / pow(2.,32.); double oscToSamples = inOptions->mPreferredSampleRate * oscToSeconds; int64 oscInc = (int64)((double)bufLength / oscToSamples); if(inOptions->mVerbosity >= 0) { printf("start time %g\n", schedTime * oscToSeconds); } bool run = true; int inBufStep = numInputChannels * bufLength; int outBufStep = numOutputChannels * bufLength; float* inputBuses = world->mAudioBus + world->mNumOutputs * bufLength; float* outputBuses = world->mAudioBus; int32* inputTouched = world->mAudioBusTouched + world->mNumOutputs; int32* outputTouched = world->mAudioBusTouched; for (; run;) { int bufFramesCalculated = 0; float* inBufPos = inputFileBuf; float* outBufPos = outputFileBuf; if (world->hw->mNRTInputFile) { int framesRead = sf_readf_float(world->hw->mNRTInputFile, inputFileBuf, fileBufFrames); if (framesRead < fileBufFrames) { memset(inputFileBuf + framesRead * numInputChannels, 0, (fileBufFrames - framesRead) * numInputChannels * sizeof(float)); } } for (int i=0; i<bufMultiple && run; ++i) { int bufCounter = world->mBufCounter; // deinterleave input to input buses if (inputFileBuf) { float *inBus = inputBuses; for (int j=0; j<numInputChannels; ++j, inBus += bufLength) { float *inFileBufPtr = inBufPos + j; for (int k=0; k<bufLength; ++k) { inBus[k] = *inFileBufPtr; inFileBufPtr += numInputChannels; } inputTouched[j] = bufCounter; } } // execute ready commands int64 nextTime = oscTime + oscInc; while (schedTime <= nextTime) { float diffTime = (float)(schedTime - oscTime) * oscToSamples + 0.5; float diffTimeFloor = floor(diffTime); world->mSampleOffset = (int)diffTimeFloor; world->mSubsampleOffset = diffTime - diffTimeFloor; if (world->mSampleOffset < 0) world->mSampleOffset = 0; else if (world->mSampleOffset >= bufLength) world->mSampleOffset = bufLength-1; PerformOSCBundle(world, &packet); if (nextOSCPacket(cmdFile, &packet, schedTime)) { run = false; break; } if(inOptions->mVerbosity >= 0) { printf("nextOSCPacket %g\n", schedTime * oscToSeconds); } if (schedTime < prevTime) { scprintf("ERROR: Packet time stamps out-of-order.\n"); run = false; goto Bail; } prevTime = schedTime; } World_Run(world); // interleave output to output buffer float *outBus = outputBuses; for (int j=0; j<numOutputChannels; ++j, outBus += bufLength) { float *outFileBufPtr = outBufPos + j; if (outputTouched[j] == bufCounter) { for (int k=0; k<bufLength; ++k) { *outFileBufPtr = outBus[k]; outFileBufPtr += numOutputChannels; } } else { for (int k=0; k<bufLength; ++k) { *outFileBufPtr = 0.f; outFileBufPtr += numOutputChannels; } } } bufFramesCalculated += bufLength; inBufPos += inBufStep; outBufPos += outBufStep; world->mBufCounter++; oscTime = nextTime; } Bail: // write output sf_writef_float(world->hw->mNRTOutputFile, outputFileBuf, bufFramesCalculated); } if (cmdFile != stdin) fclose(cmdFile); sf_close(world->hw->mNRTOutputFile); world->hw->mNRTOutputFile = 0; if (world->hw->mNRTInputFile) { sf_close(world->hw->mNRTInputFile); world->hw->mNRTInputFile = 0; } free(packet.mData); World_Cleanup(world,true); }