### Configure libsamplerate CMake Installation Source: https://github.com/libsndfile/libsamplerate/blob/master/src/CMakeLists.txt Handles the installation of targets, pkg-config files, and CMake package configuration files when LIBSAMPLERATE_INSTALL is enabled. ```cmake if(LIBSAMPLERATE_INSTALL) install(TARGETS samplerate EXPORT SampleRateTargets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} PUBLIC_HEADER DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) # pkg-config module if(LIBSAMPLERATE_INSTALL_PKGCONFIG_MODULE) set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix "\${prefix}") set(includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") set(libdir "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}") set(VERSION "${PROJECT_VERSION}") if(LIBM_REQUIRED) set(LIBS "-lm") endif() configure_file(../samplerate.pc.in samplerate.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/samplerate.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) endif() set(CMAKE_INSTALL_PACKAGEDIR "${CMAKE_INSTALL_LIBDIR}/cmake/SampleRate") configure_package_config_file(../cmake/SampleRateConfig.cmake.in SampleRateConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_PACKAGEDIR}) write_basic_package_version_file(SampleRateConfigVersion.cmake COMPATIBILITY SameMajorVersion) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/SampleRateConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/SampleRateConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_PACKAGEDIR}) install(EXPORT SampleRateTargets NAMESPACE SampleRate:: DESTINATION ${CMAKE_INSTALL_PACKAGEDIR}) endif() ``` -------------------------------- ### Install GNU Octave on Debian Source: https://github.com/libsndfile/libsamplerate/blob/master/Octave/Readme.md Command to install Octave and the signal package on Debian-based Linux distributions. ```bash sudo apt install octave octave-signal ``` -------------------------------- ### Get Converter Description Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_misc.md Retrieves a longer descriptive string for a given converter type. Returns NULL if the type is invalid. ```c const char *src_get_description (int converter_type) ; ``` -------------------------------- ### src_reset Source: https://context7.com/libsndfile/libsamplerate/llms.txt Resets the converter to its initial state without freeing memory. Use when starting conversion of a new, unrelated audio stream. ```APIDOC ## src_reset ### Description Resets the converter to its initial state without freeing memory. Use when starting conversion of a new, unrelated audio stream. ### Parameters - **state** (SRC_STATE*) - Required - Pointer to the converter state to be reset. ### Response - **Returns** (int) - Returns 0 on success, or an error code if the reset fails. ``` -------------------------------- ### Reset Converter State with src_reset Source: https://context7.com/libsndfile/libsamplerate/llms.txt Resets the converter to its initial state without freeing memory. Use when starting conversion of a new, unrelated audio stream. ```c #include int src_reset(SRC_STATE *state); /* Example: Reuse converter for multiple audio files */ int reset_converter_example(void) { int error; SRC_STATE *src_state = src_new(SRC_SINC_FASTEST, 1, &error); if (src_state == NULL) { printf("Error: %s\n", src_strerror(error)); return 1; } /* Process first audio file... */ float input1[1000], output1[1100]; SRC_DATA data = { .data_in = input1, .data_out = output1, .input_frames = 1000, .output_frames = 1100, .src_ratio = 1.1, .end_of_input = 1 }; src_process(src_state, &data); printf("File 1: Generated %ld frames\n", data.output_frames_gen); /* Reset converter for second file */ error = src_reset(src_state); if (error) { printf("Reset error: %s\n", src_strerror(error)); src_delete(src_state); return 1; } /* Process second audio file... */ float input2[2000], output2[2200]; data.data_in = input2; data.data_out = output2; data.input_frames = 2000; data.output_frames = 2200; /* Same ratio, fresh state */ src_process(src_state, &data); printf("File 2: Generated %ld frames\n", data.output_frames_gen); src_delete(src_state); return 0; } ``` -------------------------------- ### Get Error String Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_misc.md Converts an integer error code into a human-readable string. Returns "No Error" for 0 or NULL for undefined error values. ```c const char* src_strerror (int error) ; ``` -------------------------------- ### Build libsamplerate with Unix tools Source: https://github.com/libsndfile/libsamplerate/blob/master/README.md Standard build sequence for platforms with a Bourne compatible shell, ANSI C compiler, and make utility. ```bash autoreconf -vif ./configure make make install ``` -------------------------------- ### Build libsamplerate with CMake Source: https://github.com/libsndfile/libsamplerate/blob/master/README.md Build sequence using the CMake build system. ```bash mkdir build cd build cmake .. make ``` -------------------------------- ### Get Converter Name Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_misc.md Retrieves the short string name for a given converter type. Returns NULL if the type is invalid. ```c const char *src_get_name (int converter_type) ; ``` -------------------------------- ### Retrieve Library Version and Converters Source: https://context7.com/libsndfile/libsamplerate/llms.txt Use this to verify the library version and list all supported interpolation converters. Ensure samplerate.h is included. ```c #include const char* src_get_version(void); /* Example: Print version information */ int version_example(void) { printf("libsamplerate version: %s\n", src_get_version()); /* Also print available converters */ printf("\nAvailable converters:\n"); for (int i = 0; ; i++) { const char *name = src_get_name(i); if (name == NULL) break; printf(" %d: %s\n", i, name); } return 0; } ``` -------------------------------- ### Perform Multi-Channel Streaming Conversion Source: https://context7.com/libsndfile/libsamplerate/llms.txt Demonstrates a complete workflow for converting multi-channel audio in blocks, including memory allocation, state initialization, and processing loop management. ```c #include #include #include #include #include #define INPUT_SAMPLE_RATE 44100 #define OUTPUT_SAMPLE_RATE 48000 #define CHANNELS 2 #define BLOCK_SIZE 256 #define TOTAL_INPUT_FRAMES 10000 int complete_streaming_example(void) { /* Allocate buffers */ float *input = calloc(TOTAL_INPUT_FRAMES * CHANNELS, sizeof(float)); float *output = calloc(TOTAL_INPUT_FRAMES * 2 * CHANNELS, sizeof(float)); if (!input || !output) { printf("Memory allocation failed\n"); return 1; } /* Generate stereo test signal (440Hz left, 880Hz right) */ for (int i = 0; i < TOTAL_INPUT_FRAMES; i++) { float t = (float)i / INPUT_SAMPLE_RATE; input[i * CHANNELS + 0] = 0.5f * sinf(2.0f * M_PI * 440.0f * t); /* Left */ input[i * CHANNELS + 1] = 0.5f * sinf(2.0f * M_PI * 880.0f * t); /* Right */ } /* Initialize converter */ int error; SRC_STATE *state = src_new(SRC_SINC_MEDIUM_QUALITY, CHANNELS, &error); if (!state) { printf("Failed to create converter: %s\n", src_strerror(error)); free(input); free(output); return 1; } /* Process in blocks */ SRC_DATA data; double src_ratio = (double)OUTPUT_SAMPLE_RATE / INPUT_SAMPLE_RATE; long total_input_used = 0; long total_output_gen = 0; int block_count = 0; while (1) { long input_remaining = TOTAL_INPUT_FRAMES - total_input_used; long output_remaining = (TOTAL_INPUT_FRAMES * 2) - total_output_gen; data.data_in = input + (total_input_used * CHANNELS); data.data_out = output + (total_output_gen * CHANNELS); data.input_frames = (input_remaining < BLOCK_SIZE) ? input_remaining : BLOCK_SIZE; data.output_frames = (output_remaining < BLOCK_SIZE * 2) ? output_remaining : BLOCK_SIZE * 2; data.src_ratio = src_ratio; data.end_of_input = (input_remaining <= BLOCK_SIZE) ? 1 : 0; error = src_process(state, &data); if (error) { printf("Processing error: %s\n", src_strerror(error)); break; } total_input_used += data.input_frames_used; total_output_gen += data.output_frames_gen; block_count++; /* Done when end of input and no more output */ if (data.end_of_input && data.output_frames_gen == 0) break; } /* Print results */ printf("Conversion complete:\n"); printf(" Input: %ld frames @ %d Hz\n", total_input_used, INPUT_SAMPLE_RATE); printf(" Output: %ld frames @ %d Hz\n", total_output_gen, OUTPUT_SAMPLE_RATE); printf(" Blocks processed: %d\n", block_count); printf(" Expected output: ~%d frames\n", (int)(TOTAL_INPUT_FRAMES * src_ratio)); /* Cleanup */ src_delete(state); free(input); free(output); return 0; } ``` -------------------------------- ### Detect libsamplerate with autoconf Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/faq.md Use PKG_CHECK_MODULES in configure.ac to detect the library and define necessary variables. ```m4 PKG_CHECK_MODULES(SAMPLERATE, samplerate >= 0.1.3, ac_cv_samplerate=1, ac_cv_samplerate=0) AC_DEFINE_UNQUOTED([HAVE_SAMPLERATE],${ac_cv_samplerate}, [Set to 1 if you have libsamplerate.]) AC_SUBST(SAMPLERATE_CFLAGS) AC_SUBST(SAMPLERATE_LIBS) ``` -------------------------------- ### List Available Converter Types in C Source: https://context7.com/libsndfile/libsamplerate/llms.txt Iterate through the available converter algorithms to retrieve their names and descriptions using src_get_name and src_get_description. ```c #include /* Available converter types */ enum { SRC_SINC_BEST_QUALITY = 0, /* Highest quality, 97dB SNR, 97% bandwidth */ SRC_SINC_MEDIUM_QUALITY = 1, /* High quality, 97dB SNR, 90% bandwidth, faster */ SRC_SINC_FASTEST = 2, /* Good quality, 97dB SNR, 80% bandwidth, fast */ SRC_ZERO_ORDER_HOLD = 3, /* Low quality, very fast, no anti-aliasing */ SRC_LINEAR = 4 /* Low quality, very fast, no anti-aliasing */ }; /* Get converter name and description */ int main(void) { for (int k = 0; k < 5; k++) { const char *name = src_get_name(k); const char *description = src_get_description(k); if (name != NULL) { printf("Converter %d: %s\n", k, name); printf(" %s\n\n", description); } } return 0; } /* Output: Converter 0: Best Sinc Interpolator Band limited sinc interpolation, best quality, 97dB SNR, 97% BW. Converter 1: Medium Sinc Interpolator Band limited sinc interpolation, medium quality, 97dB SNR, 90% BW. Converter 2: Fastest Sinc Interpolator Band limited sinc interpolation, fastest, 97dB SNR, 80% BW. Converter 3: ZOH Interpolator Zero order hold interpolator, very fast, poor quality. Converter 4: Linear Interpolator Linear interpolator, very fast, poor quality. */ ``` -------------------------------- ### Build and Test simple_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'simple_test' executable. It links against the 'samplerate' library. ```cmake add_executable(simple_test simple_test.c util.c util.h) target_link_libraries(simple_test PRIVATE samplerate) add_test(NAME simple_test COMMAND simple_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### src_new Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_full.md Initializes a new sample rate converter object. ```APIDOC ## src_new ### Description Returns an anonymous pointer to a sample rate converter object (SRC_STATE). If an error occurs, it returns a NULL pointer and updates the error value. ### Parameters - **converter_type** (int) - Required - The type of converter to use. - **channels** (int) - Required - Number of audio channels. - **error** (int*) - Required - Pointer to store error codes. ### Response - **SRC_STATE*** - Pointer to the converter state or NULL on error. ``` -------------------------------- ### Build and Test float_short_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'float_short_test' executable. It links against the 'samplerate' library. ```cmake add_executable(float_short_test float_short_test.c) target_link_libraries(float_short_test PRIVATE samplerate) add_test(NAME float_short_test COMMAND float_short_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Initialize Sample Rate Converter Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_full.md Creates a new sample rate converter object. Returns NULL on error, filling the provided error pointer. Ensure the converter type is valid. ```c SRC_STATE* src_new (int converter_type, int channels, int *error) ; ``` -------------------------------- ### Build and Test callback_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'callback_test' executable. It links against the 'samplerate' library. ```cmake add_executable(callback_test callback_test.c util.c util.h) target_link_libraries(callback_test PRIVATE samplerate) add_test(NAME callback_test COMMAND callback_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Create Callback-Based Converter in C Source: https://context7.com/libsndfile/libsamplerate/llms.txt Initializes a new SRC_STATE using a user-supplied callback function to fetch input data. The callback must return the number of frames provided or 0 when no more data is available. ```c #include typedef long (*src_callback_t)(void *cb_data, float **data); SRC_STATE* src_callback_new(src_callback_t func, int converter_type, int channels, int *error, void *cb_data); /* Example: Callback-based converter setup */ typedef struct { float *buffer; long total_frames; long current_frame; int channels; } CALLBACK_DATA; /* Callback function to supply input data */ static long input_callback(void *cb_data, float **data) { CALLBACK_DATA *p = (CALLBACK_DATA *)cb_data; if (p->current_frame >= p->total_frames) return 0; /* No more data */ long frames_available = p->total_frames - p->current_frame; long frames_to_return = (frames_available > 256) ? 256 : frames_available; *data = p->buffer + (p->current_frame * p->channels); p->current_frame += frames_to_return; return frames_to_return; } int callback_converter_example(void) { #define TOTAL_FRAMES 5000 float input_buffer[TOTAL_FRAMES * 2]; /* Stereo */ /* Fill with test data */ for (int i = 0; i < TOTAL_FRAMES * 2; i++) { input_buffer[i] = 0.3f * sinf(2.0f * 3.14159f * 440.0f * i / 44100.0f); } CALLBACK_DATA cb_data = { .buffer = input_buffer, .total_frames = TOTAL_FRAMES, .current_frame = 0, .channels = 2 }; int error; SRC_STATE *src_state = src_callback_new( input_callback, SRC_SINC_FASTEST, 2, /* stereo */ &error, &cb_data ); if (src_state == NULL) { printf("Error: %s\n", src_strerror(error)); return 1; } printf("Callback converter created successfully\n"); src_delete(src_state); return 0; } ``` -------------------------------- ### Build and Test clone_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'clone_test' executable. It links against the 'samplerate' library. ```cmake add_executable(clone_test clone_test.c util.c util.h) target_link_libraries(clone_test PRIVATE samplerate) add_test(NAME clone_test COMMAND clone_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Include libsamplerate Header Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api.md Include the samplerate.h header file to use libsamplerate functionality. You will also need to link your binary with the libsamplerate library. ```c #include ``` -------------------------------- ### src_callback_new Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_callback.md Initializes a new sample rate converter callback object. ```APIDOC ## src_callback_new ### Description Initializes a new sample rate converter callback object. Returns an anonymous pointer to an SRC_STATE object or NULL if an error occurs. ### Parameters - **func** (src_callback_t) - Required - User-supplied function to provide input data. - **converter_type** (int) - Required - The type of converter to use. - **channels** (int) - Required - Number of audio channels. - **error** (int*) - Required - Pointer to store error code if initialization fails. - **cb_data** (void*) - Required - User data passed to the callback function. ``` -------------------------------- ### Perform One-Shot Sample Rate Conversion Source: https://context7.com/libsndfile/libsamplerate/llms.txt Use src_simple for converting complete audio buffers in memory. Ensure the output buffer is sized appropriately to accommodate potential upsampling. ```c #include #include #include #include int src_simple(SRC_DATA *data, int converter_type, int channels); /* Example: Convert entire mono audio buffer from 44100Hz to 48000Hz */ int convert_audio_simple(void) { #define INPUT_FRAMES 1000 float input[INPUT_FRAMES]; float output[INPUT_FRAMES * 2]; /* Allocate extra for upsampling */ /* Fill input with audio data (sine wave for demo) */ for (int i = 0; i < INPUT_FRAMES; i++) { input[i] = 0.5f * sinf(2.0f * 3.14159f * 440.0f * i / 44100.0f); } SRC_DATA src_data; memset(&src_data, 0, sizeof(src_data)); src_data.data_in = input; src_data.data_out = output; src_data.input_frames = INPUT_FRAMES; src_data.output_frames = INPUT_FRAMES * 2; src_data.src_ratio = 48000.0 / 44100.0; /* 44.1kHz -> 48kHz */ int error = src_simple(&src_data, SRC_SINC_BEST_QUALITY, 1 /* mono */); if (error) { printf("Error: %s\n", src_strerror(error)); return 1; } printf("Input frames used: %ld\n", src_data.input_frames_used); printf("Output frames generated: %ld\n", src_data.output_frames_gen); /* Expected: ~1088 output frames (1000 * 48000/44100) */ return 0; } ``` -------------------------------- ### Initialize Callback Converter Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_callback.md Creates a new sample rate converter using the callback API. Returns a pointer to the SRC_STATE object or NULL on error. The callback function is invoked when the converter needs input data. ```c SRC_STATE* src_callback_new (src_callback_t func, int converter_type, int channels, int *error, void* cb_data) ; ``` -------------------------------- ### Build and Test nullptr_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'nullptr_test' executable. It links against the 'samplerate' library. ```cmake add_executable(nullptr_test nullptr_test.c util.c util.h) target_link_libraries(nullptr_test PRIVATE samplerate) add_test(NAME nullptr_test COMMAND nullptr_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Build and Test multi_channel_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'multi_channel_test' executable. It links against 'samplerate' and conditionally against FFTW3 if found. ```cmake add_executable(multi_channel_test multi_channel_test.c calc_snr.c util.c util.h) target_link_libraries(multi_channel_test PRIVATE samplerate $<$:FFTW3::fftw3> ) add_test(NAME multi_channel_test COMMAND multi_channel_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Configure SRC_DATA Structure in C Source: https://context7.com/libsndfile/libsamplerate/llms.txt Initialize the SRC_DATA structure to define input/output buffers and the conversion ratio for sample rate processing. ```c #include typedef struct { const float *data_in; /* Pointer to input audio samples */ float *data_out; /* Pointer to output buffer */ long input_frames; /* Number of input frames available */ long output_frames; /* Maximum output frames buffer can hold */ long input_frames_used; /* [OUTPUT] Frames consumed from input */ long output_frames_gen; /* [OUTPUT] Frames generated in output */ int end_of_input; /* Set to 1 for last buffer, 0 otherwise */ double src_ratio; /* output_sample_rate / input_sample_rate */ } SRC_DATA; /* Example: Setup SRC_DATA for converting 44100Hz to 48000Hz */ void setup_example(void) { float input[4096]; float output[4096]; SRC_DATA src_data; memset(&src_data, 0, sizeof(src_data)); src_data.data_in = input; src_data.data_out = output; src_data.input_frames = 4096; src_data.output_frames = 4096; src_data.src_ratio = 48000.0 / 44100.0; /* ~1.0884 */ src_data.end_of_input = 0; /* More data will follow */ } ``` -------------------------------- ### Build and Test reset_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'reset_test' executable. It links against the 'samplerate' library. ```cmake add_executable(reset_test reset_test.c util.c util.h) target_link_libraries(reset_test PRIVATE samplerate) add_test(NAME reset_test COMMAND reset_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Build and Test multichan_throughput_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'multichan_throughput_test' executable. It links against the 'samplerate' library. ```cmake add_executable(multichan_throughput_test multichan_throughput_test.c util.c util.h) target_link_libraries(multichan_throughput_test PRIVATE samplerate) ``` -------------------------------- ### Declare src_simple Function Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_simple.md The signature for the simple API function. Use this for processing entire audio buffers that fit in memory. ```c int src_simple (SRC_DATA *data, int converter_type, int channels) ; ``` -------------------------------- ### Build and Test termination_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'termination_test' executable. It links against the 'samplerate' library. ```cmake add_executable(termination_test termination_test.c util.c util.h) target_link_libraries(termination_test PRIVATE samplerate) add_test(NAME termination_test COMMAND termination_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Convert Audio Data Types Source: https://context7.com/libsndfile/libsamplerate/llms.txt Helper functions for converting between integer and normalized float audio formats. ```c #include void src_short_to_float_array(const short *in, float *out, int len); void src_float_to_short_array(const float *in, short *out, int len); void src_int_to_float_array(const int *in, float *out, int len); void src_float_to_int_array(const float *in, int *out, int len); /* Example: Convert 16-bit audio, process, and convert back */ int data_conversion_example(void) { #define NUM_SAMPLES 1000 /* Simulated 16-bit PCM audio input */ short input_16bit[NUM_SAMPLES]; for (int i = 0; i < NUM_SAMPLES; i++) { input_16bit[i] = (short)(16000.0 * sin(2.0 * 3.14159 * 440.0 * i / 44100.0)); } /* Convert to float for processing */ float input_float[NUM_SAMPLES]; src_short_to_float_array(input_16bit, input_float, NUM_SAMPLES); printf("Original 16-bit sample[0]: %d\n", input_16bit[0]); printf("Converted float sample[0]: %f\n", input_float[0]); /* Perform sample rate conversion */ float output_float[NUM_SAMPLES * 2]; SRC_DATA data = { .data_in = input_float, .data_out = output_float, .input_frames = NUM_SAMPLES, .output_frames = NUM_SAMPLES * 2, .src_ratio = 48000.0 / 44100.0, }; int error = src_simple(&data, SRC_SINC_MEDIUM_QUALITY, 1); if (error) { printf("Error: %s\n", src_strerror(error)); return 1; } /* Convert back to 16-bit PCM (with clipping protection) */ short output_16bit[NUM_SAMPLES * 2]; src_float_to_short_array(output_float, output_16bit, data.output_frames_gen); printf("Output frames: %ld\n", data.output_frames_gen); printf("Output 16-bit sample[0]: %d\n", output_16bit[0]); return 0; } ``` ```c /* 32-bit integer conversion example */ int int32_conversion_example(void) { int input_32bit[100]; float floats[100]; int output_32bit[100]; /* Fill with 32-bit audio (full range: -2147483648 to 2147483647) */ for (int i = 0; i < 100; i++) { input_32bit[i] = (int)(2000000000.0 * sin(2.0 * 3.14159 * i / 50.0)); } /* Convert to float */ src_int_to_float_array(input_32bit, floats, 100); /* Process... */ /* Convert back with clipping */ src_float_to_int_array(floats, output_32bit, 100); return 0; } ``` -------------------------------- ### Build and Test downsample_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'downsample_test' executable. It links against the 'samplerate' library. ```cmake add_executable(downsample_test downsample_test.c util.c util.h) target_link_libraries(downsample_test PRIVATE samplerate) add_test(NAME downsample_test COMMAND downsample_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Build and Test misc_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'misc_test' executable. It links against the 'samplerate' library. ```cmake add_executable(misc_test misc_test.c util.c util.h) target_link_libraries(misc_test PRIVATE samplerate) add_test(NAME misc_test COMMAND misc_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Build and Test snr_bw_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'snr_bw_test' executable. It links against 'samplerate' and conditionally against FFTW3 if found. ```cmake add_executable(snr_bw_test snr_bw_test.c calc_snr.c util.c util.h) target_link_libraries(snr_bw_test PRIVATE samplerate $<$:FFTW3::fftw3> ) add_test(NAME snr_bw_test COMMAND snr_bw_test util.c util.h WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Create and Manage Converter State Source: https://context7.com/libsndfile/libsamplerate/llms.txt Initialize a converter state object using src_new and ensure it is freed with src_delete to prevent memory leaks. ```c #include SRC_STATE* src_new(int converter_type, int channels, int *error); /* Example: Create and initialize a stereo converter */ int create_converter_example(void) { int error; /* Create converter for stereo audio using best quality */ SRC_STATE *src_state = src_new(SRC_SINC_BEST_QUALITY, 2 /* stereo */, &error); if (src_state == NULL) { printf("Error creating converter: %s\n", src_strerror(error)); return 1; } /* Get channel count to verify */ int channels = src_get_channels(src_state); printf("Converter created with %d channels\n", channels); /* Clean up when done */ src_state = src_delete(src_state); /* Always returns NULL */ return 0; } ``` -------------------------------- ### Build and Test src-evaluate Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'src-evaluate' executable. It links against 'samplerate', conditionally against FFTW3, and libsndfile if found. ```cmake add_executable(src-evaluate src-evaluate.c util.c util.h calc_snr.c) target_link_libraries(src-evaluate PRIVATE samplerate $<$:FFTW3::fftw3> $<$:${SNDFILE_TARGET}> ) ``` -------------------------------- ### Build and Test throughput_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'throughput_test' executable. It links against the 'samplerate' library. ```cmake add_executable(throughput_test throughput_test.c util.c util.h) target_link_libraries(throughput_test PRIVATE samplerate) ``` -------------------------------- ### Link varispeed-play executable with platform-specific audio Source: https://github.com/libsndfile/libsamplerate/blob/master/examples/CMakeLists.txt Defines the varispeed-play executable and links platform-specific audio libraries based on the operating system. ```cmake add_executable(varispeed-play varispeed-play.c audio_out.c audio_out.h) target_link_libraries(varispeed-play PRIVATE samplerate $<$:${SNDFILE_TARGET}>) if(WIN32) target_link_libraries(varispeed-play PRIVATE winmm) elseif(APPLE) target_link_libraries(varispeed-play PRIVATE "-framework CoreAudio") elseif(ALSA_FOUND) target_link_libraries(varispeed-play PRIVATE ALSA::ALSA) endif() ``` -------------------------------- ### Set Conversion Ratio with src_set_ratio Source: https://context7.com/libsndfile/libsamplerate/llms.txt Sets a new conversion ratio with an immediate step change. Useful for precise control of playback speed. ```c #include int src_set_ratio(SRC_STATE *state, double new_ratio); /* Example: Abrupt speed change during playback */ int set_ratio_example(void) { int error; SRC_STATE *src_state = src_new(SRC_SINC_FASTEST, 2, &error); if (src_state == NULL) { printf("Error: %s\n", src_strerror(error)); return 1; } float input[2048], output[2048]; SRC_DATA data = { .data_in = input, .data_out = output, .input_frames = 512, .output_frames = 512, .src_ratio = 1.0, /* Normal speed */ .end_of_input = 0 }; /* Process at normal speed */ src_process(src_state, &data); printf("Normal speed: %ld frames\n", data.output_frames_gen); /* Force immediate ratio change (step response, no interpolation) */ error = src_set_ratio(src_state, 2.0); /* Double speed */ if (error) { printf("Set ratio error: %s\n", src_strerror(error)); src_delete(src_state); return 1; } /* Without src_set_ratio, changing src_data.src_ratio smoothly interpolates between old and new ratios. src_set_ratio forces an immediate change. */ data.data_in = input + 512; data.data_out = output; data.src_ratio = 2.0; src_process(src_state, &data); printf("Double speed: %ld frames\n", data.output_frames_gen); src_delete(src_state); return 0; } ``` -------------------------------- ### src_simple - Simple One-Shot Conversion Source: https://context7.com/libsndfile/libsamplerate/llms.txt Performs sample rate conversion on a single complete buffer of audio data, ideal for converting entire audio files in memory. ```APIDOC ## src_simple ### Description Performs sample rate conversion on a single complete buffer of audio data. ### Parameters - **data** (SRC_DATA*) - Required - Pointer to the structure containing input/output buffers, frame counts, and conversion ratio. - **converter_type** (int) - Required - The type of converter algorithm to use (e.g., SRC_SINC_BEST_QUALITY). - **channels** (int) - Required - The number of audio channels. ### Response - **int** - Returns 0 on success, or an error code on failure. ``` -------------------------------- ### Perform Streaming Sample Rate Conversion Source: https://context7.com/libsndfile/libsamplerate/llms.txt Use src_process within a loop to convert audio data in chunks. The end_of_input flag must be set correctly to signal the final block. ```c #include #include #include #include int src_process(SRC_STATE *state, SRC_DATA *data); /* Example: Stream convert audio in chunks */ int streaming_conversion_example(void) { #define BLOCK_LEN 256 #define TOTAL_INPUT 10000 float input[TOTAL_INPUT]; float output[TOTAL_INPUT * 2]; /* Fill input with test data */ for (int i = 0; i < TOTAL_INPUT; i++) { input[i] = 0.5f * sinf(2.0f * 3.14159f * 1000.0f * i / 44100.0f); } int error; SRC_STATE *src_state = src_new(SRC_SINC_FASTEST, 1 /* mono */, &error); if (src_state == NULL) { printf("Error: %s\n", src_strerror(error)); return 1; } SRC_DATA src_data; int current_in = 0, current_out = 0; double src_ratio = 48000.0 / 44100.0; /* Process in blocks */ while (1) { int remaining_in = TOTAL_INPUT - current_in; int remaining_out = (TOTAL_INPUT * 2) - current_out; src_data.data_in = input + current_in; src_data.data_out = output + current_out; src_data.input_frames = (remaining_in < BLOCK_LEN) ? remaining_in : BLOCK_LEN; src_data.output_frames = (remaining_out < BLOCK_LEN) ? remaining_out : BLOCK_LEN; src_data.src_ratio = src_ratio; src_data.end_of_input = (current_in + src_data.input_frames >= TOTAL_INPUT) ? 1 : 0; error = src_process(src_state, &src_data); if (error) { printf("Error: %s\n", src_strerror(error)); src_delete(src_state); return 1; } current_in += src_data.input_frames_used; current_out += src_data.output_frames_gen; /* Exit when all input consumed and no more output */ if (src_data.end_of_input && src_data.output_frames_gen == 0) break; } printf("Total input frames: %d\n", current_in); printf("Total output frames: %d\n", current_out); src_delete(src_state); return 0; } ``` -------------------------------- ### FFTW3 Dependency Check and Configuration Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Configures the FFTW3 library dependency. It uses pkg-config if available and CMake version is sufficient, otherwise falls back to find_package. The result is stored in HAVE_FFTW3. ```cmake if((NOT VCPKG_TOOLCHAIN) AND PKG_CONFIG_FOUND AND (NOT CMAKE_VERSION VERSION_LESS 3.6)) pkg_check_modules(FFTW3 fftw3 IMPORTED_TARGET) if(FFTW3_FOUND) add_library(FFTW3::fftw3 INTERFACE IMPORTED) target_link_libraries(FFTW3::fftw3 INTERFACE PkgConfig::FFTW3) endif() else() find_package(FFTW3) endif() set(HAVE_FFTW3 ${FFTW3_FOUND} PARENT_SCOPE) ``` -------------------------------- ### Build and Test varispeed_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'varispeed_test' executable. It links against 'samplerate' and conditionally against FFTW3 if found. ```cmake add_executable(varispeed_test varispeed_test.c calc_snr.c util.c util.h) target_link_libraries(varispeed_test PRIVATE samplerate $<$:FFTW3::fftw3> ) add_test(NAME varispeed_test COMMAND varispeed_test util.c util.h WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### src_callback_new Source: https://context7.com/libsndfile/libsamplerate/llms.txt Creates a new converter instance that pulls input data via a user-supplied callback function. ```APIDOC ## src_callback_new ### Description Creates a converter that pulls input data via a user-supplied callback function. Ideal for real-time applications with variable playback speed. ### Parameters - **func** (src_callback_t) - Required - The callback function to supply input data. - **converter_type** (int) - Required - The type of converter to use (e.g., SRC_SINC_FASTEST). - **channels** (int) - Required - Number of audio channels. - **error** (int*) - Required - Pointer to store error codes. - **cb_data** (void*) - Required - User-defined data passed to the callback. ### Response - **SRC_STATE*** - A pointer to the converter state, or NULL on failure. ``` -------------------------------- ### src_process Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_full.md Processes audio data using the converter state. ```APIDOC ## src_process ### Description Processes input data provided in an SRC_DATA struct using the specified converter state. ### Parameters - **state** (SRC_STATE*) - Required - The converter state. - **data** (SRC_DATA*) - Required - Struct containing input/output buffers and conversion parameters. ### Request Body (SRC_DATA fields) - **data_in** (float*) - Required - Pointer to input samples. - **data_out** (float*) - Required - Pointer to output buffer. - **input_frames** (long) - Required - Number of input frames. - **output_frames** (long) - Required - Max output frames. - **src_ratio** (double) - Required - Ratio of output_sample_rate / input_sample_rate. - **end_of_input** (int) - Required - 0 if more data, 1 otherwise. ### Response - **int** - Returns non-zero if an error occurs. ``` -------------------------------- ### Link timewarp-file executable Source: https://github.com/libsndfile/libsamplerate/blob/master/examples/CMakeLists.txt Defines the timewarp-file executable and links it against samplerate and optional SndFile libraries. ```cmake add_executable(timewarp-file timewarp-file.c) target_link_libraries(timewarp-file PRIVATE samplerate $<$:${SNDFILE_TARGET}>) ``` -------------------------------- ### Build and Test callback_hang_test Executable Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Compiles and adds a test for the 'callback_hang_test' executable. It links against the 'samplerate' library. ```cmake add_executable(callback_hang_test callback_hang_test.c util.c util.h) target_link_libraries(callback_hang_test PRIVATE samplerate) add_test(NAME callback_hang_test COMMAND callback_hang_test WORKING_DIRECTORY ${PROJECT_BINARY_DIR}/src) ``` -------------------------------- ### Read Data Using Callback Converter Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_callback.md Reads converted audio data from the callback-based sample rate converter. It generates a specified number of output frames based on the conversion ratio. Returns the number of frames generated or zero on error or end of input. ```c long src_callback_read (SRC_STATE *state, double src_ratio, long frames, float *data) ; ``` -------------------------------- ### Auxiliary Data Conversion Functions Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_misc.md Functions for converting between float and short/int audio data formats. ```APIDOC ## Auxiliary Functions ### Description Utility functions to convert arrays of float data to/from short or int data. Float data is assumed to be in the range [-1.0, 1.0]. ### Functions - **src_short_to_float_array** (const short *in, float *out, int len) - **src_float_to_short_array** (const float *in, short *out, int len) - **src_int_to_float_array** (const int *in, float *out, int len) - **src_float_to_int_array** (const float *in, int *out, int len) ### Notes Data is automatically scaled during conversion. Values exceeding the range of short/int are clipped. ``` -------------------------------- ### Auxiliary Data Conversion Functions Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_misc.md Functions for converting between float and short or int audio data formats, assuming a range of [-1.0, 1.0] for float values. ```c void src_short_to_float_array (const short *in, float *out, int len) ; void src_float_to_short_array (const float *in, short *out, int len) ; void src_int_to_float_array (const int *in, float *out, int len) ; void src_float_to_int_array (const float *in, int *out, int len) ; ``` -------------------------------- ### src_simple Function Source: https://github.com/libsndfile/libsamplerate/blob/master/docs/api_simple.md The src_simple function is the core of the simple API. It performs sample rate conversion on audio data that can be held entirely in memory. It requires the caller to provide input and output buffers, specify the converter type and number of channels, and set the source ratio. ```APIDOC ## src_simple Function ### Description Performs sample rate conversion on audio data that can be held entirely in memory. This function is suitable for processing entire audio files at once, assuming a constant input to output sample rate ratio. ### Method C Function Call ### Endpoint N/A (C Library Function) ### Parameters #### Input Parameters - **data** (SRC_DATA *) - Pointer to an SRC_DATA struct containing input and output buffers, frame counts, and the source ratio. - **converter_type** (int) - An integer representing the desired conversion algorithm. Must be one of the values defined in samplerate.h and documented [here](api_misc.md#converters). - **channels** (int) - The number of audio channels to process. Input and output channels are always equal. #### SRC_DATA Struct Fields (to be filled by caller): - **data_in** (const float *) - Pointer to the input audio samples. - **input_frames** (long) - The total number of frames in the input data. - **data_out** (float *) - Pointer to the buffer where output audio samples will be stored. - **output_frames** (long) - The maximum number of frames that can be stored in the data_out buffer. - **src_ratio** (double) - The ratio of output sample rate to input sample rate (output_sample_rate / input_sample_rate). ### Return Value - **0** on success. - **Non-zero** on error. The error code can be converted to a string using functions documented [here](api_misc.md#error-reporting). ### Post-conditions (fields updated by the function): - **input_frames_used** (long) - The number of input frames consumed during the conversion. - **output_frames_gen** (long) - The number of output frames generated and written to data_out. ### Request Example ```c // Example usage (conceptual) #include "samplerate.h" // Assume input_samples, output_buffer, num_input_frames, num_output_frames, and channels are defined SRC_DATA src_data; src_data.data_in = input_samples; src_data.input_frames = num_input_frames; src_data.data_out = output_buffer; src_data.output_frames = num_output_frames; src_data.src_ratio = (double)output_sample_rate / input_sample_rate; src_data.end_of_input = 1; // For simple API, typically set to 1 if all input is provided at once int result = src_simple(&src_data, SRC_SINC_FASTEST, channels); if (result == 0) { // Conversion successful long frames_generated = src_data.output_frames_gen; long frames_used = src_data.input_frames_used; // Process the generated audio data in output_buffer } else { // Handle error } ``` ### Response #### Success Response (0) - **output_frames_gen** (long) - Number of output frames generated. - **input_frames_used** (long) - Number of input frames used. #### Response Example ```json { "status": "success", "output_frames_generated": 1000, "input_frames_used": 500 } ``` ``` -------------------------------- ### src_new - Create Converter State Source: https://context7.com/libsndfile/libsamplerate/llms.txt Creates a new sample rate converter state object for streaming conversion. ```APIDOC ## src_new ### Description Initializes a new converter state object required for streaming audio conversion. ### Parameters - **converter_type** (int) - Required - The type of converter algorithm to use. - **channels** (int) - Required - The number of audio channels. - **error** (int*) - Required - Pointer to an integer to store error codes if initialization fails. ### Response - **SRC_STATE*** - Returns a pointer to the new converter state, or NULL if an error occurred. ``` -------------------------------- ### Check for signal Function Source: https://github.com/libsndfile/libsamplerate/blob/master/tests/CMakeLists.txt Verifies the existence of the 'signal' function, used for handling signals. ```cmake check_function_exists(signal HAVE_SIGNAL) ```