do noise_cancellation.BVC() works for self hosted ...
# ask-ai
b
do noise_cancellation.BVC() works for self hosted livekit?
t
Thanks for reaching out, Siddharth. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Regarding your question about
noise_cancellation.BVC()
and self-hosted LiveKit:
noise_cancellation.BVC()
is not available for self-hosted deployments. It’s part of LiveKit Cloud’s enhanced noise-cancellation (licensed Krisp models) and must be removed from agent code when self-hosting. If you'd like, I can suggest alternative noise-suppression approaches you can run in a self-hosted setup—what environment/language is your agent running in? Sources: Voice AI quickstart | LiveKit docs
b
So we are using livekit for telephony calls(via sip), currently we are using azure realtime model for our agent, so can u suggest what we can do to handle the noise
t
You're using self-hosted LiveKit with SIP and Azure Realtime — you cannot use
noise_cancellation.BVC()
in self-hosted. Here are practical alternatives you can apply now: 1) Enable Azure Realtime noise reduction • Use Azure’s
input_audio_noise_reduction
(e.g.,
"non_linear"
) when creating the Realtime model to reduce noise before transcription/processing. 2) Apply client-side WebRTC noise/echo suppression • Enable
noiseSuppression
and
echoCancellation
in browser/mobile capture so audio is cleaner before publishing. 3) Add server-side preprocessing in your agent pipeline (recommended for SIP) • Intercept raw audio frames in your agent, run a DSP/noise-suppression library, then forward cleaned frames to Azure. • Lightweight options: RNNoise (real-time, CPU-friendly). For higher quality with GPU, consider NVIDIA solutions. • Use different filters for SIP (narrowband) vs. general participants — detect
participant.kind == SIP
and apply telephony-tuned filtering. 4) Use SIP/provider-side features • Check your SIP trunk provider (Twilio, Telnyx, etc.) for echo suppression or noise reduction and enable those features. 5) Monitor and iterate • Record samples and use session metrics to evaluate which combination (Azure reduction + client-side + RNNoise) gives the best tradeoff between quality and latency. If you want, I can: • Provide a short code example showing where to run RNNoise on LiveKit audio frames for your agent language (which language/runtime is your agent written in?). • Show the exact Azure Realtime parameter snippet for
input_audio_noise_reduction
. Sources: Enhanced noise cancellation | LiveKit docs | Noise & echo cancellation | LiveKit docs | Pipeline nodes and hooks | LiveKit docs | Azure OpenAI Realtime API and LiveKit | LiveKit docs | sip | livekit/livekit_composite | DeepWiki
b
Yes please can u tell the RNNoise approach , how and where to use
t
You're asking how to integrate RNNoise into your self-hosted LiveKit agent pipeline. Below is a concise, practical guide with a Python example showing where to intercept audio frames, apply RNNoise, and forward cleaned audio to Azure Realtime or your STT/agent pipeline. What you'll do 1. Capture raw audio frames from LiveKit (agent side) before sending to Azure or STT. 2. Convert frames to the format RNNoise expects (16-bit PCM, single-channel, 48 kHz or 16 kHz depending on build). 3. Run RNNoise processing per-frame (20–30 ms frames). 4. Repackage processed frames into LiveKit AudioFrames and forward them. Prerequisites • Your agent runs Python and uses LiveKit server-side SDK or a custom ingest path that gives access to raw audio frames. • Install an RNNoise binding for Python (example: rnnoise-python) or use a small C wrapper. • Ensure sample rate alignment: RNNoise common builds expect 48 kHz or 16 kHz (telephony uses 8 kHz — resample to 16 kHz). High-level flow 1. Pull audio frames from LiveKit’s audio stream (or receive RTP payloads for SIP). 2. If audio is stereo, downmix to mono. 3. Resample to RNNoise sample rate (16k preferred for telephony). 4. Break into RNNoise frame size (480 samples @16 kHz = 30 ms, or 320 samples = 20 ms). 5. For each frame: run RNNoise → collect processed PCM. 6. Reassemble processed PCM, resample back to agent pipeline sample rate if needed, and forward to Azure Realtime or STT. Example Python sketch • This example uses a hypothetical
livekit
Python interface that yields
AudioFrame
objects, and
rnnoise
library with
RNNoise
processor. Adapt to your SDK.
Copy code
import numpy as np
import asyncio
import rnnoise  # example binding; install or wrap C library
from your_livekit_agent_sdk import AudioFrame, get_audio_stream, send_audio_frame
import resampy  # or librosa, torchaudio

