// 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 }