### Configure and Install Opus Package Information Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This snippet configures and installs the Opus package information files (.pc and CMake config files). It sets installation directories, generates the opus.pc file from a template, and installs it to the pkgconfig directory. It also handles the creation and installation of OpusConfig.cmake and OpusConfigVersion.cmake for CMake's package management system. ```cmake set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix ${CMAKE_INSTALL_PREFIX}) set(libdir ${CMAKE_INSTALL_FULL_LIBDIR}) set(includedir ${CMAKE_INSTALL_FULL_INCLUDEDIR}) set(VERSION ${PACKAGE_VERSION}) if(HAVE_LIBM) set(LIBM "-lm") endif() configure_file(opus.pc.in opus.pc) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/opus.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) if(OPUS_INSTALL_CMAKE_CONFIG_MODULE) set(CPACK_GENERATOR TGZ) include(CPack) set(CMAKE_INSTALL_PACKAGEDIR ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}) install(EXPORT OpusTargets NAMESPACE Opus:: DESTINATION ${CMAKE_INSTALL_PACKAGEDIR}) include(CMakePackageConfigHelpers) set(INCLUDE_INSTALL_DIR ${CMAKE_INSTALL_INCLUDEDIR}) configure_package_config_file(${PROJECT_SOURCE_DIR}/cmake/OpusConfig.cmake.in OpusConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_PACKAGEDIR} PATH_VARS INCLUDE_INSTALL_DIR INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) write_basic_package_version_file(OpusConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/OpusConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/OpusConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_PACKAGEDIR}) endif() ``` -------------------------------- ### CMake Minimum Version and Module Path Setup Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Specifies the minimum required CMake version and adds a custom CMake module path to the build environment. This ensures compatibility and allows the use of project-specific CMake modules. ```cmake cmake_minimum_required(VERSION 3.16) list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake") ``` -------------------------------- ### Build Opus Project using CMake Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md This command initiates the build process for the Opus project using CMake after configuration. It requires CMake to be installed and assumes the command is run from the build directory. The output will be the compiled project files. ```shell cmake --build . ``` -------------------------------- ### Install pkg-config Module Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Determines whether to install the `pkg-config` module file. This facilitates easier integration of the Opus library with other projects using `pkg-config`. ```cmake set(OPUS_INSTALL_PKG_CONFIG_MODULE_HELP_STR "install pkg-config module.") option(OPUS_INSTALL_PKG_CONFIG_MODULE ${OPUS_INSTALL_PKG_CONFIG_MODULE_HELP_STR} ON) add_feature_info(OPUS_INSTALL_PKG_CONFIG_MODULE OPUS_INSTALL_PKG_CONFIG_MODULE ${OPUS_INSTALL_PKG_CONFIG_MODULE_HELP_STR}) ``` -------------------------------- ### Complete Encode/Decode Pipeline Source: https://context7.com/voxkit/kopus/llms.txt Demonstrates a full audio processing pipeline, including encoding raw PCM to OPUS and then decoding it back. This example emphasizes resource management using the 'use' function for both encoder and decoder, ensuring proper cleanup. It also includes a basic quality verification by comparing original and decoded samples. ```kotlin import io.voxkit.kopus.* import kotlin.math.sin import kotlin.math.PI fun processAudio() { val sampleRate = SampleRate.RATE_48K val channels = Channels.STEREO val frameSize = 960 // 20ms at 48kHz // Generate test audio: 440Hz sine wave val pcmInput = ShortArray(frameSize * 2) for (i in 0 until frameSize) { val sample = (Short.MAX_VALUE * 0.5 * sin(2 * PI * 440 * i / 48000.0)).toInt().toShort() pcmInput[i * 2] = sample pcmInput[i * 2 + 1] = sample } // Use-based resource management Opus.encoder(sampleRate, channels, OpusApplication.AUDIO).use { encoder -> // Encode val encodedBuffer = ByteArray(OpusEncoder.DEFAULT_OUTPUT_BUFFER_SIZE) val encodedLength = encoder.encode(pcmInput, frameSize, encodedBuffer) println("Compressed ${pcmInput.size * 2} bytes to $encodedLength bytes") // Decode Opus.decoder(sampleRate, channels).use { decoder -> val decodedBuffer = ShortArray(frameSize * 2) val encodedPacket = encodedBuffer.copyOf(encodedLength) val samplesDecoded = decoder.decode(encodedPacket, frameSize, decodedBuffer) println("Decoded $samplesDecoded samples per channel") // Verify round-trip quality var maxDiff = 0 for (i in pcmInput.indices) { val diff = Math.abs(pcmInput[i] - decodedBuffer[i]) if (diff > maxDiff) maxDiff = diff } println("Max sample difference: $maxDiff") } } // Resources automatically closed } ``` -------------------------------- ### Project Version and Name Configuration Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Includes custom modules to get the package version and set up the project name and version. This is essential for identifying and managing different releases of the Opus library. ```cmake include(OpusPackageVersion) get_package_version(PACKAGE_VERSION PROJECT_VERSION) project(Opus LANGUAGES C VERSION ${PROJECT_VERSION}) ``` -------------------------------- ### Clone Opus Repository using Git Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md This command clones the Opus project repository from GitLab using Git. It requires Git to be installed on your system. The output is the Opus project files in a new directory. ```shell git clone https://gitlab.xiph.org/xiph/opus ``` -------------------------------- ### Install Kopus Library Dependency Source: https://github.com/voxkit/kopus/blob/main/README.md This snippet shows how to add the Kopus library dependency to your project's build.gradle.kts file. Ensure you replace '$kopus_version' with the actual version of the Kopus library you wish to use. ```kotlin dependencies { implementation("io.voxkit:kopus:$kopus_version") } ``` -------------------------------- ### Install CMake Config Module Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Determines whether to install the CMake package configuration module files. This enables other CMake projects to easily find and use the Opus library. ```cmake set(OPUS_INSTALL_CMAKE_CONFIG_MODULE_HELP_STR "install CMake package config module.") option(OPUS_INSTALL_CMAKE_CONFIG_MODULE ${OPUS_INSTALL_CMAKE_CONFIG_MODULE_HELP_STR} ON) add_feature_info(OPUS_INSTALL_CMAKE_CONFIG_MODULE OPUS_INSTALL_CMAKE_CONFIG_MODULE ${OPUS_INSTALL_CMAKE_CONFIG_MODULE_HELP_STR}) ``` -------------------------------- ### Configuring Programs Build Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Defines a CMake option to control whether auxiliary programs are built alongside the library. This is useful for building command-line tools or examples related to Opus. ```cmake set(OPUS_BUILD_PROGRAMS_HELP_STR "build programs.") option(OPUS_BUILD_PROGRAMS ${OPUS_BUILD_PROGRAMS_HELP_STR} OFF) add_feature_info(OPUS_BUILD_PROGRAMS OPUS_BUILD_PROGRAMS ${OPUS_BUILD_PROGRAMS_HELP_STR}) ``` -------------------------------- ### Including Opus Build Configuration Modules Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Includes several custom CMake modules that handle various aspects of the Opus build, such as functions, build types, configuration, sources, and installation directories. These modules encapsulate common build logic. ```cmake include(OpusFunctions) include(OpusBuildtype) include(OpusConfig) include(OpusSources) include(GNUInstallDirs) include(CMakeDependentOption) include(FeatureSummary) ``` -------------------------------- ### Configure Opus Build with CMake Options Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md This CMake command configures the build for the Opus project. It specifies build options like enabling programs and testing using the `-D` flag. Ensure CMake is installed and the command is run from the build directory. ```shell cmake .. -DOPUS_BUILD_PROGRAMS=ON -DOPUS_BUILD_TESTING=ON ``` -------------------------------- ### Build Opus Demo Executables Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This section defines and configures executables for Opus demonstrations. It includes building 'opus_custom_demo' if custom modes are enabled, and the main 'opus_demo'. Both executables are linked against the opus library and configured with appropriate include directories and compile definitions. Dependencies include the opus library and potentially silk, celt, and dnn for specific include paths. ```cmake if(OPUS_BUILD_PROGRAMS) # demo if(OPUS_CUSTOM_MODES) add_executable(opus_custom_demo ${opus_custom_demo_sources}) target_include_directories(opus_custom_demo PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(opus_custom_demo PRIVATE opus) target_compile_definitions(opus_custom_demo PRIVATE OPUS_BUILD) endif() add_executable(opus_demo ${opus_demo_sources}) target_include_directories(opus_demo PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_include_directories(opus_demo PRIVATE silk) # debug.h target_include_directories(opus_demo PRIVATE celt) # arch.h target_include_directories(opus_demo PRIVATE dnn) target_link_libraries(opus_demo PRIVATE opus ${OPUS_REQUIRED_LIBRARIES}) target_compile_definitions(opus_demo PRIVATE OPUS_BUILD) # compare add_executable(opus_compare ${opus_compare_sources}) target_include_directories(opus_compare PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(opus_compare PRIVATE opus ${OPUS_REQUIRED_LIBRARIES}) endif() ``` -------------------------------- ### Build LPCNet Software Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Builds the LPCNet software from source. Requires running autogen.sh for Git checkouts to download models. Options like `--disable-dot-product` can be used to control quantization and compatibility on ARMv7. It is recommended to set CFLAGS for vectorization before configuring. ```shell ./autogen.sh ./configure make ``` ```shell ./configure --disable-dot-product ``` ```shell export CFLAGS='-Ofast -g -march=native' ./configure ``` ```shell export CFLAGS='-Ofast -g -mfpu=neon' ./configure ``` -------------------------------- ### Encode and Decode PCM Audio with lpcnet_demo Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Demonstrates encoding a 16 kHz, 16-bit PCM file to a compressed binary format and decoding it back. The compressed data is 8 bytes per 40-ms packet. ```shell ./lpcnet_demo -encode input.pcm compressed.bin ``` ```shell ./lpcnet_demo -decode compressed.bin output.pcm ``` -------------------------------- ### Basic OPUS Encoding and Decoding with Kopus Source: https://github.com/voxkit/kopus/blob/main/README.md Demonstrates the fundamental process of initializing an OPUS encoder and decoder using the Kopus library. It covers encoding raw PCM audio data and then decoding the resulting OPUS packets back into PCM. Proper resource management by closing the encoder and decoder is crucial. ```kotlin import io.voxkit.kopus.* // Create encoder val encoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO, application = OpusApplication.AUDIO ) // Create decoder val decoder = Opus.decoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO ) // Encode PCM data val pcmInput: ShortArray = // your audio samples val frameSize = 960 // 20ms at 48kHz val encodedBuffer = ByteArray(OpusEncoder.DEFAULT_OUTPUT_BUFFER_SIZE) val encodedLength = encoder.encode(pcmInput, frameSize, encodedBuffer) // Decode back to PCM val decodedBuffer = ShortArray(frameSize * 2) // 2 channels val encodedData = encodedBuffer.copyOf(encodedLength) val decodedSamples = decoder.decode(encodedData, frameSize, decodedBuffer) // Don't forget to close resources encoder.close() decoder.close() ``` -------------------------------- ### Run Opus Tests with Meson Source: https://github.com/voxkit/kopus/blob/main/opus/meson/README.md Executes the test suite for the Opus project using Meson. This command verifies the functionality and correctness of the compiled library. ```shell meson test -C builddir ``` -------------------------------- ### Clone Opus Repository using Git Source: https://github.com/voxkit/kopus/blob/main/opus/meson/README.md Clones the Opus project repository from its GitLab instance and navigates into the newly created directory. This is the initial step before configuring the build. ```shell git clone https://gitlab.xiph.org/xiph/opus cd opus ``` -------------------------------- ### Compile Opus Project using Meson Source: https://github.com/voxkit/kopus/blob/main/opus/meson/README.md Compiles the Opus project using the Meson build system. The '-C builddir' argument specifies the build directory where compilation artifacts will be placed. ```shell meson compile -C builddir ``` -------------------------------- ### Generate Visual Studio Projects with Meson Source: https://github.com/voxkit/kopus/blob/main/opus/meson/README.md Generates Visual Studio project files for the Opus build using Meson. This command is typically run from a Visual Studio Command Prompt and enables the test suite. ```shell meson setup builddir -Dtests=enabled --backend vs ``` -------------------------------- ### Decode OPUS to Floating-point PCM Source: https://context7.com/voxkit/kopus/llms.txt Decodes OPUS audio into floating-point samples, suitable for high-precision audio processing. Similar to 16-bit PCM decoding, it requires decoder setup and the decode method call. The output buffer will contain normalized float values between -1.0 and 1.0. ```kotlin import io.voxkit.kopus.* val decoder = Opus.decoder(SampleRate.RATE_48K, Channels.STEREO) val frameSize = 960 val encodedData = ByteArray(120) // OPUS packet val decodedBuffer = FloatArray(frameSize * 2) // Stereo output val samplesDecoded = decoder.decode( data = encodedData, frameSize = frameSize, pcm = decodedBuffer, decodeFec = false ) // Normalized float values between -1.0 and 1.0 val leftChannel = decodedBuffer[0] val rightChannel = decodedBuffer[1] decoder.close() ``` -------------------------------- ### Test LPCNet Packet Loss Concealment (PLC) Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Tests the packet loss concealment capabilities of LPCNet. Requires downloading a PLC model first. The demo takes a PLC model, an error pattern file (1 for lost, 0 for not lost packets), input PCM, and an output PCM file. ```shell ./download_model.sh plc-3b1eab4 ``` ```shell ./download_model.sh plc_challenge ``` ```shell ./lpcnet_demo -plc_file noncausal_dc error_pattern.txt input.pcm output.pcm ``` -------------------------------- ### Create and Navigate to Build Directory using Shell Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md These commands create a build directory within the Opus project and then navigate into it. This is a standard practice for out-of-source builds with CMake, keeping build artifacts separate from source files. ```shell cd opus mkdir build cd build ``` -------------------------------- ### Generate Training Data for LPCNet Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Generates training data for LPCNet models. It takes a 16 kHz, 16-bit raw PCM audio file as input and produces feature and data files. This process involves multiple passes with different filters to create a large training dataset. ```shell ./dump_data -train input.s16 features.f32 data.s16 ``` -------------------------------- ### Synthesize Speech with LPCNet (Python/GPU) Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Synthesizes speech using a trained LPCNet model in Python, leveraging a GPU. This process is noted to be slow. It involves generating test features and then running the test script with the model, features, and output file. ```shell ./dump_data -test test_input.s16 test_features.f32 ``` ```shell ./training_tf2/test_lpcnet.py lpcnet_model_name.h5 test_features.f32 test.s16 ``` -------------------------------- ### Configure Opus Build with Meson (Disable Tests) Source: https://github.com/voxkit/kopus/blob/main/opus/meson/README.md Sets up the build directory for the Opus project using Meson, disabling the test suite. Meson's '-D' flag is used to specify build configuration options. ```shell meson setup builddir -Dtests=disabled ``` -------------------------------- ### Library Version and Error Handling with Kotlin Source: https://context7.com/voxkit/kopus/llms.txt Shows how to query the Opus library version and convert negative error codes returned by Opus functions into human-readable error messages. It includes a try-catch block for robust encoder initialization and demonstrates common error codes. ```kotlin import io.voxkit.kopus.* // Get library version val version = Opus.version println("Using $version") // Output: Using libopus 1.5.2 // Error handling try { val encoder = Opus.encoder( SampleRate.RATE_48K, Channels.STEREO, OpusApplication.AUDIO ) val pcm = ShortArray(960 * 2) val output = ByteArray(OpusEncoder.DEFAULT_OUTPUT_BUFFER_SIZE) val result = encoder.encode(pcm, 960, output) if (result < 0) { val errorMsg = Opus.getErrorString(result) println("Encoding error: $errorMsg") } else { println("Successfully encoded $result bytes") } encoder.close() } catch (e: Exception) { println("Failed to initialize encoder: ${e.message}") } // Common error codes println(Opus.getErrorString(0)) // "success" println(Opus.getErrorString(-1)) // "bad argument" println(Opus.getErrorString(-2)) // "buffer too small" ``` -------------------------------- ### Floating-Point API Enable Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables the floating-point API, which requires a C math library that supports floating-point operations. This is typically used on systems with a capable FPU. ```cmake set(OPUS_ENABLE_FLOAT_API_HELP_STR "compile with the floating point API (for machines with float library).") option(OPUS_ENABLE_FLOAT_API ${OPUS_ENABLE_FLOAT_API_HELP_STR} ON) add_feature_info(OPUS_ENABLE_FLOAT_API OPUS_ENABLE_FLOAT_API ${OPUS_ENABLE_FLOAT_API_HELP_STR}) ``` -------------------------------- ### Train LPCNet Model with TensorFlow 2 Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Trains a new LPCNet model using TensorFlow 2 and Keras on a system with a GPU. It requires the generated feature and data files. The training process outputs h5 files for each iteration. If memory errors occur, try specifying a smaller --batch-size. ```python python3 training_tf2/train_lpcnet.py features.f32 data.s16 model_name ``` ```python python3 training_tf2/train_lpcnet.py --batch-size 128 features.f32 data.s16 model_name ``` -------------------------------- ### Creating an OPUS Decoder Source: https://context7.com/voxkit/kopus/llms.txt Create a decoder to decompress OPUS-encoded audio back to PCM format. ```APIDOC ## Creating an OPUS Decoder ### Description Create a decoder to decompress OPUS-encoded audio back to PCM format. ### Method `Opus.decoder()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin import io.voxkit.kopus.* // Create decoder matching encoder configuration val decoder = Opus.decoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO ) // Decoder for mono voice calls val voipDecoder = Opus.decoder( sampleRate = SampleRate.RATE_16K, channels = Channels.MONO ) // Always close when done decoder.close() voipDecoder.close() ``` ### Response #### Success Response (200) An `OpusDecoder` instance configured with the specified sample rate and channel count. #### Response Example ```kotlin // An OpusDecoder instance val decoder = Opus.decoder(SampleRate.RATE_48K, Channels.STEREO) ``` ``` -------------------------------- ### OSCE Enable Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables the Open Sound Control (OSC) Engine feature. This likely pertains to integration with OSC for control or communication purposes. ```cmake set(OPUS_OSCE_HELP_STR "enable OSCE.") option(OPUS_OSCE ${OPUS_OSCE_HELP_STR} OFF) add_feature_info(OPUS_OSCE OPUS_OSCE ${OPUS_OSCE_HELP_STR}) ``` -------------------------------- ### Creating an OPUS Encoder Source: https://context7.com/voxkit/kopus/llms.txt Create an encoder to compress PCM audio data into OPUS format with configurable sample rate, channel count, and application mode. ```APIDOC ## Creating an OPUS Encoder ### Description Create an encoder to compress PCM audio data into OPUS format with configurable sample rate, channel count, and application mode. ### Method `Opus.encoder()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```kotlin import io.voxkit.kopus.* // Create stereo encoder for high-quality music at 48kHz val encoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO, application = OpusApplication.AUDIO ) // For voice calls, use VOIP mode with lower sample rate val voipEncoder = Opus.encoder( sampleRate = SampleRate.RATE_16K, channels = Channels.MONO, application = OpusApplication.VOIP ) // For low-latency real-time applications val lowLatencyEncoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.MONO, application = OpusApplication.LOW_DELAY ) // Always close when done encoder.close() voipEncoder.close() lowLatencyEncoder.close() ``` ### Response #### Success Response (200) An `OpusEncoder` instance configured with the specified parameters. #### Response Example ```kotlin // An OpusEncoder instance val encoder = Opus.encoder(SampleRate.RATE_48K, Channels.STEREO, OpusApplication.AUDIO) ``` ``` -------------------------------- ### Fixed-Point Compilation Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables compilation using fixed-point arithmetic, which is beneficial for systems lacking a fast floating-point unit (FPU). This can improve performance on embedded systems. ```cmake set(OPUS_FIXED_POINT_HELP_STR "compile as fixed-point (for machines without a fast enough FPU).") option(OPUS_FIXED_POINT ${OPUS_FIXED_POINT_HELP_STR} OFF) add_feature_info(OPUS_FIXED_POINT OPUS_FIXED_POINT ${OPUS_FIXED_POINT_HELP_STR}) ``` -------------------------------- ### Apple Framework Build Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Conditionally defines an option to build a Framework bundle specifically for Apple systems when the build is running on an Apple platform. This is a common packaging format for macOS and iOS. ```cmake if(APPLE) set(OPUS_BUILD_FRAMEWORK_HELP_STR "build Framework bundle for Apple systems.") option(OPUS_BUILD_FRAMEWORK ${OPUS_BUILD_FRAMEWORK_HELP_STR} OFF) add_feature_info(OPUS_BUILD_FRAMEWORK OPUS_BUILD_FRAMEWORK ${OPUS_BUILD_FRAMEWORK_HELP_STR}) endif() ``` -------------------------------- ### Configuring Custom Modes Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Defines a CMake option to enable custom audio modes, such as 44.1 kHz sample rate and frame sizes that are powers of two. This allows for more flexibility in audio processing scenarios. ```cmake set(OPUS_CUSTOM_MODES_HELP_STR "enable non-Opus modes, e.g. 44.1 kHz & 2^n frames.") option(OPUS_CUSTOM_MODES ${OPUS_CUSTOM_MODES_HELP_STR} OFF) add_feature_info(OPUS_CUSTOM_MODES OPUS_CUSTOM_MODES ${OPUS_CUSTOM_MODES_HELP_STR}) ``` -------------------------------- ### Floating Point Approximations Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables the use of floating-point approximations. It's important to ensure the platform supports IEEE 754 before enabling this option, as it may affect precision. ```cmake set(OPUS_FLOAT_APPROX_HELP_STR "enable floating point approximations (Ensure your platform supports IEEE 754 before enabling).") option(OPUS_FLOAT_APPROX ${OPUS_FLOAT_APPROX_HELP_STR} OFF) add_feature_info(OPUS_FLOAT_APPROX OPUS_FLOAT_APPROX ${OPUS_FLOAT_APPROX_HELP_STR}) ``` -------------------------------- ### Assembly Bit-Exactness Check Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables bit-exactness checks between the optimized assembly implementations and the standard C implementation. This is crucial for ensuring the correctness of assembly optimizations. ```cmake set(OPUS_CHECK_ASM_HELP_STR "enable bit-exactness checks between optimized and c implementations.") option(OPUS_CHECK_ASM ${OPUS_CHECK_ASM_HELP_STR} OFF) add_feature_info(OPUS_CHECK_ASM OPUS_CHECK_ASM ${OPUS_CHECK_ASM_HELP_STR}) ``` -------------------------------- ### Configure Opus Extensions Executable with CMake Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This snippet configures the build for the opus extensions executable. It specifies the source files, include directories, linked libraries (opus), and compile definitions (OPUS_BUILD). It also sets up a CMake test for this executable using the RunTest.cmake script. ```cmake add_executable(test_opus_extensions ${test_opus_extensions_sources}) target_include_directories(test_opus_extensions PRIVATE ${CMAKE_CURRENT_BINARY_DIR} celt dnn) target_link_libraries(test_opus_extensions PRIVATE opus) target_compile_definitions(test_opus_extensions PRIVATE OPUS_BUILD) add_test(NAME test_opus_extensions COMMAND ${CMAKE_COMMAND} -DTEST_EXECUTABLE=$ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} -P "${PROJECT_SOURCE_DIR}/cmake/RunTest.cmake") ``` -------------------------------- ### Configure and Run Opus Test Executables Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This CMake code configures and enables various test executables for the Opus library when testing is enabled and shared libraries are not being built. It defines executables such as 'test_opus_decode', 'test_opus_padding', 'test_opus_api', and 'test_opus_encode'. Each test is linked against the opus library, has specific include directories set, and may have conditional compile definitions based on build configurations like fixed-point support. Tests are registered using 'add_test' and executed via a CMake script. ```cmake if(BUILD_TESTING AND NOT BUILD_SHARED_LIBS) enable_testing() # tests add_executable(test_opus_decode ${test_opus_decode_sources}) target_include_directories(test_opus_decode PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(test_opus_decode PRIVATE opus) target_compile_definitions(test_opus_decode PRIVATE OPUS_BUILD) if(OPUS_FIXED_POINT) target_compile_definitions(test_opus_decode PRIVATE DISABLE_FLOAT_API) endif() add_test(NAME test_opus_decode COMMAND ${CMAKE_COMMAND} -DTEST_EXECUTABLE=$ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} -P "${PROJECT_SOURCE_DIR}/cmake/RunTest.cmake") add_executable(test_opus_padding ${test_opus_padding_sources}) target_include_directories(test_opus_padding PRIVATE ${CMAKE_CURRENT_BINARY_DIR}) target_link_libraries(test_opus_padding PRIVATE opus) add_test(NAME test_opus_padding COMMAND ${CMAKE_COMMAND} -DTEST_EXECUTABLE=$ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} -P "${PROJECT_SOURCE_DIR}/cmake/RunTest.cmake") add_executable(test_opus_api ${test_opus_api_sources}) target_include_directories(test_opus_api PRIVATE ${CMAKE_CURRENT_BINARY_DIR} celt) target_link_libraries(test_opus_api PRIVATE opus) target_compile_definitions(test_opus_api PRIVATE OPUS_BUILD) if(OPUS_FIXED_POINT) target_compile_definitions(test_opus_api PRIVATE DISABLE_FLOAT_API) endif() add_test(NAME test_opus_api COMMAND ${CMAKE_COMMAND} -DTEST_EXECUTABLE=$ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} -P "${PROJECT_SOURCE_DIR}/cmake/RunTest.cmake") add_executable(test_opus_encode ${test_opus_encode_sources}) target_include_directories(test_opus_encode PRIVATE ${CMAKE_CURRENT_BINARY_DIR} celt dnn) target_link_libraries(test_opus_encode PRIVATE opus) target_compile_definitions(test_opus_encode PRIVATE OPUS_BUILD) add_test(NAME test_opus_encode COMMAND ${CMAKE_COMMAND} -DTEST_EXECUTABLE=$ -DCMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME} -P "${PROJECT_SOURCE_DIR}/cmake/RunTest.cmake") endif() ``` -------------------------------- ### Encoding 16-bit PCM Audio Source: https://context7.com/voxkit/kopus/llms.txt Encode raw PCM audio samples (Short format) into compressed OPUS packets. ```APIDOC ## Encoding 16-bit PCM Audio ### Description Encode raw PCM audio samples (Short format) into compressed OPUS packets. ### Method `OpusEncoder.encode(pcmInput: ShortArray, frameSize: Int, outputBuffer: ByteArray): Int` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pcmInput** (ShortArray) - Required - An array of Short representing the PCM audio samples. The array should be interleaved if stereo. - **frameSize** (Int) - Required - The number of samples per channel in the input frame. - **outputBuffer** (ByteArray) - Required - A buffer to store the encoded OPUS data. ### Request Example ```kotlin import io.voxkit.kopus.* // Setup encoder val sampleRate = SampleRate.RATE_48K val channels = Channels.STEREO val encoder = Opus.encoder(sampleRate, channels, OpusApplication.AUDIO) // 20ms frame at 48kHz = 960 samples per channel val frameSize = 960 val pcmInput = ShortArray(frameSize * channels.ordinal) // Interleaved stereo // Generate sample audio data (440Hz sine wave) for (i in 0 until frameSize) { val sample = (Short.MAX_VALUE * 0.5 * Math.sin(2 * Math.PI * 440 * i / 48000.0)).toInt().toShort() for (channel in 0 until channels.ordinal) { pcmInput[i * channels.ordinal + channel] = sample } } // Encode to OPUS val encodedBuffer = ByteArray(OpusEncoder.DEFAULT_OUTPUT_BUFFER_SIZE) // 4000 bytes val encodedLength = encoder.encode(pcmInput, frameSize, encodedBuffer) println("Encoded $frameSize samples into $encodedLength bytes") // Output: Encoded 960 samples into ~80-120 bytes (typical compression ratio) encoder.close() ``` ### Response #### Success Response (200) - **encodedLength** (Int) - The number of bytes written to the output buffer containing the OPUS-encoded data. #### Response Example ``` Encoded 960 samples into 115 bytes ``` ``` -------------------------------- ### Configure SSP Library for MinGW in CMake Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This CMake snippet appends the 'ssp' library to `OPUS_REQUIRED_LIBRARIES` if the MINGW environment is detected and either `OPUS_FORTIFY_SOURCE` or `OPUS_STACK_PROTECTOR` is enabled. This is necessary for security features on MinGW. ```cmake if(MINGW AND (OPUS_FORTIFY_SOURCE OR OPUS_STACK_PROTECTOR)) # ssp lib is needed for security features for MINGW list(APPEND OPUS_REQUIRED_LIBRARIES ssp) endif() ``` -------------------------------- ### Configure Build Definitions for Opus Library - CMake Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This CMake code applies various compile definitions to the 'opus' library based on build configurations. It enables fixed-point debugging, FORTIFY_SOURCE (for security, excluding debug builds on non-MSVC), and FLOAT_APPROX. The `target_compile_definitions` command is used to add these flags. ```cmake if(OPUS_FIXED_POINT_DEBUG) target_compile_definitions(opus PRIVATE FIXED_DEBUG) endif() if(OPUS_FORTIFY_SOURCE AND NOT MSVC) target_compile_definitions(opus PRIVATE $<$>:_FORTIFY_SOURCE=2>) endif() if(OPUS_FLOAT_APPROX) target_compile_definitions(opus PRIVATE FLOAT_APPROX) endif() if(OPUS_ASSERTIONS) ``` -------------------------------- ### OPUS Decoder with Packet Loss Concealment (PLC) Source: https://github.com/voxkit/kopus/blob/main/README.md Illustrates how to use the Kopus decoder to handle packet loss. By passing 'null' for the 'data' parameter, the decoder can attempt to conceal the missing packet and generate synthetic audio samples, mitigating interruptions in playback. ```kotlin // Handle missing packets by passing null data val missingSamples = decoder.decode( data = null, // indicates packet loss frameSize = expectedFrameSize, pcm = outputBuffer ) ``` -------------------------------- ### Encoding Floating-point PCM Audio Source: https://context7.com/voxkit/kopus/llms.txt Encode floating-point PCM audio samples for higher precision audio processing. ```APIDOC ## Encoding Floating-point PCM Audio ### Description Encode floating-point PCM audio samples for higher precision audio processing. ### Method `OpusEncoder.encode(pcmInput: FloatArray, frameSize: Int, outputBuffer: ByteArray): Int` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pcmInput** (FloatArray) - Required - An array of Float representing the PCM audio samples, normalized between -1.0 and 1.0. The array should be interleaved if stereo. - **frameSize** (Int) - Required - The number of samples per channel in the input frame. - **outputBuffer** (ByteArray) - Required - A buffer to store the encoded OPUS data. ### Request Example ```kotlin import io.voxkit.kopus.* // Setup encoder val encoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO, application = OpusApplication.AUDIO ) // 20ms frame at 48kHz val frameSize = 960 val pcmInput = FloatArray(frameSize * Channels.STEREO.ordinal) // Interleaved stereo // Generate sample audio data (normalized to -1.0 to 1.0) for (i in 0 until frameSize) { val sample = (0.5f * Math.sin(2 * Math.PI * 440 * i / 48000.0)).toFloat() for (channel in 0 until Channels.STEREO.ordinal) { pcmInput[i * Channels.STEREO.ordinal + channel] = sample } } // Encode val encodedBuffer = ByteArray(OpusEncoder.DEFAULT_OUTPUT_BUFFER_SIZE) val encodedLength = encoder.encode(pcmInput, frameSize, encodedBuffer) println("Encoded $frameSize float samples into $encodedLength bytes") encoder.close() ``` ### Response #### Success Response (200) - **encodedLength** (Int) - The number of bytes written to the output buffer containing the OPUS-encoded data. #### Response Example ``` Encoded 960 float samples into 108 bytes ``` ``` -------------------------------- ### Run Opus Tests using CTest Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md These commands execute the test suite for the Opus project using CTest. It requires the project to be built first. The `ctest` command runs all tests, while `ctest -C Debug` is used on Windows to specify the Debug configuration. ```shell cd build ctest ``` ```shell ctest -C Debug ``` -------------------------------- ### Add Source Groups for Opus Components Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Organizes source files into logical groups for the 'opus' target, specifically for SILK, CELT, and LPCNet components. It conditionally adds fixed-point or float sources for SILK and includes headers and sources for LPCNet based on feature flags. ```cmake add_sources_group(opus silk ${silk_headers} ${silk_sources}) add_sources_group(opus celt ${celt_headers} ${celt_sources}) if(OPUS_FIXED_POINT) add_sources_group(opus silk ${silk_sources_fixed}) target_include_directories(opus PRIVATE silk/fixed) target_compile_definitions(opus PRIVATE FIXED_POINT=1) else() add_sources_group(opus silk ${silk_sources_float}) target_include_directories(opus PRIVATE silk/float) endif() if (OPUS_DEEP_PLC OR OPUS_DRED OR OPUS_OSCE) add_sources_group(opus lpcnet ${deep_plc_headers} ${deep_plc_sources}) endif() if (OPUS_DNN) add_sources_group(opus lpcnet ${deep_plc_headers} ${deep_plc_sources}) endif() if (OPUS_DRED) add_sources_group(opus lpcnet ${dred_headers} ${dred_sources}) endif() if (OPUS_OSCE) add_sources_group(opus lpcnet ${osce_headers} ${osce_sources}) endif() if(NOT OPUS_DISABLE_INTRINSICS) if(((OPUS_X86_MAY_HAVE_SSE AND NOT OPUS_X86_PRESUME_SSE) OR (OPUS_X86_MAY_HAVE_SSE2 AND NOT OPUS_X86_PRESUME_SSE2) OR (OPUS_X86_MAY_HAVE_SSE4_1 AND NOT OPUS_X86_PRESUME_SSE4_1) OR (OPUS_X86_MAY_HAVE_AVX2 AND NOT OPUS_X86_PRESUME_AVX2)) AND RUNTIME_CPU_CAPABILITY_DETECTION) add_sources_group(opus celt ${celt_sources_x86_rtcd}) add_sources_group(opus silk ${silk_sources_x86_rtcd}) if (OPUS_DNN) add_sources_group(opus lpcnet ${dnn_sources_x86_rtcd}) endif() endif() if(SSE1_SUPPORTED) if(OPUS_X86_MAY_HAVE_SSE) add_sources_group(opus celt ${celt_sources_sse}) endif() endif() if(SSE2_SUPPORTED) if(OPUS_X86_MAY_HAVE_SSE2) add_sources_group(opus celt ${celt_sources_sse2}) if (OPUS_DNN) add_sources_group(opus lpcnet ${dnn_sources_sse2}) endif() endif() endif() if(SSE4_1_SUPPORTED) if(OPUS_X86_MAY_HAVE_SSE4_1) add_sources_group(opus celt ${celt_sources_sse4_1}) add_sources_group(opus silk ${silk_sources_sse4_1}) if (OPUS_DNN) ``` -------------------------------- ### Hardening Runtime Checks Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables runtime checks that are designed to be safe and efficient for production environments. These checks can help detect and mitigate certain security vulnerabilities. ```cmake set(OPUS_HARDENING_HELP_STR "run-time checks that are cheap and safe for use in production.") option(OPUS_HARDENING ${OPUS_HARDENING_HELP_STR} ON) add_feature_info(OPUS_HARDENING OPUS_HARDENING ${OPUS_HARDENING_HELP_STR}) ``` -------------------------------- ### DNN Float Debug Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables running Deep Neural Network (DNN) computations using floating-point arithmetic specifically for debugging purposes. This can help in identifying issues in DNN logic. ```cmake set(OPUS_DNN_FLOAT_DEBUG_HELP_STR "Run DNN computations as float for debugging purposes.") option(OPUS_DNN_FLOAT_DEBUG ${OPUS_DNN_FLOAT_DEBUG_HELP_STR} OFF) add_feature_info(OPUS_DNN_FLOAT_DEBUG OPUS_DNN_FLOAT_DEBUG ${OPUS_DNN_FLOAT_DEBUG_HELP_STR}) ``` -------------------------------- ### Extract LPCNet Model for C Inference Source: https://github.com/voxkit/kopus/blob/main/opus/dnn/README.md Extracts LPCNet model files (nnet_data.h and nnet_data.c) from a trained h5 model. These files are intended for use with the C implementation of LPCNet for faster CPU inference. After extraction, they should be moved to the src/ directory and the software rebuilt. ```python ./training_tf2/dump_lpcnet.py lpcnet_model_name.h5 ``` -------------------------------- ### Cross-Compile Opus for Android with CMake Source: https://github.com/voxkit/kopus/blob/main/opus/cmake/README.md This CMake command demonstrates cross-compiling the Opus project for Android. It utilizes a toolchain file and specifies the target Android ABI. Ensure the ANDROID_HOME environment variable is set correctly and the specified NDK version exists. ```shell cmake .. -DCMAKE_TOOLCHAIN_FILE=${ANDROID_HOME}/ndk/25.2.9519653/build/cmake/android.toolchain.cmake -DANDROID_ABI=arm64-v8a ``` -------------------------------- ### Create OPUS Decoder - Kotlin Source: https://context7.com/voxkit/kopus/llms.txt Creates an OPUS decoder for decompressing OPUS-encoded audio back to PCM format. The decoder should be configured with the same sample rate and channel count as the encoder used for compression. Remember to close the decoder when finished. ```kotlin import io.voxkit.kopus.* // Create decoder matching encoder configuration val decoder = Opus.decoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO ) // Decoder for mono voice calls val voipDecoder = Opus.decoder( sampleRate = SampleRate.RATE_16K, channels = Channels.MONO ) // Always close when done decoder.close() voipDecoder.close() ``` -------------------------------- ### Configure Compile Options for Opus Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Sets compile options for the 'opus' target, specifically for fast math and stack protection. It includes platform-specific flags for MSVC and GCC/Clang, and handles different levels of stack protection. ```cmake if(OPUS_FAST_MATH) if(MSVC) target_compile_options(opus PRIVATE /fp:fast) else() target_compile_options(opus PRIVATE -ffast-math) endif() endif() if(OPUS_STACK_PROTECTOR) if(MSVC) target_compile_options(opus PRIVATE /GS) else() target_compile_options(opus PRIVATE -fstack-protector-strong) endif() elseif(STACK_PROTECTOR_DISABLED_SUPPORTED) target_compile_options(opus PRIVATE /GS-) endif() ``` -------------------------------- ### MSVC Static Runtime Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Conditionally defines an option to build the project with a static runtime library when using the Microsoft Visual C++ compiler (MSVC). This affects how the program links against the C runtime. ```cmake if(MSVC) set(OPUS_STATIC_RUNTIME_HELP_STR "build with static runtime library.") ``` -------------------------------- ### Configuring Testing Build Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Defines a CMake option to enable or disable the building of tests. If enabled, it also sets the global `BUILD_TESTING` variable. This option is useful for development and verification. ```cmake set(OPUS_BUILD_TESTING_HELP_STR "build tests.") option(OPUS_BUILD_TESTING ${OPUS_BUILD_TESTING_HELP_STR} OFF) if(OPUS_BUILD_TESTING OR BUILD_TESTING) set(OPUS_BUILD_TESTING ON) set(BUILD_TESTING ON) endif() add_feature_info(OPUS_BUILD_TESTING OPUS_BUILD_TESTING ${OPUS_BUILD_TESTING_HELP_STR}) ``` -------------------------------- ### Configure Fast Math in CMake Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt This CMake code enables the 'fast math' option, which uses less precise but potentially faster floating-point operations. It's marked as unsupported and discouraged due to lack of thorough testing. The option `OPUS_FAST_MATH` is configured using `cmake_dependent_option`. ```cmake set(OPUS_FAST_MATH_HELP_STR "enable fast math (unsupported and discouraged use, as code is not well tested with this build option).") cmake_dependent_option(OPUS_FAST_MATH ${OPUS_FAST_MATH_HELP_STR} ON "OPUS_FLOAT_APPROX; OPUS_FAST_MATH; FAST_MATH_SUPPORTED" OFF) add_feature_info(OPUS_FAST_MATH OPUS_FAST_MATH ${OPUS_FAST_MATH_HELP_STR}) ``` -------------------------------- ### Assertions Enable Option Source: https://github.com/voxkit/kopus/blob/main/opus/CMakeLists.txt Enables additional software error checking through assertions. This is useful during development to catch potential bugs and ensure code integrity. ```cmake set(OPUS_ASSERTIONS_HELP_STR "additional software error checking.") option(OPUS_ASSERTIONS ${OPUS_ASSERTIONS_HELP_STR} OFF) add_feature_info(OPUS_ASSERTIONS OPUS_ASSERTIONS ${OPUS_ASSERTIONS_HELP_STR}) ``` -------------------------------- ### Create OPUS Encoder - Kotlin Source: https://context7.com/voxkit/kopus/llms.txt Creates an OPUS encoder for compressing PCM audio to OPUS format. Supports configuration of sample rate, channel count, and application mode (AUDIO, VOIP, LOW_DELAY). Ensure the encoder is closed when no longer needed. ```kotlin import io.voxkit.kopus.* // Create stereo encoder for high-quality music at 48kHz val encoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.STEREO, application = OpusApplication.AUDIO ) // For voice calls, use VOIP mode with lower sample rate val voipEncoder = Opus.encoder( sampleRate = SampleRate.RATE_16K, channels = Channels.MONO, application = OpusApplication.VOIP ) // For low-latency real-time applications val lowLatencyEncoder = Opus.encoder( sampleRate = SampleRate.RATE_48K, channels = Channels.MONO, application = OpusApplication.LOW_DELAY ) // Always close when done encoder.close() voipEncoder.close() lowLatencyEncoder.close() ``` -------------------------------- ### Forward Error Correction (FEC) with Kotlin Source: https://context7.com/voxkit/kopus/llms.txt Demonstrates how to use Forward Error Correction (FEC) to recover from corrupted packets. This is achieved by enabling the `decodeFec` flag during the decoding process, allowing the decoder to utilize redundant data from subsequent packets. Ensure that the subsequent packet contains the necessary FEC data for recovery. ```kotlin import io.voxkit.kopus.* val decoder = Opus.decoder(SampleRate.RATE_48K, Channels.MONO) val frameSize = 960 val outputBuffer = ShortArray(frameSize) // Packet 1 corrupted - use FEC from packet 2 val packet1Corrupted = true if (packet1Corrupted) { // Decode with FEC enabled to recover packet 1 from packet 2 val packet2 = ByteArray(100) // Contains FEC data for packet 1 val recoveredSamples = decoder.decode( data = packet2, frameSize = frameSize, pcm = outputBuffer, decodeFec = true // Enable FEC recovery ) println("Recovered $recoveredSamples samples using FEC") } // Continue with normal decoding val packet3 = ByteArray(100) decoder.decode(packet3, frameSize, outputBuffer, decodeFec = false) decoder.close() ```