Use the Mini 2 firmware wake-word detector

This commit is contained in:
2026-11-11 12:37:10 +03:00
parent 9847ad6752
commit 42b9412f9c
8 changed files with 240 additions and 40 deletions
+3 -1
View File
@@ -32,7 +32,9 @@ cd /data/opt/alice-backend
## Локальная активация по фразе
Автозапуск использует [русскую модель microWakeWord «Алиса»](https://github.com/olegchumakov/microwakeword-models/tree/7a3490e3c5de3ec21442abcc7a44c74fd979917a/alisa). Сине-фиолетовое кольцо загорается после локальной активации. Клиент сохраняет начало команды и при произнесении без паузы. Срабатывание на слитную фразу зависит от модели wake word.
Автозапуск использует встроенный в прошивку Mini 2 детектор «Алиса» из `/system/vendor/quasar/spotter_models/activation/alisa`. Он получает обработанный `vqe_0` и сырой канал выбранного микрофона. Сине-фиолетовое кольцо загорается после локальной активации. Клиент сохраняет начало команды и при произнесении без паузы.
Для ручного сравнения доступна [русская модель microWakeWord «Алиса»](https://github.com/olegchumakov/microwakeword-models/tree/7a3490e3c5de3ec21442abcc7a44c74fd979917a/alisa) через флаг `-wake-model`.
Собери `alice-wake-helper` командой `cargo build --locked --release --target aarch64-unknown-linux-gnu` из каталога [wake-helper](../wake-helper) с настроенным ARM64 GNU toolchain. Положи helper и `wake-helper.sh` в `/data/opt/alice-backend`. Там же нужен файл `alisa.tflite`, скачанный из указанной версии модели. Его SHA-256 — `481cf6c180d3b5cbebfa6af47b4f9544c631d05b73cecf51fb8363ab7d143f38`. Helper использует приватный ARM64 runtime из каталога `spotify/`, включая `libstdc++.so.6`.
+23 -8
View File
@@ -12,6 +12,7 @@ import (
const pcmBlock = hop * 2
const rawBlock = hop * 3 * 16
const spotterBlock = pcmBlock + 1
// downsample is retained for manual raw-mic tests on the Mini 2.
func downsample(raw []byte) []int16 {
@@ -35,7 +36,7 @@ func pcm(samples []int16) []byte {
return data
}
func capture(device, vqeHelper string) (*liveReader, func(), error) {
func capture(device, vqeHelper, spotterModel string) (*liveReader, func(), error) {
channels, period, buffer, block := "8", "512", "2048", rawBlock
if vqeHelper != "" {
device, channels, buffer, block = "plug:default", "6", "4096", pcmBlock
@@ -63,6 +64,10 @@ func capture(device, vqeHelper string) (*liveReader, func(), error) {
}
if vqeHelper != "" {
helper := exec.Command(vqeHelper)
if spotterModel != "" {
helper.Args = append(helper.Args, spotterModel, mutePath)
block = spotterBlock
}
helper.Stdin = pipe.(*os.File)
helper.Stderr = os.Stderr
terminateWithClient(helper)
@@ -90,8 +95,9 @@ type liveReader struct {
}
type audioFrame struct {
seq uint64
pcm []int16
seq uint64
pcm []int16
wake, muted bool
}
func newLiveReader(pipe *os.File, block int) *liveReader {
@@ -113,7 +119,16 @@ func newLiveReader(pipe *os.File, block int) *liveReader {
samples[i] = int16(binary.LittleEndian.Uint16(buf[i*2:]))
}
}
frame := audioFrame{seq, samples}
frame := audioFrame{seq: seq, pcm: samples}
if block == spotterBlock {
flags := buf[pcmBlock]
if flags > 3 {
live.err = errors.New("invalid VQE spotter flags")
return
}
frame.wake = flags&1 != 0
frame.muted = flags&2 != 0
}
select {
case live.chunks <- frame:
default:
@@ -128,17 +143,17 @@ func newLiveReader(pipe *os.File, block int) *liveReader {
return live
}
func (l *liveReader) next() ([]int16, error) {
func (l *liveReader) next() (audioFrame, error) {
frame, ok := <-l.chunks
if !ok {
return nil, l.err
return audioFrame{}, l.err
}
last := l.last
l.last = frame.seq
if last != 0 && frame.seq != last+1 {
return nil, errors.New("microphone buffer overrun")
return audioFrame{}, errors.New("microphone buffer overrun")
}
return frame.pcm, nil
return frame, nil
}
func (l *liveReader) discardPending() {
+19 -10
View File
@@ -83,7 +83,11 @@ func (d *keywordDetector) close() {
}
func runKeywordWake(live *liveReader, detector *keywordDetector, activate func([]int16) error, once bool) error {
log.Print("Listening locally for the Алиса keyword model")
if detector == nil {
log.Print("Listening locally with the Mini 2 firmware spotter")
} else {
log.Print("Listening locally with microWakeWord")
}
// Keep 800 ms locally so recognition can see the whole wake word and
// any beginning of the command that overlaps the detector decision.
preroll := make([]int16, 8*rate/10)
@@ -91,13 +95,13 @@ func runKeywordWake(live *liveReader, detector *keywordDetector, activate func([
available := 0
muted := false
for {
samples, err := live.next()
frame, err := live.next()
if err != nil {
return err
}
if !unmuted() {
if frame.muted || !unmuted() {
next, available = 0, 0
if !muted {
if detector != nil && !muted {
if err := detector.reset(); err != nil {
return err
}
@@ -106,12 +110,15 @@ func runKeywordWake(live *liveReader, detector *keywordDetector, activate func([
continue
}
muted = false
copy(preroll[next:], samples)
copy(preroll[next:], frame.pcm)
next = (next + hop) % len(preroll)
available = min(available+hop, len(preroll))
detected, err := detector.process(samples)
if err != nil {
return err
detected := frame.wake
if detector != nil {
detected, err = detector.process(frame.pcm)
if err != nil {
return err
}
}
if !detected {
continue
@@ -132,8 +139,10 @@ func runKeywordWake(live *liveReader, detector *keywordDetector, activate func([
}
live.discardPending()
next, available = 0, 0
if err := detector.reset(); err != nil {
return err
if detector != nil {
if err := detector.reset(); err != nil {
return err
}
}
}
}
+23 -15
View File
@@ -147,7 +147,7 @@ func waitRecord(r *liveReader, max time.Duration, silence time.Duration, thresho
last := start
heard := false
for time.Since(start) < max {
s, e := r.next()
audio, e := r.next()
if e != nil {
return nil, e
}
@@ -159,7 +159,7 @@ func waitRecord(r *liveReader, max time.Duration, silence time.Duration, thresho
start = time.Now()
continue
}
samples = append(samples, s...)
samples = append(samples, audio.pcm...)
if len(samples) >= frameSamples {
frame := samples[:frameSamples]
if rms(frame) >= threshold {
@@ -296,13 +296,14 @@ func exchange(url, token string, live *liveReader, fileAudio []byte, wakeAudio [
if !heard && frames >= 400 {
break
}
s, err := live.next()
audio, err := live.next()
if err != nil {
return err
}
if !unmuted() {
if audio.muted || !unmuted() {
return errMuted
}
s := audio.pcm
level := rms(s)
peakRMS = math.Max(peakRMS, level)
if level >= threshold {
@@ -426,6 +427,7 @@ func main() {
input := flag.String("input", "", "16 kHz mono PCM16LE file for file mode (max 30 seconds)")
device := flag.String("capture", "hw:0,1", "ALSA capture device")
vqeHelper := flag.String("vqe-helper", "", "Mini 2 firmware VQE capture processor")
spotterModel := flag.String("vqe-wake-model", "", "firmware spotter model directory")
playback := flag.String("playback", "default", "ALSA playback device")
url := flag.String("url", "wss://alice.pepega.systems/v1/voice", "server websocket URL")
keywordModel := flag.String("wake-model", "", "optional local microWakeWord model path")
@@ -438,6 +440,9 @@ func main() {
max := flag.Duration("max", 12*time.Second, "maximum request duration")
silence := flag.Duration("silence", 1200*time.Millisecond, "end after speech silence")
flag.Parse()
if *spotterModel != "" && (*mode != "wake" || *vqeHelper == "" || *keywordModel != "") {
log.Fatal("-vqe-wake-model requires -mode wake and -vqe-helper, without -wake-model")
}
mutePath = *muteGPIO
lights.start()
defer lights.stop()
@@ -451,7 +456,7 @@ func main() {
var ts []template
var e error
if *mode == "wake" {
if *keywordModel == "" {
if *keywordModel == "" && *spotterModel == "" {
ts, e = loadTemplates(*path)
if e != nil {
log.Fatal(e)
@@ -484,7 +489,7 @@ func main() {
log.Fatal(e)
}
}
live, stopCapture, e := capture(*device, *vqeHelper)
live, stopCapture, e := capture(*device, *vqeHelper, *spotterModel)
if e != nil {
log.Fatal(e)
}
@@ -526,16 +531,19 @@ func main() {
}
go listenVolumeButtons(*playback)
if *keywordModel != "" {
detector, err := startKeywordDetector(*keywordHelper, *keywordModel)
if err != nil {
cleanup()
log.Fatalf("keyword model: %v", err)
if *keywordModel != "" || *spotterModel != "" {
var detector *keywordDetector
if *keywordModel != "" {
detector, e = startKeywordDetector(*keywordHelper, *keywordModel)
if e != nil {
cleanup()
log.Fatalf("keyword model: %v", e)
}
defer detector.close()
}
err = runKeywordWake(live, detector, func(preroll []int16) error {
err := runKeywordWake(live, detector, func(preroll []int16) error {
return exchange(*url, token, live, nil, preroll, *th, *max, *silence, *playback)
}, *oneTurn)
detector.close()
if err != nil {
cleanup()
log.Fatalf("keyword detector: %v", err)
@@ -550,7 +558,7 @@ func main() {
active := false
quiet := 0
for {
s, e := live.next()
audio, e := live.next()
if e != nil {
cleanup()
log.Fatal(e)
@@ -562,7 +570,7 @@ func main() {
quiet = 0
continue
}
samples = append(samples, s...)
samples = append(samples, audio.pcm...)
if len(samples) < frameSamples {
continue
}
+30
View File
@@ -57,3 +57,33 @@ func TestLiveReaderEOFStaysEOF(t *testing.T) {
}
}
}
func TestLiveReaderSpotterFlags(t *testing.T) {
in, out, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer in.Close()
defer out.Close()
packet := make([]byte, spotterBlock)
binary.LittleEndian.PutUint16(packet, 123)
packet[pcmBlock] = 1
if _, err := out.Write(packet); err != nil {
t.Fatal(err)
}
packet[pcmBlock] = 2
if _, err := out.Write(packet); err != nil {
t.Fatal(err)
}
out.Close()
reader := newLiveReader(in, spotterBlock)
frame, err := reader.next()
if err != nil || !frame.wake || frame.muted || len(frame.pcm) != hop || frame.pcm[0] != 123 {
t.Fatalf("wake packet: %+v, %v", frame, err)
}
frame, err = reader.next()
if err != nil || frame.wake || !frame.muted {
t.Fatalf("muted packet: %+v, %v", frame, err)
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ while [ "$stopping" -eq 0 ]; do
DEVICE_TOKEN=$(cat device-token)
export DEVICE_TOKEN
: > /tmp/alice-station.log
./alice-station -mode wake -voice-threshold 24 -vqe-helper /data/opt/alice-backend/vqe-capture.sh -wake-model /data/opt/alice-backend/alisa.tflite >> /tmp/alice-station.log 2>&1 9>&- &
./alice-station -mode wake -voice-threshold 24 -vqe-helper /data/opt/alice-backend/vqe-capture.sh -vqe-wake-model /system/vendor/quasar/spotter_models/activation/alisa >> /tmp/alice-station.log 2>&1 9>&- &
child=$!
while [ "$stopping" -eq 0 ] && kill -0 "$child" 2>/dev/null; do
if [ "$(wc -c < /tmp/alice-station.log)" -gt 524288 ]; then : >/tmp/alice-station.log; fi
+1 -1
View File
@@ -8,4 +8,4 @@ if ! printf '%s %s\n' fa7ad1544fe9ddfccedcf15acc031768345b0b8c7333bc1c0b47bc476
exit 1
fi
export LD_LIBRARY_PATH=/system/vendor/quasar/libs
exec ./alice-vqe
exec ./alice-vqe "$@"
+140 -4
View File
@@ -1,14 +1,18 @@
// Mini 2 armhf firmware ABI, verified against libyandex_evil BuildID
// d1d0f12f8f8389c0ca72672c61530161b85353c9 (Quasar 3.21).
// stdin: ALSA plug:default, 48 kHz S16_LE, four mics followed by stereo speaker feedback.
// stdout: vqe_0, 16 kHz mono S16_LE.
// stdout: vqe_0, 16 kHz mono S16_LE. In spotter mode, each 10 ms block
// is followed by one byte of flags (bit 0: wake, bit 1: mute).
#include <dlfcn.h>
#include <math.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { INPUT = 1536, OUTPUT = 512, MICS = 4, SPEAKERS = 2, ASR_CHANNEL = 6 };
enum { INPUT = 1536, OUTPUT = 512, HOP = 160, MICS = 4, SPEAKERS = 2,
RAW_MIC_CHANNEL = 1, ASR_CHANNEL = 6, WAKE = 1, MUTED = 2 };
static const char *(*error_message)(void *);
static void (*error_free)(void *);
@@ -37,7 +41,96 @@ static int16_t pcm(float sample) {
return (int16_t)value;
}
int main(void) {
struct spotter {
void *config, *model;
void *(*create)(void *, int, size_t, const int *, int, void **);
void (*destroy)(void *, void **);
void (*free_config)(void *, void **);
void (*submit)(void *, const int16_t *, size_t, void **);
int (*next_event)(void *, void **);
const char *(*phrase)(void *, void **);
const char *(*error_message)(void *);
void (*error_free)(void *);
};
static void check_spotter(struct spotter *spot, void *error) {
if (!error) return;
fprintf(stderr, "Spotter: %s\n", spot->error_message(error));
spot->error_free(error);
exit(1);
}
static void start_spotter(struct spotter *spot) {
// The bundled activation model consumes the cleaned stream and one raw mic.
const int channels[] = {0, 4};
void *error = NULL;
spot->model = spot->create(spot->config, 16000, 2, channels, 0, &error);
check_spotter(spot, error);
if (!spot->model) exit(1);
}
static void stop_spotter(struct spotter *spot) {
if (!spot->model) return;
void *error = NULL;
spot->destroy(spot->model, &error);
check_spotter(spot, error);
spot->model = NULL;
}
static void load_spotter(struct spotter *spot, void *lib, const char *path) {
#define SPOT(name) symbol(lib, "spotter_" #name)
void *(*read_config)(const char *, void **) = SPOT(conf_read);
spot->create = SPOT(create_multichannel);
spot->destroy = SPOT(destroy);
spot->free_config = SPOT(conf_free);
spot->submit = SPOT(submit_raw_data);
spot->next_event = SPOT(get_next_event);
spot->phrase = SPOT(get_current_phrase);
spot->error_message = SPOT(error_get_message);
spot->error_free = SPOT(error_free);
#undef SPOT
void *error = NULL;
spot->config = read_config(path, &error);
check_spotter(spot, error);
if (!spot->config) exit(1);
start_spotter(spot);
}
static bool detect(struct spotter *spot, const int16_t *clean, const float *raw) {
int16_t audio[OUTPUT][2];
for (size_t i = 0; i < OUTPUT; ++i) {
audio[i][0] = clean[i];
audio[i][1] = pcm(raw[i]);
}
void *error = NULL;
spot->submit(spot->model, &audio[0][0], sizeof(audio), &error);
check_spotter(spot, error);
bool detected = false;
for (;;) {
int event = spot->next_event(spot->model, &error);
check_spotter(spot, error);
if (event == 0) return detected;
if (event != 2) continue;
const char *phrase = spot->phrase(spot->model, &error);
check_spotter(spot, error);
if (phrase && strcmp(phrase, "алиса") == 0) detected = true;
}
}
static bool mic_unmuted(const char *path) {
FILE *file = fopen(path, "r");
if (!file) return false;
int value = fgetc(file);
fclose(file);
return value == '1';
}
int main(int argc, char **argv) {
if (argc != 1 && argc != 3) {
fprintf(stderr, "Usage: alice-vqe [SPOTTER_MODEL MUTE_GPIO]\n");
return 1;
}
const bool use_spotter = argc == 3;
void *lib = dlopen("/system/vendor/quasar/libs/libyandex_evil.so", RTLD_NOW | RTLD_LOCAL);
if (!lib) {
fprintf(stderr, "VQE: %s\n", dlerror());
@@ -57,6 +150,7 @@ int main(void) {
void (*destroy)(void *) = VQE(Free);
void *(*process)(void *, const float *, size_t, const float *, size_t) = VQE(Process);
void *(*channel)(void *, int, size_t, const float **, size_t *) = VQE(GetOutputChannelData);
void *(*omni_mic)(void *, size_t *) = VQE(GetOmniMicIndex);
#undef VQE
void *config = NULL, *vqe = NULL;
@@ -69,10 +163,16 @@ int main(void) {
check(create(config, "/system/vendor/quasar/vqe_models", 0, NULL, &vqe));
free_config(config);
struct spotter spot = {0};
if (use_spotter) load_spotter(&spot, lib, argv[1]);
int16_t input[INPUT][MICS + SPEAKERS], output[OUTPUT];
float mics[INPUT][MICS], speakers[INPUT][SPEAKERS];
// Suppress the PDM startup transient while warming the processor (512 ms).
unsigned warmup = 16;
uint8_t packet[HOP * sizeof(int16_t) + 1];
size_t packet_samples = 0;
bool partial_muted = false;
while (fread(input, sizeof(input), 1, stdin) == 1) {
for (size_t i = 0; i < INPUT; ++i) {
for (size_t j = 0; j < MICS; ++j) mics[i][j] = input[i][j] / 32768.0f;
@@ -91,7 +191,43 @@ int main(void) {
continue;
}
for (size_t i = 0; i < OUTPUT; ++i) output[i] = pcm(samples[i]);
if (fwrite(output, sizeof(output), 1, stdout) != 1 || fflush(stdout) != 0) return 1;
if (!use_spotter) {
if (fwrite(output, sizeof(output), 1, stdout) != 1 || fflush(stdout) != 0) return 1;
continue;
}
bool detected = false;
bool chunk_muted = !mic_unmuted(argv[2]);
if (!chunk_muted) {
if (!spot.model) start_spotter(&spot);
size_t mic = 0;
check(omni_mic(vqe, &mic));
check(channel(vqe, RAW_MIC_CHANNEL, mic, &samples, &count));
if (count != OUTPUT || !samples) return 1;
// The last 10 ms packet in this chunk carries the spotter event.
detected = detect(&spot, output, samples);
} else {
stop_spotter(&spot);
memset(output, 0, sizeof(output));
}
for (size_t i = 0; i < OUTPUT; ++i) {
memcpy(packet + packet_samples++ * sizeof(int16_t), &output[i], sizeof(int16_t));
if (packet_samples != HOP) continue;
bool last = OUTPUT - i - 1 < HOP;
packet[sizeof(packet) - 1] =
(last && detected ? WAKE : 0) | (chunk_muted || partial_muted ? MUTED : 0);
if (fwrite(packet, sizeof(packet), 1, stdout) != 1) return 1;
packet_samples = 0;
partial_muted = false;
}
// If the final packet straddles two chunks, carry its mute state.
partial_muted = chunk_muted && packet_samples != 0;
if (fflush(stdout) != 0) return 1;
}
if (use_spotter) {
stop_spotter(&spot);
void *error = NULL;
spot.free_config(spot.config, &error);
check_spotter(&spot, error);
}
destroy(vqe);
return ferror(stdin) ? 1 : 0;