Files
Media-download-telegram-bot/internal/ytdlp/exec.go
T
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

474 lines
14 KiB
Go

package ytdlp
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/noderunners/dlbot/internal/media"
)
// Exec runs the real yt-dlp and ffprobe binaries.
type Exec struct {
// Path of the yt-dlp binary. Defaults to "yt-dlp".
Path string
// FfmpegPath is passed to yt-dlp as --ffmpeg-location when it is not the
// plain "ffmpeg" found on PATH. ffprobe is expected next to it.
FfmpegPath string
// ProbeTimeout bounds a metadata lookup. Defaults to 45 seconds.
ProbeTimeout time.Duration
// DownloadTimeout bounds one download. Defaults to 30 minutes.
DownloadTimeout time.Duration
// ExtraArgs are appended to every yt-dlp call, for example a proxy.
ExtraArgs []string
}
var _ Runner = (*Exec)(nil)
func (e *Exec) bin() string {
if e.Path == "" {
return "yt-dlp"
}
return e.Path
}
func (e *Exec) ffprobeBin() string {
if e.FfmpegPath == "" || e.FfmpegPath == "ffmpeg" {
return "ffprobe"
}
return filepath.Join(filepath.Dir(e.FfmpegPath), "ffprobe")
}
func (e *Exec) baseArgs() []string {
args := []string{"--ignore-config", "--no-warnings", "--no-playlist", "--color", "never",
"--socket-timeout", "30"}
if e.FfmpegPath != "" && e.FfmpegPath != "ffmpeg" {
args = append(args, "--ffmpeg-location", e.FfmpegPath)
}
return append(args, e.ExtraArgs...)
}
// Version returns the yt-dlp version string.
func (e *Exec) Version(ctx context.Context) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, e.bin(), "--version").Output()
if err != nil {
return "", fmt.Errorf("ytdlp: version: %w", err)
}
return strings.TrimSpace(string(out)), nil
}
// Probe implements Runner. It asks for one JSON document, which is either a
// single video or a flat playlist listing.
func (e *Exec) Probe(ctx context.Context, url string) (*Info, error) {
timeout := e.ProbeTimeout
if timeout <= 0 {
timeout = 45 * time.Second
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
args := append(e.baseArgs(), "--flat-playlist", "-J", "--", url)
cmd := exec.CommandContext(ctx, e.bin(), args...)
setProcAttrs(cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &Error{Code: CodeTimeout, Retryable: true, Raw: "probe timed out"}
}
return nil, &Error{Code: CodeCancelled, Raw: "probe cancelled"}
}
if err != nil {
var ee *exec.ExitError
if !errors.As(err, &ee) {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: "cannot run yt-dlp: " + err.Error()}
}
return nil, Classify(stderr.String())
}
var info Info
if err := json.Unmarshal(bytes.TrimSpace(stdout.Bytes()), &info); err != nil {
return nil, &Error{Code: CodeUnknown, Retryable: true, Raw: "bad metadata json: " + err.Error()}
}
if info.Type == "" {
info.Type = "video"
}
return &info, nil
}
const (
progressTemplate = "download:DLP|%(progress.status)s|%(progress.downloaded_bytes)s|%(progress.total_bytes)s|%(progress.total_bytes_estimate)s"
infoTemplate = "pre_process:INFO|%(.{id,title,duration,extractor,extractor_key,uploader,is_live,live_status})j"
resultTemplate = "after_move:RESULT|%(.{width,height,duration,ext,filepath})j"
)
// profileArgs returns the yt-dlp flags that select and shape one profile.
// Video prefers h264 with AAC in an mp4 container because that is what
// Telegram clients can stream inline.
func profileArgs(p media.Profile) []string {
switch p.Kind() {
case media.KindAudio:
if p == media.M4A {
return []string{"-f", "ba[ext=m4a]/ba/b", "-x", "--audio-format", "m4a"}
}
return []string{"-f", "ba/b", "-x", "--audio-format", "mp3", "--audio-quality", "192K"}
case media.KindThumb:
return []string{"--skip-download", "--write-thumbnail", "--convert-thumbnails", "jpg"}
case media.KindSubs:
return []string{"--skip-download", "--write-subs", "--write-auto-subs",
"--sub-langs", p.SubLang(), "--convert-subs", "srt"}
}
sort := "vcodec:h264,res,acodec:m4a"
if h := p.Height(); h > 0 {
sort = "vcodec:h264,res:" + strconv.Itoa(h) + ",acodec:m4a"
}
return []string{"-S", sort, "-f", "bv*+ba/b", "--merge-output-format", "mp4/mkv"}
}
// DownloadArgs builds the full argument list for a download. It is exported
// for tests and for the operations docs.
func (e *Exec) DownloadArgs(req DownloadRequest) []string {
args := e.baseArgs()
args = append(args,
"--newline", "--no-mtime", "--progress", "--progress-delta", "1",
"--retries", "3", "--fragment-retries", "5",
"--progress-template", progressTemplate,
"--print", infoTemplate,
"--print", resultTemplate,
"--no-simulate",
"-P", req.Dir, "-o", "media.%(ext)s",
)
filter := "!is_live"
if req.MaxDuration > 0 {
filter += " & duration<=?" + strconv.Itoa(int(req.MaxDuration.Seconds()))
}
args = append(args, "--match-filters", filter)
if req.MaxSize > 0 && req.Profile.Kind() != media.KindThumb && req.Profile.Kind() != media.KindSubs {
args = append(args, "--max-filesize", strconv.FormatInt(req.MaxSize, 10))
}
args = append(args, profileArgs(req.Profile)...)
return append(args, "--", req.URL)
}
type preInfo struct {
ID string `json:"id"`
Title string `json:"title"`
Duration Float `json:"duration"`
Extractor string `json:"extractor"`
Uploader string `json:"uploader"`
IsLive bool `json:"is_live"`
LiveStatus string `json:"live_status"`
}
type postInfo struct {
Width Int `json:"width"`
Height Int `json:"height"`
Duration Float `json:"duration"`
Ext string `json:"ext"`
Filepath string `json:"filepath"`
}
// Download implements Runner.
func (e *Exec) Download(ctx context.Context, req DownloadRequest, onProgress func(Progress)) (*Result, error) {
timeout := e.DownloadTimeout
if timeout <= 0 {
timeout = 30 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
if err := os.MkdirAll(req.Dir, 0o750); err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
cmd := exec.CommandContext(ctx, e.bin(), e.DownloadArgs(req)...)
setProcAttrs(cmd)
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
var stderr tailBuffer
cmd.Stderr = &stderr
if err := cmd.Start(); err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: "cannot run yt-dlp: " + err.Error()}
}
var (
pre preInfo
post postInfo
outLines tailBuffer
)
sc := bufio.NewScanner(stdout)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
for sc.Scan() {
line := sc.Text()
switch {
case strings.HasPrefix(line, "DLP|"):
if onProgress != nil {
if p, ok := parseProgress(line); ok {
onProgress(p)
}
}
case strings.HasPrefix(line, "INFO|"):
_ = json.Unmarshal([]byte(line[5:]), &pre)
case strings.HasPrefix(line, "RESULT|"):
_ = json.Unmarshal([]byte(line[7:]), &post)
default:
if onProgress != nil && isPostprocessLine(line) {
onProgress(Progress{Stage: StageProcessing})
}
_, _ = outLines.Write([]byte(line + "\n"))
}
}
waitErr := cmd.Wait()
if ctxErr := ctx.Err(); ctxErr != nil {
if errors.Is(ctxErr, context.DeadlineExceeded) {
return nil, &Error{Code: CodeTimeout, Retryable: true, Raw: "download timed out"}
}
return nil, &Error{Code: CodeCancelled, Raw: "download cancelled"}
}
raw := stderr.String() + "\n" + outLines.String()
if waitErr != nil {
return nil, Classify(raw)
}
path := post.Filepath
if path == "" || !fileExists(path) {
path = findOutput(req.Dir)
}
if path == "" {
// yt-dlp exits 0 when a filter or the size cap skipped the item.
return nil, noFileError(req, pre, raw)
}
st, err := os.Stat(path)
if err != nil {
return nil, &Error{Code: CodeInternal, Retryable: true, Raw: err.Error()}
}
res := &Result{
Path: path,
Size: st.Size(),
Ext: strings.TrimPrefix(filepath.Ext(path), "."),
ID: pre.ID,
Title: pre.Title,
Uploader: pre.Uploader,
Extractor: pre.Extractor,
Duration: float64(pre.Duration),
Width: int(post.Width),
Height: int(post.Height),
}
if post.Duration > 0 {
res.Duration = float64(post.Duration)
}
if k := req.Profile.Kind(); k == media.KindVideo || k == media.KindAudio {
if fp, err := e.ffprobe(ctx, path); err == nil {
if fp.duration > 0 {
res.Duration = fp.duration
}
if k == media.KindVideo && fp.width > 0 {
res.Width, res.Height = fp.width, fp.height
}
}
}
if req.MaxSize > 0 && res.Size > req.MaxSize {
return nil, &Error{Code: CodeTooLarge, Raw: fmt.Sprintf("output is %d bytes, cap is %d", res.Size, req.MaxSize)}
}
if req.MaxDuration > 0 && res.Duration > req.MaxDuration.Seconds()+1 {
return nil, &Error{Code: CodeTooLong, Raw: fmt.Sprintf("output is %.0f seconds, cap is %.0f", res.Duration, req.MaxDuration.Seconds())}
}
return res, nil
}
func noFileError(req DownloadRequest, pre preInfo, raw string) *Error {
low := strings.ToLower(raw)
switch {
case pre.IsLive || pre.LiveStatus == "is_live" || pre.LiveStatus == "is_upcoming":
return &Error{Code: CodeLive, Raw: "live stream skipped"}
case req.MaxDuration > 0 && float64(pre.Duration) > req.MaxDuration.Seconds():
return &Error{Code: CodeTooLong, Raw: fmt.Sprintf("duration %.0f over cap", float64(pre.Duration))}
case strings.Contains(low, "larger than max-filesize"):
return &Error{Code: CodeTooLarge, Raw: "file larger than cap"}
case strings.Contains(low, "no subtitles") || req.Profile.Kind() == media.KindSubs:
return &Error{Code: CodeNoSubtitles, Raw: "no subtitles for " + req.Profile.SubLang()}
case req.Profile.Kind() == media.KindThumb:
return &Error{Code: CodeNoMedia, Raw: "no thumbnail"}
}
e := Classify(raw)
if e.Code == CodeUnknown {
e.Raw = "yt-dlp produced no file: " + e.Raw
}
return e
}
func parseProgress(line string) (Progress, bool) {
parts := strings.Split(line, "|")
if len(parts) < 5 {
return Progress{}, false
}
p := Progress{Stage: StageDownloading}
p.Downloaded = atoi64(parts[2])
p.Total = atoi64(parts[3])
if p.Total == 0 {
p.Total = atoi64(parts[4])
}
if parts[1] == "finished" {
p.Stage = StageProcessing
}
return p, true
}
func atoi64(s string) int64 {
if s == "" || s == "NA" || s == "None" {
return 0
}
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
return n
}
if f, err := strconv.ParseFloat(s, 64); err == nil {
return int64(f)
}
return 0
}
func isPostprocessLine(line string) bool {
for _, p := range []string{"[Merger]", "[ExtractAudio]", "[VideoRemuxer]", "[VideoConvertor]", "[ThumbnailsConvertor]", "[SubtitlesConvertor]", "[Fixup"} {
if strings.HasPrefix(line, p) {
return true
}
}
return false
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && st.Mode().IsRegular()
}
// findOutput returns the largest finished file in dir, ignoring yt-dlp
// leftovers. Used for profiles that never reach the after_move stage.
func findOutput(dir string) string {
entries, err := os.ReadDir(dir)
if err != nil {
return ""
}
var best string
var bestSize int64 = -1
for _, en := range entries {
if en.IsDir() {
continue
}
name := en.Name()
if strings.HasSuffix(name, ".part") || strings.HasSuffix(name, ".ytdl") ||
strings.HasSuffix(name, ".json") || strings.HasSuffix(name, ".temp") ||
strings.Contains(name, ".part-") {
continue
}
fi, err := en.Info()
if err != nil || fi.Size() == 0 {
continue
}
if fi.Size() > bestSize {
best, bestSize = filepath.Join(dir, name), fi.Size()
}
}
return best
}
type probed struct {
duration float64
width, height int
}
func (e *Exec) ffprobe(ctx context.Context, path string) (probed, error) {
return ffprobe(ctx, e.ffprobeBin(), path)
}
// FileInfo reads duration and picture size of a media file with ffprobe.
func FileInfo(ctx context.Context, ffprobePath, path string) (duration float64, width, height int, err error) {
p, err := ffprobe(ctx, ffprobePath, path)
return p.duration, p.width, p.height, err
}
func ffprobe(ctx context.Context, bin, path string) (probed, error) {
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
out, err := exec.CommandContext(ctx, bin, "-v", "error",
"-show_entries", "format=duration:stream=codec_type,width,height",
"-of", "json", path).Output()
if err != nil {
return probed{}, err
}
var doc struct {
Streams []struct {
CodecType string `json:"codec_type"`
Width int `json:"width"`
Height int `json:"height"`
} `json:"streams"`
Format struct {
Duration string `json:"duration"`
} `json:"format"`
}
if err := json.Unmarshal(out, &doc); err != nil {
return probed{}, err
}
var p probed
p.duration, _ = strconv.ParseFloat(doc.Format.Duration, 64)
for _, s := range doc.Streams {
if s.CodecType == "video" && s.Width > 0 {
p.width, p.height = s.Width, s.Height
break
}
}
return p, nil
}
// setProcAttrs puts the child in its own process group so that cancelling
// also stops the ffmpeg processes yt-dlp starts.
func setProcAttrs(cmd *exec.Cmd) {
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
}
// tailBuffer keeps the last 16 KiB written to it.
type tailBuffer struct {
mu sync.Mutex
buf []byte
}
const tailMax = 16 * 1024
func (t *tailBuffer) Write(p []byte) (int, error) {
t.mu.Lock()
defer t.mu.Unlock()
t.buf = append(t.buf, p...)
if len(t.buf) > tailMax {
t.buf = t.buf[len(t.buf)-tailMax:]
}
return len(p), nil
}
func (t *tailBuffer) String() string {
t.mu.Lock()
defer t.mu.Unlock()
return string(t.buf)
}