RNNOISE_SR = 16000
FRAME_MS = 30
FRAME_SAMPLES = int(RNNOISE_SR * FRAME_MS / 1000)  # 480 samples for 30ms

def pcm_bytes_to_int16_array(pcm_bytes):
    return np.frombuffer(pcm_bytes, dtype=np.int16)

def int16_array_to_pcm_bytes(arr):
    return arr.astype(np.int16).tobytes()

async def process_stream():
    rn = rnnoise.RNNoise()  # construct RNNoise processor
    async for in_frame in get_audio_stream():  # yields AudioFrame with .data, .sample_rate, .channels
        # 1) Downmix to mono if needed
        data = pcm_bytes_to_int16_array(in_frame.data)
        if in_frame.channels == 2:
            data = data.reshape(-1, 2).mean(axis=1).astype(np.int16)

        # 2) Resample to RNNoise SR if needed
        if in_frame.sample_rate != RNNOISE_SR:
            data = resampy.resample(data.astype(np.float32), in_frame.sample_rate, RNNOISE_SR)
            data = np.clip(data, -32768, 32767).astype(np.int16)

        # 3) Frame and process
        processed = []
        offset = 0
        total_samples = data.shape[0]
        while offset + FRAME_SAMPLES <= total_samples:
            frame_samples = data[offset:offset + FRAME_SAMPLES]
            out = rn.process(frame_samples)  # returns int16 array of FRAME_SAMPLES
            processed.append(out)
            offset += FRAME_SAMPLES

        # Handle tail (zero-pad)
        if offset < total_samples:
            tail = np.zeros(FRAME_SAMPLES, dtype=np.int16)
            remaining = total_samples - offset
            tail[:remaining] = data[offset:offset + remaining]
            out = rn.process(tail)
            processed.append(out)

        processed_pcm = np.concatenate(processed)

        # 4) Resample back if original sample rate differs
        if in_frame.sample_rate != RNNOISE_SR:
            processed_pcm = resampy.resample(processed_pcm.astype(np.float32), RNNOISE_SR, in_frame.sample_rate)
            processed_pcm = np.clip(processed_pcm, -32768, 32767).astype(np.int16)

        # 5) Send cleaned audio frame onward
        out_bytes = int16_array_to_pcm_bytes(processed_pcm)
        out_frame = AudioFrame(
            data=out_bytes,
            sample_rate=in_frame.sample_rate,
            num_channels=1,
            samples_per_channel=len(processed_pcm)
        )
        await send_audio_frame(out_frame)

# Run the processor
asyncio.run(process_stream())
Key implementation notes • Telephony (SIP) is usually 8 kHz: resample 8 kHz → 16 kHz, run RNNoise, then resample back to 8 kHz. RNNoise works significantly better at 16 kHz than at 8 kHz. • Use frame sizes RNNoise expects (20–30 ms). Keep strict framing to avoid artifacts. • Minimize added latency: keep processing in streaming fashion, use a small processing buffer, and avoid batch resampling that adds delay. • If using a compiled RNNoise C library, consider a thin C extension for performance rather than a pure-Python binding. • Test CPU usage; RNNoise is lightweight but still consumes CPU per concurrent call. Scale horizontally or use worker pools for many concurrent SIP calls. Where in LiveKit agent to hook this • If you have an agent that gets raw audio from participants (e.g., via LiveKit’s audio pull or plugin hooks), intercept there before you hand audio to Azure Realtime or your STT. • If integrating at SIP ingress, hook into the RTP to PCM conversion stage (before any encoding/transcoding to the model). • If using LiveKit recordings or transforms pipeline, add a preprocessing transform step that replaces the audio track with the cleaned audio. Would you like: • A focused SIP-specific example handling 8 kHz RTP payload resample and RNNoise? • A recommendation for a specific Python RNNoise binding or a small C wrapper example?
b
Does RNNoise works with realtime model, since we are not using stt-tts pipeline
t
Yes — RNNoise can be used with the Azure Realtime model as a preprocessing step even if you’re not using a separate STT–TTS pipeline. How to use it with your realtime flow • Intercept raw audio frames from LiveKit (or from your SIP RTP → PCM stage) before sending audio to the Azure Realtime model. • Run RNNoise on each frame (resample to RNNoise rate if needed, e.g., 16 kHz), then repackage the cleaned PCM and send that audio to the realtime model input. • Keep processing streaming and low-latency: use 20–30 ms frames, minimal buffering, and resample only when required. Key considerations • RNNoise is a client/server-side DSP filter — it doesn’t replace the realtime model; it improves audio quality fed into the model. • Telephony audio (8 kHz) should be resampled to 16 kHz for best RNNoise results, then resampled back if your downstream requires 8 kHz. • Watch CPU/latency: RNNoise is lightweight but per-call CPU adds up; use worker pools or horizontal scaling for many concurrent calls. • Azure Realtime’s own
input_audio_noise_reduction
can be used in combination (RNNoise preprocessing + Azure reduction) for stronger results. If you want, I can provide: • A SIP-focused code snippet showing resample 8 kHz → 16 kHz → RNNoise → resample → send to Azure realtime, or • A short example in the specific language/runtime your agent uses. Which language is your agent written in?
b
Python, can u give some short sample, and can u tell where i need to add this code
t
Below is a short, focused Python example that shows how to run RNNoise on incoming SIP/WebRTC audio frames and forward cleaned audio to the Azure Realtime model. After the snippet I’ll state exactly where to add this in your agent pipeline. Requirements • Python runtime for your agent. • An RNNoise binding (example uses a thin wrapper
rnnoise
with a
process(frame_samples)
method). • A resampling library (example uses
resampy
). • Access to raw PCM audio frames in your LiveKit agent (or RTP→PCM conversion for SIP). Short example (assumes 16-bit PCM input; telephony 8 kHz resampled to 16 kHz):
Copy code
import numpy as np
import resampy
import rnnoise  # your RNNoise binding
# Hypothetical LiveKit agent functions:
# async for frame in pull_audio_frames(): yields AudioFrame(data: bytes, sample_rate: int, channels: int)
# await send_to_azure_realtime(pcm_bytes: bytes, sample_rate: int, channels: int)

RN_SR = 16000
FRAME_MS = 30
FRAME_SAMPLES = int(RN_SR * FRAME_MS / 1000)  # 480 samples

def bytes_to_int16(arr_bytes):
    return np.frombuffer(arr_bytes, dtype=np.int16)

def int16_to_bytes(arr):
    return arr.astype(np.int16).tobytes()

async def rnnoise_pipeline():
    rn = rnnoise.RNNoise()
    async for in_frame in pull_audio_frames():
        pcm = bytes_to_int16(in_frame.data)

        # Downmix to mono if stereo
        if in_frame.channels == 2:
            pcm = pcm.reshape(-1, 2).mean(axis=1).astype(np.int16)

        # Resample to RNNoise SR if needed
        if in_frame.sample_rate != RN_SR:
            pcm = resampy.resample(pcm.astype(np.float32), in_frame.sample_rate, RN_SR)
            pcm = np.clip(pcm, -32768, 32767).astype(np.int16)

        # Frame-wise processing
        processed_frames = []
        i = 0
        total = len(pcm)
        while i + FRAME_SAMPLES <= total:
            frame_samples = pcm[i:i + FRAME_SAMPLES]
            out = rn.process(frame_samples)  # returns int16 numpy array length FRAME_SAMPLES
            processed_frames.append(out)
            i += FRAME_SAMPLES

        # tail (zero-pad)
        if i < total:
            tail = np.zeros(FRAME_SAMPLES, dtype=np.int16)
            rem = total - i
            tail[:rem] = pcm[i:]
            out = rn.process(tail)
            processed_frames.append(out)

        cleaned = np.concatenate(processed_frames)

        # Resample back to original sample_rate if required by downstream
        target_sr = in_frame.sample_rate
        if target_sr != RN_SR:
            cleaned = resampy.resample(cleaned.astype(np.float32), RN_SR, target_sr)
            cleaned = np.clip(cleaned, -32768, 32767).astype(np.int16)

        out_bytes = int16_to_bytes(cleaned)
        await send_to_azure_realtime(out_bytes, sample_rate=target_sr, channels=1)
Where to add this code in your agent pipeline • If you get audio from LiveKit participant tracks: hook this as a preprocessing step immediately after you receive raw PCM AudioFrames and before handing audio to the Azure Realtime input. • If you ingest SIP RTP: add this after RTP→PCM decoding and before you encode/wrap audio to send to the realtime model. • If you have a central audio transform pipeline or middleware, add this as a transform that replaces the incoming audio track with the cleaned track. Practical tips • For SIP (8 kHz) resample 8→16 kHz, run RNNoise, then 16→8 kHz if your downstream requires 8 kHz. • Keep frame sizes strict (20–30 ms) to avoid artifacts and minimize latency. • Use an efficient RNNoise binding (C extension) and consider a worker pool for many concurrent calls. • Monitor CPU and latency when enabling this in production. Would you like a SIP-specific variant handling RTP packet decoding and resampling, or a recommendation for a Python RNNoise binding to use?