Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:78 Xiaozhi esp32 Opus Decoder

From Leeroopedia
Knowledge Sources
Domains Audio_Coding, Compression
Last Updated 2026-10-17 00:00 GMT

Overview

Concrete tool for decoding Opus audio to PCM format provided by the ESP-Opus component, wrapped by the XiaoZhi firmware's AudioService for real-time TTS playback with dynamic sample rate reconfiguration.

Description

The Opus decoder is an external library API (ESP-Opus) used by XiaoZhi's AudioService::OpusCodecTask() to decompress server-sent Opus packets into PCM audio for speaker playback. This is a Wrapper Doc.

The decoder is configured via the OPUS_DEC_CFG macro:

  • Channels: Mono
  • Self-delimited: false (each frame is independent)

Unlike the encoder, the decoder must handle variable sample rates from the server (typically 24kHz, but may change). The SetDecodeSampleRate() method recreates the decoder handle when the sample rate or frame duration changes, and creates a new output resampler to convert from the server's sample rate to the speaker codec's native rate.

The decode loop:

  1. Pop AudioStreamPacket from audio_decode_queue_
  2. Check if sample rate changed; if so, call SetDecodeSampleRate()
  3. Call esp_opus_dec_decode() to produce PCM
  4. If output resampler exists, resample to speaker native rate
  5. Push AudioTask to audio_playback_queue_

Usage

Reference this implementation when:

  • Understanding Opus decoder configuration
  • Tracing the decode path in the audio pipeline
  • Handling dynamic sample rate changes
  • Debugging TTS playback quality

Code Reference

Source Location

  • Repository: XiaoZhi ESP32
  • Files: main/audio/audio_service.h (config macro), main/audio/audio_service.cc (decoder init and decode loop)

Signature

// ESP-Opus external API (from esp_opus_dec.h)
esp_err_t esp_opus_dec_open(esp_opus_dec_cfg_t* cfg, int cfg_size, void** handle);
esp_err_t esp_opus_dec_decode(void* handle,
                                esp_audio_dec_in_raw_t* raw,
                                esp_audio_dec_out_frame_t* out,
                                esp_audio_dec_info_t* info);
esp_err_t esp_opus_dec_reset(void* handle);
void esp_opus_dec_close(void* handle);

// XiaoZhi configuration macro
#define OPUS_DEC_CFG(sample_rate, frame_duration) \
    { \
        .sample_rate = sample_rate, \
        .channel = ESP_AUDIO_MONO, \
        .self_delimited = false, \
    }

// AudioService method to handle sample rate changes
void AudioService::SetDecodeSampleRate(int sample_rate, int frame_duration);

Import

#include "esp_opus_dec.h"
#include "esp_audio_enc.h"  // for esp_audio_dec_* types
// Used internally by audio_service.h

I/O Contract

Inputs

Name Type Required Description
cfg esp_opus_dec_cfg_t* Decoder config (sample_rate, channel, self_delimited)
raw esp_audio_dec_in_raw_t* Input Opus frame: {buffer, size}
packet AudioStreamPacket From decode queue: {sample_rate, frame_duration, payload}

Outputs

Name Type Description
out Output PCM: {buffer, size, decoded_size}
info Decoded frame info (sample rate, channels)
AudioTask PCM pushed to playback queue with timestamp and playback_id

Usage Examples

Decoder Initialization

// In AudioService::Initialize() — initial decoder (recreated on rate change)
esp_opus_dec_cfg_t dec_cfg = OPUS_DEC_CFG(24000, 60);
esp_opus_dec_open(&dec_cfg, sizeof(dec_cfg), &opus_decoder_);

Decode Loop

// In AudioService::OpusCodecTask() — decode section
while (true) {
    auto packet = audio_decode_queue_.Pop();  // blocks until available

    // Check for sample rate change
    if (packet->sample_rate != decoder_sample_rate_ ||
        packet->frame_duration != decoder_duration_ms_) {
        SetDecodeSampleRate(packet->sample_rate, packet->frame_duration);
    }

    // Decode Opus to PCM
    esp_audio_dec_in_raw_t raw = {
        .buffer = packet->payload.data(),
        .size = (int)packet->payload.size()
    };
    std::vector<int16_t> pcm(decoder_frame_size_);
    esp_audio_dec_out_frame_t out = {
        .buffer = pcm.data(),
        .size = (int)pcm.size() * sizeof(int16_t)
    };
    esp_audio_dec_info_t info;
    esp_opus_dec_decode(opus_decoder_, &raw, &out, &info);

    // Resample to speaker native rate if needed
    if (output_resampler_ != nullptr) {
        // esp_ae_rate_cvt_process(...)
    }

    // Push to playback queue
    AudioTask task;
    task.pcm = std::move(pcm);
    task.timestamp = packet->timestamp;
    task.playback_id = packet->playback_id;
    audio_playback_queue_.Push(std::move(task));
}

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment