Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 49 additions & 23 deletions core.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ type Core struct {
features ffmpeg.Features
hotkeyErrs []string
dl downloadState
voice voiceState
aiQueue chan string
upd updater
ctx context.Context
Expand Down Expand Up @@ -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{
Expand Down Expand Up @@ -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"`
}
Expand All @@ -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" {
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
}

Expand Down Expand Up @@ -484,46 +496,60 @@ 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()) {
c.toast("error", "No FFmpeg build works with this NVIDIA driver yet, capture stays on the CPU until you update it")
}
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
Expand Down
3 changes: 3 additions & 0 deletions frontend/src/features/settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down Expand Up @@ -70,6 +72,7 @@ export function Settings() {
<ClipsSection s={s} set={set} est={est} />
<AudioSection s={s} set={set} />
<HotkeysSection s={s} set={set} />
<VoiceSection s={s} set={set} />
<StorageSection s={s} set={set} />
<SharingSection s={s} set={set} />
<AISection s={s} set={set} />
Expand Down
32 changes: 31 additions & 1 deletion frontend/src/features/settings/parts.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -13,3 +14,32 @@ export function Section({ id, title, children }: { id: string; title: string; ch
</section>
);
}

export function DraftInput({
value,
onCommit,
allowEmpty = false,
...rest
}: {
value: string;
onCommit: (v: string) => void;
allowEmpty?: boolean;
} & Omit<InputHTMLAttributes<HTMLInputElement>, "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 (
<Input
spellCheck={false}
{...rest}
value={draft}
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => e.key === "Enter" && commit()}
/>
);
}
16 changes: 5 additions & 11 deletions frontend/src/features/settings/sections/Sharing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Uploader[]>([]);
Expand Down Expand Up @@ -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 (
<Row
title="Catbox account"
Expand All @@ -134,15 +130,13 @@ function UserhashRow({ value, onSave }: { value: string; onSave: (v: string) =>
</>
}
>
<Input
<DraftInput
type="password"
value={v}
value={value}
allowEmpty
placeholder="Anonymous"
onChange={(e) => setV(e.target.value)}
onBlur={commit}
onKeyDown={(e) => e.key === "Enter" && commit()}
onCommit={onSave}
className="w-[240px]"
spellCheck={false}
autoComplete="off"
/>
</Row>
Expand Down
110 changes: 110 additions & 0 deletions frontend/src/features/settings/sections/Voice.tsx
Original file line number Diff line number Diff line change
@@ -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 (
<Section id="voice" title="Voice">
<p className="mb-1 mt-1 text-xs text-muted">
Say a phrase to save a clip. Only listens while capturing. Uses the mic
from Audio.
</p>
<Row
title="Voice trigger"
desc="Listens only for the phrase, light on the CPU"
>
<Switch
checked={s.voiceTrigger}
onCheckedChange={(v) => set({ voiceTrigger: v })}
/>
</Row>
{s.voiceTrigger && (
<>
<Row title="Phrase" desc="English words, saves a full-length clip">
<DraftInput
value={s.voicePhrase}
onCommit={(v) => set({ voicePhrase: v })}
className="w-[320px]"
/>
</Row>
<Row
title="Sensitivity"
desc="Higher catches mumbled phrases, lower avoids false saves"
>
<div className="flex w-[320px] items-center gap-3">
<Slider
min={0}
max={100}
step={5}
value={[sens]}
onValueChange={([v]) => setSens(v)}
onValueCommit={([v]) => set({ voiceSensitivity: v })}
/>
<span className="w-8 text-right text-xs tabular-nums text-muted">
{sens}
</span>
</div>
</Row>
<Row
title={
voice?.ready
? "Keyword spotter ready"
: "Keyword spotter not installed"
}
desc="sherpa-onnx with a small English model, about a 25 MB download"
>
<Button
onClick={() =>
api
.downloadVoice()
.catch((e) => useStore.getState().toast("error", String(e)))
}
disabled={dl?.active}
>
{dlLabel}
</Button>
</Row>
<Row
title="Install folder"
desc={<span className="break-all">{voice?.dir}</span>}
>
<div className="flex gap-2">
{s.voiceDir && (
<Button variant="ghost" onClick={() => set({ voiceDir: "" })}>
Reset
</Button>
)}
<Button
onClick={async () => {
const p = await api.pickFolder(s.voiceDir || "");
if (p) set({ voiceDir: p });
}}
>
Change
</Button>
</div>
</Row>
{voice?.error && <p className="text-2xs text-bad">{voice.error}</p>}
{dl?.error && !dl.active && (
<p className="text-2xs text-bad">{dl.error}</p>
)}
<p className="mt-3 text-2xs leading-relaxed text-faint">
Runs on your PC, nothing is sent anywhere.
</p>
</>
)}
</Section>
);
}
10 changes: 9 additions & 1 deletion frontend/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
};
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -255,6 +262,7 @@ export const api = {
pickSoundFile: () => call<string>("PickSoundFile"),
addBookmark: () => call<void>("AddBookmark"),
downloadFFmpeg: () => call<void>("DownloadFFmpeg"),
downloadVoice: () => call<void>("DownloadVoice"),
reprobe: () => call<Encoder[]>("ReprobeEncoders"),
audioDevices: () => call<{ outputs: AudioDevice[]; inputs: AudioDevice[] }>("ListAudioDevices"),
monitors: () => call<Monitor[]>("ListMonitors"),
Expand Down
Loading