diff --git a/core.go b/core.go index 80c0ba6..cda172a 100644 --- a/core.go +++ b/core.go @@ -46,6 +46,7 @@ type Core struct { features ffmpeg.Features hotkeyErrs []string dl downloadState + voice voiceState aiQueue chan string upd updater ctx context.Context @@ -76,7 +77,10 @@ func newCore(dataDir string) (*Core, error) { Tools: c.Tools, Encoders: c.Encoders, Features: c.Features, - OnChange: c.pushStatus, + OnChange: func() { + c.syncVoice() + c.pushStatus() + }, }) c.lib = library.Open(dataDir, c.Tools, func() { c.emit("clips:changed", nil) }) c.jobs = jobs.New(jobs.Deps{ @@ -257,6 +261,7 @@ type AppStatus struct { FFmpeg ffmpeg.Tools `json:"ffmpeg"` FFmpegReady bool `json:"ffmpegReady"` Download downloadState `json:"download"` + Voice voiceStatus `json:"voice"` HotkeyErrors []string `json:"hotkeyErrors"` ActiveJobs int `json:"activeJobs"` } @@ -267,6 +272,7 @@ func (c *Core) Status() AppStatus { st := AppStatus{FFmpeg: c.tools, FFmpegReady: c.tools.FFmpeg != "", Download: c.dl, HotkeyErrors: c.hotkeyErrs} c.mu.Unlock() st.Recorder = c.rec.Status() + st.Voice = c.voiceStatus() st.Usage = c.lib.Usage(s.ClipsDir, s) for _, j := range c.jobs.List() { if j.Status == "queued" || j.Status == "running" { @@ -308,6 +314,8 @@ func (c *Core) start() { go c.shrinkLoop() go c.updateLoop() go c.aiWorker() + c.refreshVoiceReady() + c.syncVoice() go func() { t := time.NewTicker(time.Second) defer t.Stop() @@ -454,6 +462,10 @@ func (c *Core) applySettings(prev, next config.Settings) { if prev.SmartMode && !next.SmartMode && next.AutoStartBuffer { c.rec.Start() } + if prev.VoiceDir != next.VoiceDir { + c.refreshVoiceReady() + } + c.syncVoice() c.pushStatus() } @@ -484,38 +496,52 @@ func ceilingFor(t ffmpeg.Tools, encs []ffmpeg.Encoder) int { return 1 << 20 } -func (c *Core) download() error { - c.mu.Lock() - if c.dl.Active { - c.mu.Unlock() +func (c *Core) runDownload(mu *sync.Mutex, st *downloadState, fn func(progress func(done, total int64)) error) error { + mu.Lock() + if st.Active { + mu.Unlock() return errors.New("download already running") } - c.dl = downloadState{Active: true} + *st = downloadState{Active: true} + mu.Unlock() + c.pushStatus() + + err := fn(func(done, total int64) { + mu.Lock() + st.Done, st.Total = done, total + mu.Unlock() + }) + + mu.Lock() + st.Active = false + if err != nil { + st.Error = err.Error() + } + mu.Unlock() + c.pushStatus() + return err +} + +func (c *Core) download() error { + c.mu.Lock() below := ceilingFor(c.tools, c.encoders) c.mu.Unlock() - c.pushStatus() nvidia := false for _, g := range winapi.GPUs() { nvidia = nvidia || g.Vendor == "nvidia" } - _, err := ffmpeg.DownloadFitting(c.ctx, c.store.Get().FFmpegInstallDir(c.dataDir), below, nvidia, func(done, total int64) { - c.mu.Lock() - c.dl.Done, c.dl.Total = done, total - c.mu.Unlock() - c.emit("ffmpeg:progress", map[string]int64{"done": done, "total": total}) + err := c.runDownload(&c.mu, &c.dl, func(progress func(done, total int64)) error { + _, err := ffmpeg.DownloadFitting(c.ctx, c.store.Get().FFmpegInstallDir(c.dataDir), below, nvidia, func(done, total int64) { + progress(done, total) + c.emit("ffmpeg:progress", map[string]int64{"done": done, "total": total}) + }) + if err == nil { + c.probeTools(true) + } + return err }) - if err == nil { - c.probeTools(true) - } - c.mu.Lock() - c.dl.Active = false if err != nil { - c.dl.Error = err.Error() - } - c.mu.Unlock() - if err != nil { - c.pushStatus() return err } if nvencTooOld(c.Encoders()) { @@ -523,7 +549,7 @@ func (c *Core) download() error { } s := c.store.Get() c.lib.Scan(s.ClipsDir, s.ExportsPath()) - if s.AutoStartBuffer && !s.SmartMode && c.rec.Status().State == recorder.Idle { + if s.AutoStartBuffer && !s.SmartMode && c.rec.State() == recorder.Idle { c.rec.Start() } return nil diff --git a/frontend/src/features/settings/Settings.tsx b/frontend/src/features/settings/Settings.tsx index b5d911c..2818868 100644 --- a/frontend/src/features/settings/Settings.tsx +++ b/frontend/src/features/settings/Settings.tsx @@ -11,12 +11,14 @@ import { HotkeysSection } from "./sections/Hotkeys"; import { SharingSection } from "./sections/Sharing"; import { StorageSection } from "./sections/Storage"; import { VideoSection } from "./sections/Video"; +import { VoiceSection } from "./sections/Voice"; export const sections = [ ["capture", "Video"], ["buffer", "Clips"], ["audio", "Audio"], ["hotkeys", "Hotkeys"], + ["voice", "Voice"], ["storage", "Storage"], ["sharing", "Sharing"], ["ai", "AI"], @@ -70,6 +72,7 @@ export function Settings() { + diff --git a/frontend/src/features/settings/parts.tsx b/frontend/src/features/settings/parts.tsx index a4b8861..1d465e8 100644 --- a/frontend/src/features/settings/parts.tsx +++ b/frontend/src/features/settings/parts.tsx @@ -1,4 +1,5 @@ -import type { ReactNode } from "react"; +import { useEffect, useState, type InputHTMLAttributes, type ReactNode } from "react"; +import { Input } from "@/components/ui/input"; import type { Settings as S } from "@/lib/api"; export { Row } from "@/components/ui/row"; @@ -13,3 +14,32 @@ export function Section({ id, title, children }: { id: string; title: string; ch ); } + +export function DraftInput({ + value, + onCommit, + allowEmpty = false, + ...rest +}: { + value: string; + onCommit: (v: string) => void; + allowEmpty?: boolean; +} & Omit, "value" | "onChange">) { + const [draft, setDraft] = useState(value); + useEffect(() => setDraft(value), [value]); + const commit = () => { + const v = draft.trim(); + if (!v && !allowEmpty) return setDraft(value); + if (v !== value) onCommit(v); + }; + return ( + setDraft(e.target.value)} + onBlur={commit} + onKeyDown={(e) => e.key === "Enter" && commit()} + /> + ); +} diff --git a/frontend/src/features/settings/sections/Sharing.tsx b/frontend/src/features/settings/sections/Sharing.tsx index 7f7c611..67b7c84 100644 --- a/frontend/src/features/settings/sections/Sharing.tsx +++ b/frontend/src/features/settings/sections/Sharing.tsx @@ -5,10 +5,9 @@ import { Dialog } from "@/components/ui/dialog"; import { Tip } from "@/components/ui/tooltip"; import { Select } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; -import { Input } from "@/components/ui/input"; import { api, openUrl, type Uploader } from "@/lib/api"; import { useStore } from "@/lib/store"; -import { Row, Section, type SectionProps } from "../parts"; +import { DraftInput, Row, Section, type SectionProps } from "../parts"; export function SharingSection({ s, set }: SectionProps) { const [list, setList] = useState([]); @@ -119,9 +118,6 @@ export function SharingSection({ s, set }: SectionProps) { } function UserhashRow({ value, onSave }: { value: string; onSave: (v: string) => void }) { - const [v, setV] = useState(value); - useEffect(() => setV(value), [value]); - const commit = () => v.trim() !== value && onSave(v.trim()); return ( } > - setV(e.target.value)} - onBlur={commit} - onKeyDown={(e) => e.key === "Enter" && commit()} + onCommit={onSave} className="w-[240px]" - spellCheck={false} autoComplete="off" /> diff --git a/frontend/src/features/settings/sections/Voice.tsx b/frontend/src/features/settings/sections/Voice.tsx new file mode 100644 index 0000000..04d1868 --- /dev/null +++ b/frontend/src/features/settings/sections/Voice.tsx @@ -0,0 +1,110 @@ +import { useEffect, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { Slider } from "@/components/ui/slider"; +import { Switch } from "@/components/ui/switch"; +import { api } from "@/lib/api"; +import { useStore } from "@/lib/store"; +import { DraftInput, Row, Section, type SectionProps } from "../parts"; + +export function VoiceSection({ s, set }: SectionProps) { + const voice = useStore((st) => st.status?.voice); + const [sens, setSens] = useState(s.voiceSensitivity); + useEffect(() => setSens(s.voiceSensitivity), [s.voiceSensitivity]); + + const dl = voice?.download; + const pct = dl?.total ? Math.round((dl.done / dl.total) * 100) : 0; + const dlLabel = dl?.active ? `Downloading ${pct}%` : voice?.ready ? "Download again" : "Download"; + + return ( +
+

+ Say a phrase to save a clip. Only listens while capturing. Uses the mic + from Audio. +

+ + set({ voiceTrigger: v })} + /> + + {s.voiceTrigger && ( + <> + + set({ voicePhrase: v })} + className="w-[320px]" + /> + + +
+ setSens(v)} + onValueCommit={([v]) => set({ voiceSensitivity: v })} + /> + + {sens} + +
+
+ + + + {voice?.dir}} + > +
+ {s.voiceDir && ( + + )} + +
+
+ {voice?.error &&

{voice.error}

} + {dl?.error && !dl.active && ( +

{dl.error}

+ )} +

+ Runs on your PC, nothing is sent anywhere. +

+ + )} +
+ ); +} diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index a6d7d68..194b54b 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -36,6 +36,10 @@ export type Settings = { aiModel: string; aiAutoTitle: boolean; aiTranscribe: boolean; + voiceTrigger: boolean; + voicePhrase: string; + voiceDir: string; + voiceSensitivity: number; systemDeviceId: string; micDeviceId: string; hotkeys: Hotkeys; @@ -93,7 +97,8 @@ export type AppStatus = { usage: Usage; ffmpeg: { ffmpeg: string; ffprobe: string; version: string }; ffmpegReady: boolean; - download: { active: boolean; done: number; total: number; error: string }; + download: Download; + voice: { ready: boolean; dir: string; error: string; download: Download }; hotkeyErrors: string[]; activeJobs: number; }; @@ -164,6 +169,8 @@ export type UpdateState = { available: boolean; checking: boolean; latest: strin export type Uploader = { id: string; name: string; host: string; builtin: boolean; videoReady: boolean }; +export type Download = { active: boolean; done: number; total: number; error: string }; + export type AIProvider = { id: string; label: string; model: string; transcribe: boolean; keyUrl: string }; export type Job = { @@ -255,6 +262,7 @@ export const api = { pickSoundFile: () => call("PickSoundFile"), addBookmark: () => call("AddBookmark"), downloadFFmpeg: () => call("DownloadFFmpeg"), + downloadVoice: () => call("DownloadVoice"), reprobe: () => call("ReprobeEncoders"), audioDevices: () => call<{ outputs: AudioDevice[]; inputs: AudioDevice[] }>("ListAudioDevices"), monitors: () => call("ListMonitors"), diff --git a/frontend/src/lib/mock.ts b/frontend/src/lib/mock.ts index 7add70b..905295b 100644 --- a/frontend/src/lib/mock.ts +++ b/frontend/src/lib/mock.ts @@ -105,6 +105,10 @@ let settings: Settings = { aiModel: "", aiAutoTitle: true, aiTranscribe: false, + voiceTrigger: false, + voicePhrase: "clip that", + voiceDir: "", + voiceSensitivity: 50, smartMode: false, autoStartBuffer: true, saveSound: true, @@ -159,6 +163,7 @@ function status(): AppStatus { ffmpeg: { ffmpeg: "ffmpeg.exe", ffprobe: "ffprobe.exe", version: "8.0" }, ffmpegReady: !scenario.noFFmpeg, download: { active: false, done: 0, total: 0, error: "" }, + voice: { ready: false, dir: "C:\\Users\\you\\AppData\\Local\\Snag\\kws", error: "", download: { active: false, done: 0, total: 0, error: "" } }, hotkeyErrors: [], activeJobs: jobs.filter((j) => j.status === "running" || j.status === "queued").length, }; @@ -297,6 +302,7 @@ const handlers: Record unknown> = { SaveClip: () => setTimeout(() => emit("toast", { kind: "success", message: `Saved ${liveGame} 2026-10-24 19-41-03` }), 300), AddBookmark: () => emit("toast", { kind: "info", message: "Bookmark added" }), PickFolder: () => "C:\\Users\\you\\Videos\\Snag", + DownloadVoice: () => undefined, CopyClip: () => undefined, AIProviders: () => [ { id: "groq", label: "Groq", model: "qwen/qwen3.8-27b", transcribe: true, keyUrl: "https://console.groq.com/keys" }, diff --git a/internal/config/config.go b/internal/config/config.go index 88529e0..d9cc84f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -78,6 +78,12 @@ type Settings struct { AIAutoTitle bool `json:"aiAutoTitle"` AITranscribe bool `json:"aiTranscribe"` + VoiceTrigger bool `json:"voiceTrigger"` + VoicePhrase string `json:"voicePhrase"` + VoiceDir string `json:"voiceDir"` + // 0..100, how readily the keyword spotter fires + VoiceSensitivity int `json:"voiceSensitivity"` + LaunchOnStartup bool `json:"launchOnStartup"` StartMinimized bool `json:"startMinimized"` CloseToTray bool `json:"closeToTray"` @@ -108,6 +114,8 @@ func Defaults() Settings { Resolution: "native", Quality: "medium", DrawCursor: true, + VoicePhrase: DefaultVoicePhrase, + VoiceSensitivity: 50, BufferSeconds: 60, CaptureSystemAudio: true, CaptureMic: false, @@ -162,6 +170,13 @@ func (s *Settings) Normalize() { default: s.AIProvider = "" } + if s.VoiceSensitivity < 0 || s.VoiceSensitivity > 100 { + s.VoiceSensitivity = 50 + } + s.VoicePhrase = strings.TrimSpace(s.VoicePhrase) + if s.VoicePhrase == "" { + s.VoicePhrase = DefaultVoicePhrase + } switch s.AutoShrinkDays { case 0, 3, 7, 14, 30: default: @@ -295,6 +310,8 @@ func WriteFileAtomic(path string, data []byte) error { const DefaultTemplate = "{game} {date} {time}" +const DefaultVoicePhrase = "clip that" + // empty means clips\Exports func (s Settings) ExportsPath() string { if strings.TrimSpace(s.ExportsDir) != "" { @@ -351,3 +368,10 @@ func (s Settings) FFmpegInstallDir(dataDir string) string { } return filepath.Join(dataDir, "bin") } + +func (s Settings) VoiceInstallDir(dataDir string) string { + if strings.TrimSpace(s.VoiceDir) != "" { + return strings.TrimSpace(s.VoiceDir) + } + return filepath.Join(dataDir, "kws") +} diff --git a/internal/ffmpeg/download.go b/internal/ffmpeg/download.go index 4dcbecc..2d63485 100644 --- a/internal/ffmpeg/download.go +++ b/internal/ffmpeg/download.go @@ -18,6 +18,8 @@ import ( "sort" "strconv" "strings" + + "snag/internal/progress" ) const releaseAPI = "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/tags/latest" @@ -92,22 +94,7 @@ func pickAsset(assets []asset, below int) (asset, *asset, error) { return asset{}, nil, errors.New("no windows build found in release") } -type progressWriter struct { - done, total int64 - fn func(done, total int64) - last int64 -} - -func (p *progressWriter) Write(b []byte) (int, error) { - p.done += int64(len(b)) - if p.fn != nil && (p.done-p.last > 512<<10 || p.done == p.total) { - p.last = p.done - p.fn(p.done, p.total) - } - return len(b), nil -} - -func Download(ctx context.Context, installDir string, below int, progress func(done, total int64)) (Tools, error) { +func Download(ctx context.Context, installDir string, below int, onProgress func(done, total int64)) (Tools, error) { client := &http.Client{} req, _ := http.NewRequestWithContext(ctx, "GET", releaseAPI, nil) req.Header.Set("Accept", "application/vnd.github+json") @@ -163,7 +150,7 @@ func Download(ctx context.Context, installDir string, below int, progress func(d if total <= 0 { total = a.Size } - pw := &progressWriter{total: total, fn: progress} + pw := &progress.Writer{Total: total, Fn: onProgress} _, err = io.Copy(io.MultiWriter(f, h, pw), resp.Body) f.Close() if err != nil { diff --git a/internal/progress/progress.go b/internal/progress/progress.go new file mode 100644 index 0000000..e8a1746 --- /dev/null +++ b/internal/progress/progress.go @@ -0,0 +1,17 @@ +package progress + +type Writer struct { + Total int64 + Fn func(done, total int64) + done int64 + last int64 +} + +func (w *Writer) Write(b []byte) (int, error) { + w.done += int64(len(b)) + if w.Fn != nil && (w.done-w.last > 512<<10 || w.done == w.Total) { + w.last = w.done + w.Fn(w.done, w.Total) + } + return len(b), nil +} diff --git a/internal/recorder/recorder_windows.go b/internal/recorder/recorder_windows.go index 3a1d015..ca1d0fd 100644 --- a/internal/recorder/recorder_windows.go +++ b/internal/recorder/recorder_windows.go @@ -110,6 +110,12 @@ func (r *Recorder) notify() { } } +func (r *Recorder) State() State { + r.mu.Lock() + defer r.mu.Unlock() + return r.state +} + func (r *Recorder) Status() Status { secs, bytes := r.ring.Buffered() r.mu.Lock() diff --git a/internal/voice/download.go b/internal/voice/download.go new file mode 100644 index 0000000..6d2fc73 --- /dev/null +++ b/internal/voice/download.go @@ -0,0 +1,242 @@ +package voice + +import ( + "archive/tar" + "compress/bzip2" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "net/http" + "os" + "path" + "path/filepath" + "strings" + + "snag/internal/progress" +) + +// pinned: snag calls the c api with structs laid out for this exact version +const ( + kwsLibDLL = "sherpa-onnx-c-api.dll" + kwsLibURL = "https://github.com/k2-fsa/sherpa-onnx/releases/download/v2.0.1/sherpa-onnx-v2.0.1-win-x64-shared-MT-Release-no-tts-lib.tar.bz2" + kwsLibSHA = "21da6a8b92d63ca02ad41dbfc120012343aaaec2e5e02b14819c6b4f38004509" + kwsLibSize = 7655517 + kwsVerFile = "version.txt" + kwsVersion = "sherpa-onnx v2.0.1, kws-zipformer-gigaspeech-3.3M-2024-01-01" + + // not the -mobile export, its encoder fails a reshape under the onnxruntime this release ships + kwsModelURL = "https://github.com/k2-fsa/sherpa-onnx/releases/download/kws-models/sherpa-onnx-kws-zipformer-gigaspeech-3.3M-2024-01-01.tar.bz2" + kwsModelSHA = "f170013b4716e41b62b9bfd809687c207cef798ef9bc6534d524e17af9b6561a" + kwsModelSize = 17626723 +) + +var kwsDLLs = []string{"onnxruntime.dll", "onnxruntime_providers_shared.dll", kwsLibDLL} + +type Model struct { + Encoder, Decoder, Joiner, Tokens, Bpe string +} + +func modelOf(dir string) Model { + m := filepath.Join(dir, "model") + return Model{ + Encoder: filepath.Join(m, "encoder.onnx"), + Decoder: filepath.Join(m, "decoder.onnx"), + Joiner: filepath.Join(m, "joiner.onnx"), + Tokens: filepath.Join(m, "tokens.txt"), + Bpe: filepath.Join(m, "bpe.model"), + } +} + +func Find(dir string) (Model, error) { + m := modelOf(dir) + b, _ := os.ReadFile(filepath.Join(dir, kwsVerFile)) + if strings.TrimSpace(string(b)) != kwsVersion { + return m, errors.New("download the keyword spotter in Settings, Voice") + } + for _, p := range append([]string{m.Encoder, m.Decoder, m.Joiner, m.Tokens, m.Bpe}, filepath.Join(dir, kwsLibDLL)) { + if !exists(p) { + return m, errors.New("download the keyword spotter in Settings, Voice") + } + } + return m, nil +} + +func Download(ctx context.Context, dir string, onProgress func(done, total int64)) error { + if err := os.MkdirAll(filepath.Join(dir, "model"), 0o755); err != nil { + return err + } + client := &http.Client{} + pw := &progress.Writer{Total: kwsLibSize + kwsModelSize, Fn: onProgress} + get := func(url, sha string) (string, error) { + part := filepath.Join(dir, path.Base(url)+".part") + sum, err := fetch(ctx, client, url, part, pw) + if err != nil { + os.Remove(part) + return "", err + } + if !strings.EqualFold(sum, sha) { + os.Remove(part) + return "", errors.New("checksum mismatch, download was corrupted") + } + return part, nil + } + lib, err := get(kwsLibURL, kwsLibSHA) + if err != nil { + return err + } + defer os.Remove(lib) + model, err := get(kwsModelURL, kwsModelSHA) + if err != nil { + return err + } + defer os.Remove(model) + return installKWS(dir, lib, model) +} + +func installKWS(dir, lib, model string) error { + if err := os.MkdirAll(filepath.Join(dir, "model"), 0o755); err != nil { + return err + } + err := untar(lib, func(name string) string { + base := path.Base(name) + for _, d := range kwsDLLs { + if strings.EqualFold(base, d) && path.Base(path.Dir(name)) == "lib" { + return filepath.Join(dir, d) + } + } + return "" + }) + if err != nil { + return err + } + m := modelOf(dir) + // the int8 files are the light ones + pick := map[string]string{} + err = untar(model, func(name string) string { + base := path.Base(name) + switch base { + case "tokens.txt": + return m.Tokens + case "bpe.model": + return m.Bpe + } + for _, part := range []string{"encoder", "decoder", "joiner"} { + if !strings.HasPrefix(base, part+"-") || !strings.HasSuffix(base, ".onnx") { + continue + } + int8 := strings.HasSuffix(base, ".int8.onnx") + if prev, ok := pick[part]; ok && (strings.HasSuffix(prev, ".int8.onnx") || !int8) { + return "" + } + pick[part] = base + return filepath.Join(dir, "model", part+".onnx") + } + return "" + }) + if err != nil { + return err + } + for _, d := range kwsDLLs { + if !exists(filepath.Join(dir, d)) { + return fmt.Errorf("%s missing from the download", d) + } + } + for _, p := range []string{m.Encoder, m.Decoder, m.Joiner, m.Tokens, m.Bpe} { + if !exists(p) { + return fmt.Errorf("%s missing from the download", filepath.Base(p)) + } + } + return os.WriteFile(filepath.Join(dir, kwsVerFile), []byte(kwsVersion+"\n"), 0o644) +} + +// dest returns where an entry goes, empty skips it +func untar(file string, dest func(name string) string) error { + f, err := os.Open(file) + if err != nil { + return err + } + defer f.Close() + tr := tar.NewReader(bzip2.NewReader(f)) + for { + h, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + if h.Typeflag != tar.TypeReg { + continue + } + final := dest(h.Name) + if final == "" { + continue + } + if err := writeFile(tr, final); err != nil { + return err + } + } +} + +func writeFile(r io.Reader, final string) error { + tmp := final + ".part" + out, err := os.Create(tmp) + if err != nil { + return err + } + _, err = io.Copy(out, r) + if cerr := out.Close(); err == nil { + err = cerr + } + if err != nil { + os.Remove(tmp) + return err + } + // a loaded dll can't be overwritten but can be renamed + if exists(final) { + old := final + ".old" + os.Remove(old) + if os.Rename(final, old) == nil { + os.Remove(old) + } + } + return os.Rename(tmp, final) +} + +func exists(p string) bool { + _, err := os.Stat(p) + return err == nil +} + +// fetch writes the body to dst and returns its sha256 hex digest +func fetch(ctx context.Context, client *http.Client, url, dst string, pw *progress.Writer) (string, error) { + req, err := http.NewRequestWithContext(ctx, "GET", url, nil) + if err != nil { + return "", err + } + req.Header.Set("User-Agent", "snag") + resp, err := client.Do(req) + if err != nil { + return "", err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + return "", fmt.Errorf("download returned %s", resp.Status) + } + f, err := os.Create(dst) + if err != nil { + return "", err + } + h := sha256.New() + _, err = io.Copy(io.MultiWriter(f, h, pw), resp.Body) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + return "", err + } + return hex.EncodeToString(h.Sum(nil)), nil +} diff --git a/internal/voice/kws_other.go b/internal/voice/kws_other.go new file mode 100644 index 0000000..759c255 --- /dev/null +++ b/internal/voice/kws_other.go @@ -0,0 +1,22 @@ +//go:build !windows + +package voice + +import ( + "context" + "errors" +) + +type Spotter struct{} + +func NewSpotter(dir, phrase string, sensitivity float64) (*Spotter, error) { + return nil, errors.ErrUnsupported +} + +func (s *Spotter) Feed(samples []float32) string { return "" } +func (s *Spotter) Reset() {} +func (s *Spotter) Close() {} + +func Listen(ctx context.Context, o Options, onHeard func(phrase string)) error { + return errors.ErrUnsupported +} diff --git a/internal/voice/kws_windows.go b/internal/voice/kws_windows.go new file mode 100644 index 0000000..4776c56 --- /dev/null +++ b/internal/voice/kws_windows.go @@ -0,0 +1,281 @@ +//go:build windows + +package voice + +import ( + "context" + "errors" + "fmt" + "log/slog" + "path/filepath" + "runtime" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" + + "snag/internal/wasapi" +) + +// mirrors c-api.h of the pinned sherpa-onnx release, the layout changes between versions +type kwsFeatureConfig struct { + SampleRate int32 + FeatureDim int32 +} + +type kwsModelConfig struct { + Encoder, Decoder, Joiner *byte + ParaEncoder, ParaDecoder *byte + Zipformer2Ctc *byte + Tokens *byte + NumThreads int32 + Provider *byte + Debug int32 + ModelType *byte + ModelingUnit *byte + BpeVocab *byte + TokensBuf *byte + TokensBufSize int32 + NemoCtc *byte + TOneCtc *byte +} + +type kwsConfig struct { + Feat kwsFeatureConfig + Model kwsModelConfig + MaxActivePaths int32 + NumTrailingBlanks int32 + KeywordsScore float32 + KeywordsThreshold float32 + KeywordsFile *byte + KeywordsBuf *byte + KeywordsBufSize int32 +} + +type kwsResult struct { + Keyword *byte +} + +type kwsLib struct { + create, destroy, stream, destroyStream, accept, ready, decode, reset, result, freeResult *syscall.Proc +} + +var ( + kwsMu sync.Mutex + kwsLoaded *kwsLib + kwsLoadDir string +) + +const loadWithAlteredSearchPath = 0x8 + +var procLoadLibraryEx = syscall.NewLazyDLL("kernel32.dll").NewProc("LoadLibraryExW") + +func loadLibraryEx(path string) (syscall.Handle, error) { + p, err := syscall.UTF16PtrFromString(path) + if err != nil { + return 0, err + } + h, _, err := procLoadLibraryEx.Call(uintptr(unsafe.Pointer(p)), 0, loadWithAlteredSearchPath) + if h == 0 { + return 0, err + } + return syscall.Handle(h), nil +} + +// onnxruntime.dll also ships with windows, load ours from the install folder before anything else does +func loadKWS(dir string) (*kwsLib, error) { + dir = filepath.Clean(dir) + kwsMu.Lock() + defer kwsMu.Unlock() + if kwsLoaded != nil { + if strings.EqualFold(kwsLoadDir, dir) { + return kwsLoaded, nil + } + return nil, errors.New("restart snag to use a different voice folder") + } + if _, err := loadLibraryEx(filepath.Join(dir, "onnxruntime.dll")); err != nil { + return nil, fmt.Errorf("can't load onnxruntime.dll: %w", err) + } + h, err := loadLibraryEx(filepath.Join(dir, kwsLibDLL)) + if err != nil { + return nil, fmt.Errorf("can't load %s: %w", kwsLibDLL, err) + } + dll := &syscall.DLL{Name: kwsLibDLL, Handle: h} + l := &kwsLib{} + for _, p := range []struct { + dst **syscall.Proc + name string + }{ + {&l.create, "SherpaOnnxCreateKeywordSpotter"}, + {&l.destroy, "SherpaOnnxDestroyKeywordSpotter"}, + {&l.stream, "SherpaOnnxCreateKeywordStream"}, + {&l.destroyStream, "SherpaOnnxDestroyOnlineStream"}, + {&l.accept, "SherpaOnnxOnlineStreamAcceptWaveform"}, + {&l.ready, "SherpaOnnxIsKeywordStreamReady"}, + {&l.decode, "SherpaOnnxDecodeKeywordStream"}, + {&l.reset, "SherpaOnnxResetKeywordStream"}, + {&l.result, "SherpaOnnxGetKeywordResult"}, + {&l.freeResult, "SherpaOnnxDestroyKeywordResult"}, + } { + proc, err := dll.FindProc(p.name) + if err != nil { + return nil, fmt.Errorf("%s is missing %s (download it again): %w", kwsLibDLL, p.name, err) + } + *p.dst = proc + } + kwsLoaded, kwsLoadDir = l, dir + return l, nil +} + +func cstr(s string) *byte { + b, _ := syscall.BytePtrFromString(s) + return b +} + +func gostr(p *byte) string { + if p == nil { + return "" + } + n := 0 + for *(*byte)(unsafe.Add(unsafe.Pointer(p), n)) != 0 { + n++ + } + return string(unsafe.Slice(p, n)) +} + +type Spotter struct { + lib *kwsLib + h, st uintptr + closed bool +} + +// sensitivity 0..1, higher fires on less certain matches +func NewSpotter(dir, phrase string, sensitivity float64) (*Spotter, error) { + m, err := Find(dir) + if err != nil { + return nil, err + } + keywords, err := KeywordLine(m.Bpe, phrase, sensitivity) + if err != nil { + return nil, err + } + lib, err := loadKWS(dir) + if err != nil { + return nil, err + } + kw := cstr(keywords) + cfg := &kwsConfig{ + Feat: kwsFeatureConfig{SampleRate: vrate, FeatureDim: 80}, + Model: kwsModelConfig{ + Encoder: cstr(m.Encoder), Decoder: cstr(m.Decoder), Joiner: cstr(m.Joiner), + Tokens: cstr(m.Tokens), NumThreads: 1, Provider: cstr("cpu"), + }, + MaxActivePaths: 4, + NumTrailingBlanks: 1, + KeywordsScore: 1.0, + KeywordsThreshold: 0.25, + KeywordsBuf: kw, + KeywordsBufSize: int32(len(keywords)), + } + h, _, _ := lib.create.Call(uintptr(unsafe.Pointer(cfg))) + runtime.KeepAlive(cfg) + if h == 0 { + return nil, errors.New("keyword spotter failed to start, download it again") + } + st, _, _ := lib.stream.Call(h) + if st == 0 { + lib.destroy.Call(h) + return nil, errors.New("keyword spotter failed to start") + } + return &Spotter{lib: lib, h: h, st: st}, nil +} + +// 16 kHz mono samples in, the keyword out when it was just heard +func (s *Spotter) Feed(samples []float32) string { + if len(samples) == 0 || s.closed { + return "" + } + s.lib.accept.Call(s.st, vrate, uintptr(unsafe.Pointer(&samples[0])), uintptr(len(samples))) + runtime.KeepAlive(samples) + heard := "" + for { + r, _, _ := s.lib.ready.Call(s.h, s.st) + if int32(r) == 0 { + break + } + s.lib.decode.Call(s.h, s.st) + res, _, _ := s.lib.result.Call(s.h, s.st) + if res == 0 { + continue + } + if k := gostr((*kwsResult)(unsafe.Add(nil, res)).Keyword); k != "" { + heard = k + // a match has to be reset or it fires again + s.Reset() + } + s.lib.freeResult.Call(res) + } + return heard +} + +func (s *Spotter) Reset() { + if !s.closed { + s.lib.reset.Call(s.h, s.st) + } +} + +func (s *Spotter) Close() { + if s.closed { + return + } + s.closed = true + s.lib.destroyStream.Call(s.st) + s.lib.destroy.Call(s.h) +} + +// streams the mic into the spotter, no audio leaves the pc and there's no per-utterance decode +func Listen(ctx context.Context, o Options, onHeard func(phrase string)) error { + sp, err := NewSpotter(o.Dir, o.Phrase, o.Sensitivity) + if err != nil { + return err + } + defer sp.Close() + chunks := make(chan []byte, 400) + var dropped atomic.Int64 + c, err := wasapi.Open(ctx, o.Mic, false, func(b []byte) { + select { + case chunks <- b: + default: + dropped.Add(1) + } + }) + if err != nil { + return err + } + conv, err := newResampler(c.Format.SampleFmt, c.Format.SampleRate, c.Format.Channels) + if err != nil { + return err + } + c.Start() + var lastHeard, lastDropLog time.Time + for { + select { + case <-ctx.Done(): + return nil + case b := <-chunks: + if dropped.Load() > 0 && time.Since(lastDropLog) >= 5*time.Second { + if n := dropped.Swap(0); n > 0 { + slog.Warn("voice audio dropped", "chunks", n) + lastDropLog = time.Now() + } + } + pcm := conv.Write(b) + if k := sp.Feed(pcm); k != "" && time.Since(lastHeard) >= 3*time.Second { + lastHeard = time.Now() + onHeard(k) + } + } + } +} diff --git a/internal/voice/kws_windows_test.go b/internal/voice/kws_windows_test.go new file mode 100644 index 0000000..522c3f4 --- /dev/null +++ b/internal/voice/kws_windows_test.go @@ -0,0 +1,108 @@ +//go:build windows + +package voice + +import ( + "bytes" + "cmp" + "encoding/binary" + "os" + "path/filepath" + "strings" + "testing" +) + +func wavSamples(t *testing.T, file string) []float32 { + b, err := os.ReadFile(file) + if err != nil { + t.Fatal(err) + } + i := bytes.Index(b, []byte("data")) + if i < 0 { + t.Fatal("no data chunk") + } + pcm := b[i+8:] + out := make([]float32, len(pcm)/2) + for j := range out { + out[j] = float32(int16(binary.LittleEndian.Uint16(pcm[j*2:]))) / 32768 + } + // trailing silence so the last word gets decoded + return append(out, make([]float32, vrate)...) +} + +// SNAG_KWS_TEST=dir with the two release archives and a wav folder of hit*.wav and miss*.wav, 16 kHz mono +func TestSpotterHears(t *testing.T) { + src := os.Getenv("SNAG_KWS_TEST") + if src == "" { + t.Skip("SNAG_KWS_TEST not set") + } + dir := os.Getenv("SNAG_KWS_DIR") + var err error + if dir == "" { + // not t.TempDir, the loaded dlls can't be deleted until the process exits + dir, _ = os.MkdirTemp("", "snag-kws-*") + err = installKWS(dir, filepath.Join(src, filepath.Base(kwsLibURL)), filepath.Join(src, filepath.Base(kwsModelURL))) + } + if err != nil { + t.Fatal(err) + } + wavs, _ := filepath.Glob(filepath.Join(cmp.Or(os.Getenv("SNAG_KWS_WAVS"), filepath.Join(src, "wav")), "*.wav")) + for _, w := range wavs { + sp, err := NewSpotter(dir, cmp.Or(os.Getenv("SNAG_KWS_PHRASE"), "clip that"), 0.5) + if err != nil { + t.Fatal(err) + } + heard := "" + s := wavSamples(t, w) + for i := 0; i < len(s); i += 1600 { + if k := sp.Feed(s[i:min(i+1600, len(s))]); k != "" { + heard = k + } + } + sp.Close() + name := filepath.Base(w) + want := name[:3] == "hit" + t.Logf("%s: %q", name, heard) + if (heard != "") != want { + t.Errorf("%s: heard %q", name, heard) + } + } +} + +func TestSplitMatchesModelKeywords(t *testing.T) { + src := os.Getenv("SNAG_KWS_TEST") + if src == "" { + t.Skip("SNAG_KWS_TEST not set") + } + dir := t.TempDir() + if err := installKWS(dir, filepath.Join(src, filepath.Base(kwsLibURL)), filepath.Join(src, filepath.Base(kwsModelURL))); err != nil { + t.Fatal(err) + } + scores, err := loadPieces(modelOf(dir).Bpe) + if err != nil { + t.Fatal(err) + } + // from the model's own keywords.txt and test_keywords.txt + for phrase, want := range map[string]string{ + "HELLO WORLD": "▁HE LL O ▁WORLD", + "HI GOOGLE": "▁HI ▁GO O G LE", + "HEY SIRI": "▁HE Y ▁S I RI", + "ALEXA": "▁A LE X A", + "LOVE AND PEACE": "▁LOVE ▁AND ▁P E A CE", + "PLAY MUSIC": "▁PLAY ▁MU S IC", + "GO HOME": "▁GO ▁HOME", + "HAPPY NEW YEAR": "▁HA PP Y ▁NEW ▁YEAR", + "MERRY CHRISTMAS": "▁ME R RY ▁ CH R IST MA S", + "LIGHT UP": "▁ L IGHT ▁UP", + "LOVELY CHILD": "▁LOVE LY ▁CHI L D", + "FOREVER": "▁FOR E VER", + } { + got, _, err := spmEncode(scores, phrase) + if err != nil { + t.Fatal(err) + } + if g := strings.Join(got, " "); g != want { + t.Errorf("%s: got %q, want %q", phrase, g, want) + } + } +} diff --git a/internal/voice/resample.go b/internal/voice/resample.go new file mode 100644 index 0000000..8ec5d86 --- /dev/null +++ b/internal/voice/resample.go @@ -0,0 +1,148 @@ +package voice + +import ( + "encoding/binary" + "fmt" + "math" +) + +const vrate = 16000 + +type sampleFormat int + +const ( + fmtS16LE sampleFormat = iota + 1 + fmtS24LE + fmtS32LE + fmtF32LE +) + +func parseSampleFormat(s string) (sampleFormat, int, error) { + switch s { + case "s16le": + return fmtS16LE, 2, nil + case "s24le": + return fmtS24LE, 3, nil + case "s32le": + return fmtS32LE, 4, nil + case "f32le": + return fmtF32LE, 4, nil + default: + return 0, 0, fmt.Errorf("unsupported audio format %q", s) + } +} + +// turns wasapi frames into mono 16 kHz float samples for the spotter +type resampler struct { + fmt sampleFormat + bps int + ch int + step float64 + fir []float64 + raw []byte + in []float64 + filt []float64 + out []float32 + pos float64 +} + +func newResampler(sampleFmt string, rate, channels int) (*resampler, error) { + sf, bps, err := parseSampleFormat(sampleFmt) + if err != nil { + return nil, err + } + if rate <= 0 { + rate = vrate + } + if channels <= 0 { + channels = 1 + } + step := float64(rate) / vrate + r := &resampler{fmt: sf, bps: bps, ch: channels, step: step} + if step > 1 { + // low-pass before decimating so energy above 8 kHz doesn't fold into speech + r.fir = lowpassFIR(31, 0.45/step) + } + return r, nil +} + +func lowpassFIR(taps int, fc float64) []float64 { + h := make([]float64, taps) + mid := taps / 2 + var sum float64 + for i := range h { + n := float64(i - mid) + var v float64 + if i == mid { + v = 2 * fc + } else { + v = math.Sin(2*math.Pi*fc*n) / (math.Pi * n) + } + // hamming window + w := 0.54 - 0.46*math.Cos(2*math.Pi*float64(i)/float64(taps-1)) + h[i] = v * w + sum += h[i] + } + for i := range h { + h[i] /= sum + } + return h +} + +// Write returns resampled 16 kHz mono samples; the returned slice is valid until the next Write. +func (r *resampler) Write(b []byte) []float32 { + r.raw = append(r.raw, b...) + fs := r.bps * r.ch + n := len(r.raw) / fs * fs + for i := 0; i < n; i += fs { + var sum float64 + for c := 0; c < r.ch; c++ { + sum += r.sample(r.raw[i+c*r.bps:]) + } + s := sum / float64(r.ch) + if len(r.fir) > 0 { + r.in = append(r.in, s) + } else { + r.filt = append(r.filt, s) + } + } + r.raw = append(r.raw[:0], r.raw[n:]...) + + if taps := len(r.fir); taps > 0 && len(r.in) >= taps { + avail := len(r.in) - taps + 1 + for i := 0; i < avail; i++ { + var acc float64 + for j, w := range r.fir { + acc += r.in[i+j] * w + } + r.filt = append(r.filt, acc) + } + r.in = append(r.in[:0], r.in[avail:]...) + } + + r.out = r.out[:0] + for r.pos+1 < float64(len(r.filt)) { + i := int(r.pos) + f := r.pos - float64(i) + r.out = append(r.out, float32(max(-1, min(1, r.filt[i]*(1-f)+r.filt[i+1]*f)))) + r.pos += r.step + } + k := min(int(r.pos), len(r.filt)) + r.filt = append(r.filt[:0], r.filt[k:]...) + r.pos -= float64(k) + return r.out +} + +func (r *resampler) sample(b []byte) float64 { + switch r.fmt { + case fmtF32LE: + return float64(math.Float32frombits(binary.LittleEndian.Uint32(b))) + case fmtS24LE: + u := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 + return float64(int32(u<<8)>>8) / 8388608 + case fmtS32LE: + return float64(int32(binary.LittleEndian.Uint32(b))) / 2147483648 + default: + return float64(int16(binary.LittleEndian.Uint16(b))) / 32768 + } +} diff --git a/internal/voice/resample_test.go b/internal/voice/resample_test.go new file mode 100644 index 0000000..339d6d1 --- /dev/null +++ b/internal/voice/resample_test.go @@ -0,0 +1,36 @@ +package voice + +import ( + "encoding/binary" + "math" + "testing" +) + +func TestResampler(t *testing.T) { + var b []byte + for i := 0; i < 48000; i++ { + v := uint16(int16(16000 * math.Sin(2*math.Pi*440*float64(i)/48000))) + b = binary.LittleEndian.AppendUint16(b, v) + b = binary.LittleEndian.AppendUint16(b, v) + } + r, err := newResampler("s16le", 48000, 2) + if err != nil { + t.Fatal(err) + } + + var out []float32 + for off := 0; off < len(b); off += 1922 { + out = append(out, r.Write(b[off:min(off+1922, len(b))])...) + } + + if n := len(out); n < 15980 || n > 16000 { + t.Fatalf("got %d samples from 1 s at 48 kHz, want about 16000", n) + } + var peak float32 + for _, v := range out { + peak = max(peak, v) + } + if want := float32(16000) / 32768; math.Abs(float64(peak-want)) > 0.01 { + t.Errorf("peak %v, want about %v", peak, want) + } +} diff --git a/internal/voice/spm.go b/internal/voice/spm.go new file mode 100644 index 0000000..2cef77e --- /dev/null +++ b/internal/voice/spm.go @@ -0,0 +1,173 @@ +package voice + +import ( + "encoding/binary" + "errors" + "fmt" + "math" + "os" + "slices" + "strings" + "unicode" + "unicode/utf8" +) + +// sherpa-onnx wants keywords already split into the model's pieces, its own splitter is python only +func KeywordLine(spmPath, phrase string, sensitivity float64) (string, error) { + scores, err := loadPieces(spmPath) + if err != nil { + return "", err + } + pieces, words, err := spmEncode(scores, phrase) + if err != nil { + return "", err + } + sensitivity = min(max(sensitivity, 0), 1) + return fmt.Sprintf("%s #%.2f @%s", strings.Join(pieces, " "), 0.45-0.4*sensitivity, strings.Join(words, "_")), nil +} + +// reads the normal pieces and their scores out of a sentencepiece model file, a protobuf +// ModelProto with repeated pieces = 1 { piece = 1, score = 2, type = 3 } +func loadPieces(path string) (map[string]float32, error) { + b, err := os.ReadFile(path) + if err != nil { + return nil, err + } + bad := errors.New("the keyword spotter's bpe.model is damaged, download it again") + scores := map[string]float32{} + for len(b) > 0 { + num, typ, n := protowire(b) + if n <= 0 { + return nil, bad + } + b = b[n:] + val, n := protoSkip(b, typ) + if n < 0 { + return nil, bad + } + b = b[n:] + if num != 1 || typ != 2 { + continue + } + var piece string + var score float32 + kind := uint64(1) + for len(val) > 0 { + fnum, ftyp, n := protowire(val) + if n <= 0 { + return nil, bad + } + val = val[n:] + fval, n := protoSkip(val, ftyp) + if n < 0 { + return nil, bad + } + switch { + case fnum == 1 && ftyp == 2: + piece = string(fval) + case fnum == 2 && ftyp == 5: + score = math.Float32frombits(binary.LittleEndian.Uint32(fval)) + case fnum == 3 && ftyp == 0: + kind, _ = binary.Uvarint(fval) + } + val = val[n:] + } + if kind == 1 && piece != "" { + scores[piece] = score + } + } + if len(scores) == 0 { + return nil, bad + } + return scores, nil +} + +func protowire(b []byte) (num, typ uint64, n int) { + k, n := binary.Uvarint(b) + return k >> 3, k & 7, n +} + +// returns the field's value bytes and how much of b the value took +func protoSkip(b []byte, typ uint64) ([]byte, int) { + switch typ { + case 0: + _, n := binary.Uvarint(b) + if n <= 0 { + return nil, -1 + } + return b[:n], n + case 1: + if len(b) < 8 { + return nil, -1 + } + return b[:8], 8 + case 2: + l, n := binary.Uvarint(b) + if n <= 0 || uint64(len(b)-n) < l { + return nil, -1 + } + return b[n : n+int(l)], n + int(l) + case 5: + if len(b) < 4 { + return nil, -1 + } + return b[:4], 4 + } + return nil, -1 +} + +const wordStart = "▁" + +// sentencepiece unigram: the split of each word whose pieces have the best total score +func spmEncode(scores map[string]float32, phrase string) ([]string, []string, error) { + var words []string + for _, raw := range strings.Fields(strings.ToUpper(phrase)) { + var b strings.Builder + for _, r := range raw { + if (r >= 'A' && r <= 'Z') || r == '\'' { + b.WriteRune(r) + } else if unicode.IsLetter(r) { + return nil, nil, errors.New("the phrase needs English words") + } + } + if b.Len() > 0 { + words = append(words, b.String()) + } + } + if len(words) == 0 { + return nil, nil, errors.New("the phrase needs English words") + } + maxLen := 0 + for p := range scores { + maxLen = max(maxLen, len(p)) + } + var out []string + for _, w := range words { + s := wordStart + w + best := make([]float64, len(s)+1) + from := make([]int, len(s)+1) + for i := 1; i <= len(s); i++ { + best[i] = math.Inf(-1) + } + for i := 0; i < len(s); i++ { + if math.IsInf(best[i], -1) || !utf8.RuneStart(s[i]) { + continue + } + for j := i + 1; j <= min(len(s), i+maxLen); j++ { + if sc, ok := scores[s[i:j]]; ok && best[i]+float64(sc) > best[j] { + best[j], from[j] = best[i]+float64(sc), i + } + } + } + if math.IsInf(best[len(s)], -1) { + return nil, nil, fmt.Errorf("the model can't spell %q", w) + } + var parts []string + for j := len(s); j > 0; j = from[j] { + parts = append(parts, s[from[j]:j]) + } + slices.Reverse(parts) + out = append(out, parts...) + } + return out, words, nil +} diff --git a/internal/voice/voice.go b/internal/voice/voice.go new file mode 100644 index 0000000..539e267 --- /dev/null +++ b/internal/voice/voice.go @@ -0,0 +1,8 @@ +package voice + +type Options struct { + Mic string + Dir string + Phrase string + Sensitivity float64 +} diff --git a/service.go b/service.go index d29aec2..c28a32c 100644 --- a/service.go +++ b/service.go @@ -130,6 +130,8 @@ func (s *SnagService) AddBookmark() { s.c.addMark() } func (s *SnagService) DownloadFFmpeg() error { return s.c.download() } +func (s *SnagService) DownloadVoice() error { return s.c.downloadVoice() } + func (s *SnagService) ReprobeEncoders() []ffmpeg.Encoder { s.c.probeTools(true) return s.c.Encoders() diff --git a/voice.go b/voice.go new file mode 100644 index 0000000..a13c25a --- /dev/null +++ b/voice.go @@ -0,0 +1,118 @@ +package main + +import ( + "context" + "log/slog" + "strconv" + "strings" + "sync" + + "snag/internal/config" + "snag/internal/recorder" + "snag/internal/voice" +) + +type voiceState struct { + mu sync.Mutex + stop context.CancelFunc + key string + err string + dir string + ready bool + dl downloadState +} + +type voiceStatus struct { + Ready bool `json:"ready"` + Dir string `json:"dir"` + Error string `json:"error"` + Download downloadState `json:"download"` +} + +func (c *Core) refreshVoiceReady() { + dir := c.store.Get().VoiceInstallDir(c.dataDir) + _, err := voice.Find(dir) + c.voice.mu.Lock() + c.voice.dir = dir + c.voice.ready = err == nil + c.voice.mu.Unlock() +} + +func (c *Core) voiceStatus() voiceStatus { + c.voice.mu.Lock() + defer c.voice.mu.Unlock() + return voiceStatus{ + Ready: c.voice.ready, + Dir: c.voice.dir, + Error: c.voice.err, + Download: c.voice.dl, + } +} + +func (c *Core) downloadVoice() error { + err := c.runDownload(&c.voice.mu, &c.voice.dl, func(progress func(done, total int64)) error { + return voice.Download(c.ctx, c.store.Get().VoiceInstallDir(c.dataDir), progress) + }) + if err != nil { + return err + } + c.refreshVoiceReady() + c.toast("success", "Keyword spotter is ready") + c.syncVoice() + c.pushStatus() + return nil +} + +func voiceKeyOf(s config.Settings, dir string, ready, buffering bool) string { + if !s.VoiceTrigger || !ready || !buffering { + return "" + } + return strings.Join([]string{s.VoicePhrase, s.MicDeviceID, dir, strconv.Itoa(s.VoiceSensitivity)}, "\x00") +} + +func (c *Core) syncVoice() { + s := c.store.Get() + buffering := c.rec.State() == recorder.Buffering + c.voice.mu.Lock() + defer c.voice.mu.Unlock() + k := voiceKeyOf(s, c.voice.dir, c.voice.ready, buffering) + if k == c.voice.key { + return + } + if c.voice.stop != nil { + c.voice.stop() + c.voice.stop = nil + } + c.voice.key = k + c.voice.err = "" + if k == "" { + return + } + ctx, cancel := context.WithCancel(c.ctx) + c.voice.stop = cancel + dir := c.voice.dir + go c.runVoice(ctx, k, dir, s) +} + +func (c *Core) runVoice(ctx context.Context, key, dir string, s config.Settings) { + heard := func(phrase string) { + slog.Info("voice trigger", "heard", phrase) + go c.saveFull() + } + + err := voice.Listen(ctx, voice.Options{ + Mic: s.MicDeviceID, + Dir: dir, + Phrase: s.VoicePhrase, + Sensitivity: float64(s.VoiceSensitivity) / 100, + }, heard) + if err != nil && ctx.Err() == nil { + c.voice.mu.Lock() + if c.voice.key == key { + c.voice.err = err.Error() + } + c.voice.mu.Unlock() + c.toast("error", "Voice trigger: "+err.Error()) + c.pushStatus() + } +}