Files
MichilisandClaude Fable 5.2 9c9d641eda Phase 3: cache
Repeat downloads are instant, and the cache never bypasses a limit.

- internal/cache: canonical key (extractor + video id + profile, URL hash
  fallback), per-bot file_id layer, stored copy layer, metadata layer,
  TTL by source type, LRU-plus-hits eviction that keeps file_ids, orphan
  sweeper, takedown that deletes, invalidates and blocks
- One admission gate: a cache hit passes the same size, duration, quota,
  volume, active job and queue checks as a fresh download, is judged by
  the real cached file, and costs the same. It only skips the worker
- Singleflight: a second requester joins the job that is queued or running
  for the same result. Each keeps their own caps, checked at delivery
- Derive: lower profiles and audio are transcoded from a stored copy with
  ffmpeg; a higher profile that already fits is served as an alias; a
  failed derive falls back to a download
- Self-healing: a rejected file_id falls back to the stored copy, then to
  a fresh download, and the entry is updated either way
- Private or login-gated content and live streams are never cached
- Playlists as per-item jobs started in turn, /subs, /history with resend,
  /fresh, owner /purge and /cache
- Worker removes its temp files right after the upload

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-18 08:38:38 +00:00

127 lines
4.0 KiB
Go

// Package ffmpeg makes lower profiles and audio from a stored file, so a
// video that is already in the cache does not have to be downloaded again.
package ffmpeg
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/links"
"github.com/noderunners/dlbot/internal/media"
"github.com/noderunners/dlbot/internal/ytdlp"
)
// Transcoder derives one profile from a source file.
type Transcoder interface {
// Derive writes the profile made from src into dir and describes it.
// Failures are returned as *ytdlp.Error.
Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error)
}
// Exec runs the real ffmpeg.
type Exec struct {
// Path of the ffmpeg binary. Defaults to "ffmpeg". ffprobe is expected
// next to it.
Path string
// Timeout bounds one transcode. Defaults to 30 minutes.
Timeout time.Duration
}
var _ Transcoder = (*Exec)(nil)
func (e *Exec) bin() string {
if e.Path == "" {
return "ffmpeg"
}
return e.Path
}
func (e *Exec) probeBin() string {
if e.Path == "" || e.Path == "ffmpeg" {
return "ffprobe"
}
return filepath.Join(filepath.Dir(e.Path), "ffprobe")
}
// Args returns the ffmpeg arguments for a profile and the output file
// name. It is exported for tests and the operations docs.
func Args(src, dir string, profile media.Profile) (args []string, out string, err error) {
base := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", src}
switch {
case profile == media.MP3:
out = filepath.Join(dir, "media.mp3")
return append(base, "-vn", "-c:a", "libmp3lame", "-b:a", "192k", out), out, nil
case profile == media.M4A:
out = filepath.Join(dir, "media.m4a")
return append(base, "-vn", "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", out), out, nil
case profile.Height() > 0:
out = filepath.Join(dir, "media.mp4")
// Scale to the target height, keep the aspect ratio, and keep the
// width even, which h264 requires.
scale := "scale=-2:" + strconv.Itoa(profile.Height())
return append(base, "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
"-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", out), out, nil
}
return nil, "", fmt.Errorf("ffmpeg: profile %q cannot be derived", profile)
}
// Derive implements Transcoder.
func (e *Exec) Derive(ctx context.Context, src, dir string, profile media.Profile) (*ytdlp.Result, error) {
timeout := e.Timeout
if timeout <= 0 {
timeout = 30 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := os.MkdirAll(dir, 0o750); err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeInternal, Retryable: true, Raw: err.Error()}
}
args, out, err := Args(src, dir, profile)
if err != nil {
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: err.Error()}
}
cmd := exec.CommandContext(ctx, e.bin(), args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
if cmd.Process == nil {
return nil
}
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
cmd.WaitDelay = 5 * time.Second
var stderr bytes.Buffer
cmd.Stderr = &stderr
runErr := cmd.Run()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &ytdlp.Error{Code: ytdlp.CodeTimeout, Retryable: true, Raw: "transcode timed out"}
}
return nil, &ytdlp.Error{Code: ytdlp.CodeCancelled, Raw: "transcode cancelled"}
}
if runErr != nil {
raw := strings.TrimSpace(stderr.String())
if len(raw) > 600 {
raw = raw[len(raw)-600:]
}
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg: " + links.RedactText(raw)}
}
st, err := os.Stat(out)
if err != nil || st.Size() == 0 {
return nil, &ytdlp.Error{Code: ytdlp.CodeProcessing, Raw: "ffmpeg produced no output"}
}
res := &ytdlp.Result{Path: out, Size: st.Size(), Ext: strings.TrimPrefix(filepath.Ext(out), ".")}
if d, w, h, err := ytdlp.FileInfo(ctx, e.probeBin(), out); err == nil {
res.Duration, res.Width, res.Height = d, w, h
}
return res, nil
}