Making a performant audio seize system⚡🚀💨

Making a performant audio seize system⚡🚀💨

Ever needed to construct a performant audio capturing system, however do not know the place to start out? It undoubtedly occurred to me.

Due to lack of recent C++ implementations on this, I made a decision to share what I’ve realized when making it and provide you with a beginning group off of what I’ve managed to construct!

DISCLAIMER: Knowledge about OOP, fundamental C++ ideas or total normal programming data and GRPC is suggested!

The motivation

The motivation is for a manner bigger undertaking I’m engaged on. The supply code for the entire code goes to be linked under on the finish of the publish! 😊

The CMake configuration

Every fashionable C/C++ software requires some kind of configuration, that is the place I selected CMake since It’s excellent for cross platform compilation!


# Define the minimal required model
# and the undertaking model
cmake_minimum_required(VERSION 3.16)
undertaking(audio_capture VERSION 1.0)

# Set C requirements
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

#Include extra widespread cmake code for working with GRPC

embrace(./cmake/widespread.cmake)

#Include FetchContent for fetching code and recordsdata remotely.

embrace(FetchContent)

# Find all .proto recordsdata within the protos listing
file(GLOB_RECURSE PROTO_FILES "${CMAKE_SOURCE_DIR}/protos/*.proto")

# Create lists to retailer generated recordsdata
set(PROTO_SRCS)
set(PROTO_HDRS)
set(GRPC_SRCS)
set(GRPC_HDRS)

