bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

210
main/audio/audio_service.h Normal file
View File

@@ -0,0 +1,210 @@
#pragma once
#include "audio_codec.h"
#include "wake_word.h"
#include "voice_processor.h"
#include <opus_encoder.h>
#include <opus_decoder.h>
#include <opus_resampler.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <functional>
#include <memory>
#include <deque>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <atomic>
#define OPUS_FRAME_DURATION_MS 60
// 音频任务项
struct AudioTask {
enum Type { kEncode, kPlayback };
Type type;
std::vector<int16_t> pcm;
};
// 音频流包(与 Protocol 层交互)
struct AudioStreamPacket {
int sample_rate = 0;
int frame_duration = 0;
uint32_t timestamp = 0;
std::vector<uint8_t> payload;
};
struct AudioServiceCallbacks {
std::function<void()> on_send_queue_available;
// Fired by energy-threshold VAD (rough RMS detector) when sustained voice
// energy is observed. One-shot: VAD auto-disables after firing. Used by
// IdleWatchdog to detect "child responded" inside the post-prompt window.
std::function<void()> on_voice_detected;
};
// 音频服务:管理 3 个 FreeRTOS 任务实现音频采集 → Opus 编码 → 发送
// 接收 → Opus 解码 → 播放
class AudioService {
public:
void Initialize(AudioCodec* codec);
void Start();
void Stop();
void SetCallbacks(const AudioServiceCallbacks& callbacks);
// Play a generated tone through the speaker
// freq_hz: frequency, duration_ms: length, volume: 0.0-1.0
void PlayTone(int freq_hz, int duration_ms, float volume = 0.3f);
// Play predefined sound effects
void PlayBootSound();
void PlayShutdownSound();
void PlayConfigSound();
void PlayErrorSound();
// 上行:编码后的 Opus 包从发送队列弹出
std::unique_ptr<AudioStreamPacket> PopPacketFromSendQueue();
// 下行:收到 server Opus 音频包,入解码队列
void PushPacketToDecodeQueue(std::unique_ptr<AudioStreamPacket> packet);
// 播放控制
void SetPlaybackHint(bool playing);
void ResetDecoder();
// 2026-6-29 ckkj debug 获取解码、播放队列是否为空
void GetQueueEmptyStatus(bool& decode_empty, bool& play_empty);
// Clear the cancel flag and bump the generation counter before starting a
// new local prompt. Generation lets in-flight PlayTask from the previous
// iteration self-exit even if its cancel-flag check is racing against this
// BeginNewPlayback() (cancel may have been re-cleared to false before the
// old task wakes from vTaskDelay). Must be called right before
// xTaskCreate(PlayTask, ...).
void BeginNewPlayback() {
playback_cancelled_.store(false);
playback_generation_.fetch_add(1, std::memory_order_relaxed);
}
bool IsPlaybackCancelled() const { return playback_cancelled_.load(); }
int CurrentPlaybackGeneration() const {
return playback_generation_.load(std::memory_order_relaxed);
}
// 录音控制(语音处理开关)
void EnableVoiceProcessing(bool enable);
// Phone-call mode: enable AEC+NS+AGC on MIC path, with downlink PCM as
// the speaker reference signal. On enable the VoiceProcessor is lazy-
// initialized; on disable the processor is torn down and the reference
// queue cleared.
void EnableCallMode(bool enable);
bool IsCallModeEnabled() const { return call_mode_enabled_.load(); }
// TTS barge-in mode: keep MIC upload active during Speaking and reuse the
// VoiceProcessor/AEC reference path so the server can hear the child
// without treating the speaker's own TTS as speech.
void EnableBargeInMode(bool enable);
bool IsBargeInModeEnabled() const { return barge_in_mode_enabled_.load(); }
// 能量阈值粗 VAD(用于 IdleWatchdog 检测 15s 等待窗口内是否有声音)
// 一次性触发:on_voice_detected 回调后自动 disable,需重新 enable。
// 仅在 wake_word 或 voice_processing 已启用(MIC 在采集)时生效。
void EnableEnergyVad(bool enable);
bool IsEnergyVadEnabled() const { return energy_vad_enabled_.load(); }
// 唤醒词检测
bool InitWakeWord();
void EnableWakeWordDetection(bool enable);
bool IsWakeWordDetectionEnabled() const { return wake_word_enabled_.load(); }
WakeWordDetector& wake_word_detector() { return wake_word_detector_; }
bool IsIdle() const;
// Wait until decode and playback queues are empty (audio finished playing)
void WaitForPlaybackComplete(int timeout_ms);
private:
static void AudioInputTask(void* arg);
static void AudioOutputTask(void* arg);
static void OpusCodecTask(void* arg);
AudioCodec* codec_ = nullptr;
AudioServiceCallbacks callbacks_;
// Opus 编解码器
std::unique_ptr<OpusEncoderWrapper> opus_encoder_;
std::unique_ptr<OpusDecoderWrapper> opus_decoder_;
std::unique_ptr<OpusResampler> input_resampler_;
std::unique_ptr<OpusResampler> output_resampler_;
// Downsamples decoded downlink PCM (at decoder rate, typically 24k)
// to 16kHz for the AEC reference path. Only used in call mode.
std::unique_ptr<OpusResampler> aec_ref_resampler_;
// 队列(用 deque + mutex + cv 替代 FreeRTOS Queue,与 xiaozhi 对齐)
std::deque<std::unique_ptr<AudioTask>> encode_queue_;
std::mutex encode_mutex_;
std::condition_variable encode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> decode_queue_;
std::mutex decode_mutex_;
std::condition_variable decode_cv_;
std::deque<std::unique_ptr<AudioStreamPacket>> send_queue_;
std::mutex send_mutex_;
std::deque<std::unique_ptr<AudioTask>> playback_queue_;
std::mutex playback_mutex_;
std::condition_variable playback_cv_;
// FreeRTOS 任务
TaskHandle_t input_task_ = nullptr;
TaskHandle_t output_task_ = nullptr;
TaskHandle_t codec_task_ = nullptr;
std::atomic<bool> running_{false};
std::atomic<bool> voice_processing_enabled_{false};
std::atomic<bool> wake_word_enabled_{false};
std::atomic<bool> playback_hint_{false};
std::atomic<bool> call_mode_enabled_{false}; // AEC+NS+AGC active when true
std::atomic<bool> barge_in_mode_enabled_{false};
std::atomic<bool> energy_vad_enabled_{false}; // Rough RMS-based VAD for IdleWatchdog
int vad_consecutive_frames_ = 0;
// Voice processing pipeline for phone-call mode. Lazy-inited on first
// EnableCallMode(true); torn down on EnableCallMode(false).
std::mutex voice_processor_mutex_;
std::unique_ptr<VoiceProcessor> voice_processor_;
// Reference PCM queue — 16kHz mono int16 frames written by AudioOutputTask
// when downlink audio is actually sent to the speaker, then consumed by
// AudioInputTask paired with freshly-captured MIC PCM for AEC.
// Keeping this tied to real playback timing avoids feeding the canceller
// an early reference while frames are still buffered in playback_queue_.
std::deque<std::vector<int16_t>> aec_ref_queue_;
std::mutex aec_ref_mutex_;
static constexpr size_t kMaxAecRefFrames = 10; // ~600ms buffer
// Encoder accumulator for call mode. VoiceProcessor emits chunks whose
// size depends on AEC/NS alignment (not 60ms). This buffer collects
// clean PCM and hands it to OpusEncoder in fixed 960-sample (60ms@16k)
// frames. Only used in call mode — the non-call path sends raw 60ms
// frames directly.
std::vector<int16_t> vp_encoder_acc_;
// Set true by ResetDecoder; PlayEmbeddedOpus (audio_prompt) checks it each
// frame and breaks early so the local-prompt task stops re-filling the
// queue after an abort (e.g. wake-word interrupt during alarm ringing).
std::atomic<bool> playback_cancelled_{false};
// Bumped by BeginNewPlayback. Each PlayTask captures the value at start
// and self-exits when CurrentPlaybackGeneration() != captured value —
// immune to the cancel-flag race in tight Reset→BeginNew sequences.
std::atomic<int> playback_generation_{0};
WakeWordDetector wake_word_detector_;
std::vector<int16_t> wake_word_buffer_;
static constexpr int kInputSampleRate = 16000;
static constexpr int kMaxEncodeQueueSize = 2;
static constexpr int kMaxDecodeQueueSize = 40; // 2400ms / 60ms
static constexpr int kMaxSendQueueSize = 40;
static constexpr int kMaxPlaybackQueueSize = 8;
};