package tts import ( "crypto/sha256" "encoding/hex" "fmt" "math" "os" "path/filepath" "sort" "sync" ) type Cache struct { dir string mu sync.Mutex maxBytes int64 } func NewCache(dir string) (*Cache, error) { if err := os.MkdirAll(dir, 0o755); err != nil { return nil, fmt.Errorf("create cache dir: %w", err) } c := &Cache{dir: dir, maxBytes: 256 << 20} if err := c.prune(0); err != nil { return nil, err } return c, nil } // Key covers everything that changes the rendered audio, including the voice // pack version, so upgrades invalidate old files on their own. func (c *Cache) Key(version, voice string, speed, pitch float32, text string) string { sum := sha256.Sum256([]byte(fmt.Sprintf("dsp-v2\x00%s\x00%s\x00%08x\x00%08x\x00%s", version, voice, math.Float32bits(speed), math.Float32bits(pitch), text))) return hex.EncodeToString(sum[:]) } func (c *Cache) Get(key string) ([]byte, bool) { data, err := os.ReadFile(filepath.Join(c.dir, key+".wav")) if err != nil { return nil, false } return data, true } func (c *Cache) Put(key string, data []byte) error { c.mu.Lock() defer c.mu.Unlock() if int64(len(data)) > c.maxBytes { return fmt.Errorf("audio exceeds cache budget") } if err := c.prune(int64(len(data))); err != nil { return err } tmp, err := os.CreateTemp(c.dir, key[:8]+"-*.tmp") if err != nil { return err } name := tmp.Name() defer os.Remove(name) if _, err := tmp.Write(data); err != nil { tmp.Close() os.Remove(name) return err } if err := tmp.Close(); err != nil { os.Remove(name) return err } return os.Rename(name, filepath.Join(c.dir, key+".wav")) } func (c *Cache) Open(key string) (*os.File, error) { return os.Open(filepath.Join(c.dir, key+".wav")) } func (c *Cache) prune(incoming int64) error { entries, err := os.ReadDir(c.dir) if err != nil { return err } var files []os.FileInfo var total int64 for _, entry := range entries { if entry.IsDir() || filepath.Ext(entry.Name()) != ".wav" { continue } info, err := entry.Info() if err != nil { return err } total += info.Size() files = append(files, info) } sort.Slice(files, func(i, j int) bool { return files[i].ModTime().Before(files[j].ModTime()) }) for _, file := range files { if total+incoming <= c.maxBytes { break } if err := os.Remove(filepath.Join(c.dir, file.Name())); err != nil { return err } total -= file.Size() } return nil }