# Generate protocol buffer and gRPC code for every .proto file
foreach(proto_file ${PROTO_FILES})
    get_filename_component(proto_path "${proto_file}" PATH)
    get_filename_component(proto_name "${proto_file}" NAME_WE)

    listing(APPEND PROTO_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.pb.cc")
    listing(APPEND PROTO_HDRS "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.pb.h")
    listing(APPEND GRPC_SRCS "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.grpc.pb.cc")
    listing(APPEND GRPC_HDRS "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.grpc.pb.h")

    add_custom_command(
        OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.pb.cc"
            "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.pb.h"
            "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.grpc.pb.cc"
            "${CMAKE_CURRENT_BINARY_DIR}/${proto_name}.grpc.pb.h"
        COMMAND ${_PROTOBUF_PROTOC}
        ARGS --grpc_out=generate_mock_code=false:"${CMAKE_CURRENT_BINARY_DIR}"  # Disable server stub
            --cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
            -I "${proto_path}"
            --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
            "${proto_file}"
        DEPENDS "${proto_file}")
endforeach()

# Create protocol buffer library
add_library(audio_proto
    ${GRPC_SRCS}
    ${GRPC_HDRS}
    ${PROTO_SRCS}
    ${PROTO_HDRS})

target_link_libraries(audio_proto
    absl::examine
    ${_REFLECTION}
    ${_GRPC_GRPCPP}
    ${_PROTOBUF_LIBPROTOBUF})

# Configure PortAudio
FetchContent_Declare(
    portaudio
    GIT_REPOSITORY https://github.com/PortAudio/portaudio.git
    GIT_TAG v19.7.0
)

# Configure PortAudio construct choices
set(PA_BUILD_SHARED OFF CACHE BOOL "")
set(PA_BUILD_TESTS OFF CACHE BOOL "")
set(PA_BUILD_EXAMPLES OFF CACHE BOOL "")

# Make PortAudio obtainable
FetchContent_MakeAvailable(portaudio)

# Configure spdlog
FetchContent_Declare(
    spdlog
    GIT_REPOSITORY https://github.com/gabime/spdlog.git
    GIT_TAG v1.15.1
)
FetchContent_MakeAvailable(spdlog)

# Find FFTW3
find_package(PkgConfig REQUIRED)
pkg_check_modules(FFTW3 REQUIRED fftw3)

# Include directories
include_directories(
    ${CMAKE_CURRENT_BINARY_DIR}
    ${CMAKE_SOURCE_DIR}/contains
    ${FFTW3_INCLUDE_DIRS}
    ${portaudio_SOURCE_DIR}/supply
)

# Create most important executable
file(GLOB_RECURSE SRC_FILES src/*.cc)
add_executable(audio_capture ${SRC_FILES})

# Link dependencies
target_link_libraries(audio_capture PRIVATE
    audio_proto
    portaudio_static
    spdlog::spdlog
    ${FFTW3_LIBRARIES}
    absl::examine
    absl::flags
    absl::flags_parse
    absl::log
    ${_REFLECTION}
    ${_GRPC_GRPCPP}
    ${_PROTOBUF_LIBPROTOBUF}
)

# Platform-specific configuration
if(WIN32)
    target_link_libraries(audio_capture PRIVATE winmm)
elseif(UNIX AND NOT APPLE)
    find_package(Threads REQUIRED)
    target_link_libraries(audio_capture PRIVATE
        pthread
        fftw3
    )
endif()

# Add FFTW3 library directories
link_directories(${FFTW3_LIBRARY_DIRS})

The undertaking structure

The complete undertaking structure is kind of easy, maintainable and made to scale.

|-- CMakeLists.txt
|-- Makefile
|-- cmake
|   `-- widespread.cmake
|-- contains
|   |-- audio_capture.h
|   `-- logger.h
|-- protos
|   `-- device_stream.proto
`-- src
    |-- audio_capture.cc
    |-- logger.cc
    `-- most important.cc

The logger

I’ve used the spdlog for stunning logging messages that include it!

Here is the .h definition (the entire supply code is on github)


#pragma as soon as

#embrace <cstddef>
#embrace <reminiscence>
#embrace <spdlog/sinks/basic_file_sink.h>
#embrace <spdlog/spdlog.h>
#embrace <string>

class Logger {
public:
  static void init();
  static std::shared_ptr<Logger> get();

  static constexpr size_t queue_items_max = 8192;
  static constexpr size_t backing_thread_count = 1;
  static constexpr size_t max_file_size = 10 * 1024 * 1024;
  static constexpr size_t max_files = 5;
  static constexpr std::string logs_path = "logs/app.log";

  static void data(const std::string &message) {
    logger_->data(message);
  }

  static void warn(const std::string &message) {
    logger_->warn(message);
  }

  static void error(const std::string &message) {
    logger_->error(message);
  }

non-public:
  static std::shared_ptr<spdlog::logger> logger_;
};

The logger implementation:

#embrace "logger.h"
#embrace "spdlog/async.h"
#embrace "spdlog/widespread.h"
#embrace "spdlog/sinks/rotating_file_sink.h"
#embrace "spdlog/sinks/stdout_color_sinks.h"
#embrace "spdlog/spdlog.h"
#embrace <iostream>
#embrace <reminiscence>

// Initialize logger as nullptr
std::shared_ptr<spdlog::logger> Logger::logger_ = nullptr;

void Logger::init() {
  attempt {
    spdlog::init_thread_pool(queue_items_max, backing_thread_count);

    auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
    auto file_rotating_sink =
        std::make_shared<spdlog::sinks::rotating_file_sink_mt>(
            logs_path, max_file_size, max_files);

    console_sink->set_level(spdlog::degree::data);
    file_rotating_sink->set_level(spdlog::degree::debug);

    logger_ = std::make_shared<spdlog::async_logger>(
        "main_logger",
        spdlog::sinks_init_list{console_sink, file_rotating_sink},
        spdlog::thread_pool(), spdlog::async_overflow_policy::block);

    spdlog::set_default_logger(logger_);
    spdlog::set_pattern("[%Y-%m-%d %H:%M:%S] [%^%l%$] [thread %t] %v");

#ifdef NDEBUG
    spdlog::set_level(spdlog::degree::data);
#else
    spdlog::set_level(spdlog::degree::debug);
#endif

    spdlog::data("Logger initialized efficiently!");
  } catch (const spdlog::spdlog_ex &ex) {
    std::cerr << "Log initialization failed: " << ex.what() << std::endl;
    exit(EXIT_FAILURE);
  }
}

std::shared_ptr<Logger> Logger::get() {
  static std::shared_ptr<Logger> occasion = std::make_shared<Logger>();
  return occasion;
}

The protobuf GRPC messages & RPCs

The present implementation of that is quite simple and straight ahead. Both the server and the consumer share the identical GRPC file and construction to speak with streams.

syntax = "proto3";

bundle audio_stream;

service AudioStream {
    rpc StreamAudio(stream AudioChunk) returns (StreamResponse);
}

message AudioChunk {
    bytes audio_data = 1;
    repeated double spectral_data = 2;  
    double vitality = 3;
    double zero_crossings = 4;
    double speech_band_energy = 5;
    bool voice_detected = 6; 
    int64 timestamp = 7;
}

message StreamResponse {
    bool success = 1;
    string response = 2;
}

The audio seize system

The audio seize system is carried out utilizing portaudio.h which is a library used for cross platform audio growth!

Here is my implementation of the .h file (header):

#pragma as soon as

#embrace "portaudio.h"
#embrace <atomic>
#embrace <condition_variable>
#embrace <cstddef>
#embrace <reminiscence>
#embrace <mutex>
#embrace <queue>
#embrace <unordered_map>
#embrace <vector>
#embrace "device_stream.grpc.pb.h" // gRPC generated header

// Forward declaration of Logger
class Logger;

// AudioSeize class for dealing with audio streaming
class AudioSeize {
public:
  AudioSeize();
  ~AudioSeize();

  static constexpr size_t sample_rate = 44100;           // Audio pattern charge
  static constexpr size_t frames_per_buffer = 512;        // Frames per buffer
  static constexpr int numInputChannels = 1;              // Number of enter channels (mono)
  static constexpr int numOutputChannels = 0;             // Number of output channels (no output)

  // Starts the audio stream
  bool begin();
  // Stops the audio stream
  void cease();
  // Checks if the stream is operating
  bool isRunning() const;

  // Retrieves obtainable audio units
  std::unordered_map<size_t, std::shared_ptr<const PaDeviceInfo>> getDevices();

  // Opens the audio stream with the desired machine index
  void openAudioStream(int deviceIndex);

  // Gets the overall variety of audio units
  int getDeviceRely() const;

  // Creates stream parameters for a given machine and variety of channels
  std::unique_ptr<PaStreamParameters> createStreamParameters(int machine, int numChannels);

  // Sends the audio stream to the gRPC server
  void shipAudioStream(std::shared_ptr<audio_stream::AudioStream::Stub> stub);

  // Closes the audio stream
  void shutAudioStream();

  // Retrieves the following audio chunk from the queue
  std::vector<float> getNextAudioChunk();

non-public:
  // Audio callback perform for PortAudio
  static int audioCallback(const void *enter, void *, size_t, 
                           const PaStreamCallbackTimeInfo *, 
                           PaStreamCallbackFlags, void *userData);

  // Queue to carry audio chunks
  std::queue<std::vector<float>> audioQueue;
  // Mutex and situation variable for thread synchronization
  std::mutex queueMutex;
  std::condition_variable queueCondition;
  // Atomic flag to handle the operating state of the seize
  std::atomic<bool> running_;

  // Stream parameters for enter and output
  std::unique_ptr<PaStreamParameters> inputParameters;
  std::unique_ptr<PaStreamParameters> outputParameters;

  // Logger for logging occasions
  std::shared_ptr<Logger> logger_;
  // Pointer to the PortAudio stream
  PaStream *stream_;
};

The implementation of audio seize:

// AudioSeize.cpp
#embrace "audio_capture.h"
#embrace "device_stream.pb.h"
#embrace "logger.h"
#embrace "portaudio.h"
#embrace <algorithm>
#embrace <cstddef>
#embrace <grpcpp/client_context.h>
#embrace <grpcpp/assist/sync_stream.h>
#embrace <mutex>
#embrace <non-obligatory>
#embrace <string>
#embrace <utility>
#embrace <vector>

static void deal withAudioError(PaError err, std::shared_ptr<Logger> logger) {
  if (err != paNoError) {
    logger->error("PortAudio error: " + std::string(Pa_GetErrorText(err)));
  }
}

AudioSeize::AudioSeize()
    : stream_(nullptr), running_(false), logger_(std::make_shared<Logger>()) {
  PaError err = Pa_Initialize();
  deal withAudioError(err, logger_);
}

AudioSeize::~AudioSeize() {
  PaError err = Pa_Terminate();
  deal withAudioError(err, logger_);
}

bool AudioSeize::begin() {
  if (running_)
    return false;

  deal withAudioError(Pa_OpenDefaultStream(
                       &stream_, numInputChannels, numOutputChannels, paFloat32,
                       sample_rate, frames_per_buffer, audioCallback, this),
                   logger_);

  PaError err = Pa_StartStream(stream_);
  if (err != paNoError) {
    logger_->error("Failed to start out audio stream: " +
                   std::string(Pa_GetErrorText(err)));
    return false;
  }

  running_ = true;

  return true;
}

void AudioSeize::cease() {
  if (!running_) {
    return;
  }

  deal withAudioError(Pa_StopStream(stream_), logger_);
  Pa_CloseStream(stream_);
  running_ = false;
}

bool AudioSeize::isRunning() const { return running_; }

int AudioSeize::getDeviceRely() const {
  PaDeviceIndex deviceCount = Pa_GetDeviceRely();
  return static_cast<int>(deviceCount);
}

std::vector<float> AudioSeize::getNextAudioChunk() {
  std::unique_lock<std::mutex> lock(queueMutex);
  queueCondition.wait(lock,
                      [this]  !running_; );

  if (!audioQueue.empty()) {
    std::vector<float> chunk = std::transfer(audioQueue.entrance());
    audioQueue.pop();
    return chunk;
  }

  return std::vector<float>();
}

void AudioSeize::shutAudioStream() {
  if (Pa_IsStreamEnergetic(stream_) == 1) {
    Pa_StopStream(stream_);
  }

  Pa_CloseStream(stream_);

  stream_ = nullptr;
}

void AudioSeize::openAudioStream(int deviceIndex) {
  if (stream_) {
    if (Pa_IsStreamEnergetic(stream_) == 1) {
      deal withAudioError(Pa_StopStream(stream_), logger_);
    }

    Pa_CloseStream(stream_);
    stream_ = nullptr;
  }

  // Reset parameters

  inputParameters.reset();
  outputParameters.reset();

  if (deviceIndex < 0 || deviceIndex >= getDeviceRely()) {
    logger_->error("Invalid machine index");
  }

  const PaDeviceInfo *machineInfo = Pa_GetDeviceInfo(deviceIndex);

  if (!deviceIndex) {
    logger_->error("Failed to get machine data");
    return;
  }

  logger_->data("Device Info: ");
  logger_->data("Name: " + std::string(machineInfo->identify));
  logger_->data("Max Input Channels: " +
                std::to_string(machineInfo->maxInputChannels));
  logger_->data("Max Output Channels: " +
                std::to_string(machineInfo->maxOutputChannels));
  logger_->data("Default Sample Rate: " +
                std::to_string(machineInfo->defaultSampleRate));

  std::non-obligatory<PaStreamParameters> inputParams;
  std::non-obligatory<PaStreamParameters> outputParams;

  if (machineInfo->maxInputChannels > 0) {
    inputParameters =
        createStreamParameters(deviceIndex, machineInfo->maxInputChannels);
    inputParams = *inputParameters;
  }

  if (machineInfo->maxOutputChannels > 0) {
    outputParameters =
        createStreamParameters(deviceIndex, machineInfo->maxOutputChannels);
    outputParams = *outputParameters;
  }

  double machineSampleRate = machineInfo->defaultSampleRate;

  deal withAudioError(
      Pa_OpenStream(&stream_, inputParams ? &*inputParams : nullptr,
                    outputParams ? &*outputParams : nullptr, machineSampleRate,
                    frames_per_buffer, paClipOff, audioCallback, this),
      logger_);

  std::string machineName = std::string(machineInfo->identify);
  logger_->data("Stream efficiently opened for machine" + machineName);

  Pa_StartStream(stream_);
}

std::unique_ptr<PaStreamParameters>
AudioSeize::createStreamParameters(int machine, int numChannels) {
  auto parameters = std::make_unique<PaStreamParameters>();
  const PaDeviceInfo *machineInfo = Pa_GetDeviceInfo(machine);

  if (!machineInfo) {
    logger_->error("Failed to get machine data for machine: " +
                   std::to_string(machine));
    return nullptr;
  }

  int channels = std::min(numChannels, machineInfo->maxInputChannels);

  parameters->machine = machine;
  parameters->channelCount = channels;
  parameters->patternFormat = paFloat32;
  parameters->suggestedLatency = machineInfo->defaultHighInputLatency;
  parameters->hostApiSpecificStreamInfo = nullptr;

  return parameters;
}

std::unordered_map<size_t, std::shared_ptr<const PaDeviceInfo>>
AudioSeize::getDevices() {
  std::unordered_map<size_t, std::shared_ptr<const PaDeviceInfo>> units;
  PaDeviceIndex deviceCount = Pa_GetDeviceRely();

  if (deviceCount < 0) {
    logger_->error("Failed to retrieve PortAudio machine rely: " +
                   std::to_string(deviceCount));
    return units;
  }

  for (size_t i = 0; i < static_cast<size_t>(deviceCount); i++) {
    const PaDeviceInfo *machineInfo = Pa_GetDeviceInfo(i);
    if (machineInfo) {
      units.emplace(i, std::make_shared<const PaDeviceInfo>(*machineInfo));
    } else {
      logger_->warn("Warning: Failed to get machine data for machine " +
                    std::to_string(i));
    }
  }

  return units;
}

int AudioSeize::audioCallback(const void *enter, void *, size_t,
                                const PaStreamCallbackTimeInfo *,
                                PaStreamCallbackFlags, void *userData) {
  if (!enter) {
    return paContinue;
  }

  auto *self = static_cast<AudioSeize *>(userData);
  std::vector<float> buffer(static_cast<const float *>(enter),
                            static_cast<const float *>(enter) +
                                frames_per_buffer);

  {
    std::lock_guard<std::mutex> lock(self->queueMutex);
    self->audioQueue.push(buffer);
  }

  self->queueCondition.notify_one();
  return paContinue;
}

void AudioSeize::shipAudioStream(
    std::shared_ptr<audio_stream::AudioStream::Stub> stub) {
  grpc::ClientContext context;
  audio_stream::StreamResponse response; // Define the response right here

  // Pass the response pointer because the second argument to StreamAudio
  std::unique_ptr<grpc::ConsumerWriter<audio_stream::AudioChunk>> author(
      stub->StreamAudio(&context, &response));

  if (!author) {
    logger_->error("Failed to create gRPC author.");
    return;
  }

  // Sending audio chunks in a stream
  whereas (isRunning()) {
    std::vector<float> chunk = getNextAudioChunk();
    if (!chunk.empty()) {
      audio_stream::AudioChunk audioChunk;

      // Convert float vector to byte array (audio knowledge)
      std::string audioData(reinterpret_cast<const char *>(chunk.knowledge()),
                            chunk.measurement() * sizeof(float));
      audioChunk.set_audio_data(audioData);

      // Fill in different fields like spectral knowledge, vitality, and so forth.
      audioChunk.add_spectral_data(0.0);  // Example spectral knowledge
      audioChunk.set_energy(0.0);         // Example vitality
      audioChunk.set_zero_crossings(0.0); // Example zero crossings
      audioChunk.set_speech_band_energy(0.0); // Example speech band vitality
      audioChunk.set_voice_detected(false); // Example voice detection
      audioChunk.set_timestamp(0);          // Example timestamp

      if (!author->Write(audioChunk)) {
        logger_->error("Failed to ship audio chunk.");
        break;
      }
    }

    // Optional: sleep to keep away from overloading the server
    std::this_thread::sleep_for(std::chrono::milliseconds(10));  // Adjust as crucial
  }

  author->WritesDone();

  // Now calling Finish with response object handed as the primary argument
  grpc::Status standing = author->Finish();

  if (!standing.okay()) {
    logger_->error("gRPC failed: " + standing.error_message());
  } else {
    // Optionally deal with the StreamResponse from the server
    logger_->data("Audio stream efficiently despatched and obtained response.");
    // If you need to log response particulars, you need to use `response` right here.
  }
}

The most important

The most important executable then connects to a GRPC server (which iss written in Golang) which is out of the scope of this weblog publish, so I’ll embrace the supply code for it within the github repository.

#embrace "audio_capture.h"
#embrace "device_stream.grpc.pb.h"
#embrace "logger.h"
#embrace <cstdlib>
#embrace <grpcpp/grpcpp.h>

int most important() {
  Logger::init();

  auto logger = Logger::get();
  AudioSeize audioCapture;  // Only one occasion is required

  auto units = audioCapture.getDevices();

  if (units.empty()) {
    logger->error("No audio units discovered.");
    return EXIT_FAILURE;
  }

  logger->data("Available Audio Devices");

  for (const auto &[index, deviceInfo] : units) {
    std::string machineName =
        "Device " + std::to_string(index) + ": " + machineInfo->identify + "n";

    logger->data(machineName);
    logger->warn("Opening audio stream on machine " + std::to_string(index));
    audioCapture.openAudioStream(index);
  }

  // Create a gRPC channel to the server
  std::shared_ptr<grpc::Channel> channel = grpc::CreateChannel(
      "localhost:50051", grpc::InsecureChannelCredentials());

  // Create the gRPC consumer stub
  std::shared_ptr<audio_stream::AudioStream::Stub> stub =
      audio_stream::AudioStream::NewStub(channel);

  // Start capturing audio
  audioCapture.begin();

  // Send audio stream to the exterior gRPC server
  audioCapture.shipAudioStream(stub);

  return 0;
}

Running and constructing the code

For operating and constructing the code I exploit a easy Makefile with a number of instructions:

# Compiler optimizations
CMAKE_FLAGS=-G Ninja -DCMAKE_BUILD_TYPE=Release
BUILD_DIR=construct
NUM_CORES=$(shell nproc)

.PHONY: construct run run_detailed rerun take away rebuild

construct:
    @mkdir -p $(BUILD_DIR)
    @cd $(BUILD_DIR) && cmake $(CMAKE_FLAGS) .. && cmake --build . -j$(NUM_CORES)

run:
    @cd $(BUILD_DIR) && ./audio_capture 2>/dev/null

run_detailed:
    @cd $(BUILD_DIR) && ./audio_capture

rerun: rebuild run

take away:
    @rm -rf $(BUILD_DIR)

rebuild:
    @cd $(BUILD_DIR) && cmake --build . --clean-first -j$(NUM_CORES) || { rm -rf $(BUILD_DIR) && make construct; }

Running the code needs to be as simple as make $COMMAND

Thank you for studying this far ⭐

I need to thanks, the reader, for studying this far! If you’ve got made it this far, right here is the hyperlink to the repository of the entire supply code 😊!

https://github.com/LegationPro/audio_capture_system

HI-FI News

through DEV Community https://dev.to

February 19, 2025 at 07:59PM