carlos / platform Public

media: sniff and probe before any encode

Plan 3 Task 3. The codec handler reads the source's first bytes in Go
and accepts only the container families spec §6 allows, so ffprobe
never sees anything else. It then runs ffprobe with the demuxer forced,
the protocol and decoder allow-lists and -loglevel error (F19), and
checks the facts in spec §6's order against the job's limits, using
media's MaxSide, MaxFPS, MaxDimensions and Above1080p (F37). PCM is
exactly the allow-list's set (F18); cover art is not video (F17).

runChild runs every child with an explicit minimal environment, its
own process group and Pdeathsig, with the starting thread locked and
the direct child reaped first (F35). The handler is a child subreaper,
and on exit or timeout everything the child started is killed and
reaped within 5 s, else engine_failed. Runs are one at a time.

Probe fixtures are stand-ins until plan 1's spike saves Paul's files.
New log lines are in the copy deck, pending a Luna pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 80bae6cf30e2bfd0f9816a0b77bd8c700b19f23c parent 71dae49
27 files changed, +3,075 −2
  • docs/superpowers/notes/media-conversion-copy-deck.md +14 −0
  • internal/mediahandler/fakeffmpeg_test.go +209 −0
  • internal/mediahandler/handler.go +13 −2
  • internal/mediahandler/probe.go +619 −0
  • internal/mediahandler/probe_test.go +722 −0
  • internal/mediahandler/procs.go +63 −0
  • internal/mediahandler/procs_linux.go +275 −0
  • internal/mediahandler/procs_other.go +24 −0
  • internal/mediahandler/procs_test.go +482 −0
  • internal/mediahandler/sniff.go +77 −0
  • internal/mediahandler/sniff_test.go +137 −0
  • internal/mediahandler/testdata/probe/aac-6ch.json +23 −0
  • internal/mediahandler/testdata/probe/bomb-30000.json +23 −0
  • internal/mediahandler/testdata/probe/chrome-webm-opus.json +25 −0
  • internal/mediahandler/testdata/probe/chrome-webm-opus.packets.csv +7 −0
  • internal/mediahandler/testdata/probe/dolby-vision-5.json +26 −0
  • internal/mediahandler/testdata/probe/dolby-vision-8-4.json +41 −0
  • internal/mediahandler/testdata/probe/h264-120fps.json +23 −0
  • internal/mediahandler/testdata/probe/h264-4k60.json +34 −0
  • internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json +59 −0
  • internal/mediahandler/testdata/probe/lying-10h.json +23 −0
  • internal/mediahandler/testdata/probe/m4a-cover-art.json +32 −0
  • internal/mediahandler/testdata/probe/mka-cover-art.json +30 −0
  • internal/mediahandler/testdata/probe/mp3-cover-art.json +34 −0
  • internal/mediahandler/testdata/probe/stand-ins.txt +13 −0
  • internal/mediahandler/testdata/probe/vfr-screen-recording.json +24 −0
  • internal/mediahandler/testdata/probe/wav-mono.json +23 −0
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 4c5e54588..34411c0a5 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -548,3 +548,17 @@ prints nothing.
| `engine.codec.stopped` | `codec: stopped: %s` (pending Luna pass; plan 3 Task 2). `%s` is Go's context error |
| `engine.download.resume` | `source download: broke after %d bytes; resume %d of %d` (pending Luna pass; plan 3 Task 2) |
| `engine.download.gave_up` | `source download: broke %d times; giving up` (pending Luna pass; plan 3 Task 2) |
+| `engine.codec.source_unopenable` | `codec: the downloaded source cannot be read: %s` (pending Luna pass; plan 3 Task 3). `%s` is the system's error for the scratch source path |
+| `engine.probe.failed` | `codec: ffprobe failed: %q` (pending Luna pass; plan 3 Task 3). `%q` is the last 64 KiB of ffprobe's stderr at `-loglevel error`, quoted so it stays one line |
+| `engine.probe.timeout` | `codec: ffprobe did not finish in time` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.unusable` | `codec: ffprobe's answer is over %d bytes` (pending Luna pass; plan 3 Task 3). `%d` is 1048576 |
+| `engine.probe.unparsable` | `codec: ffprobe's answer is unusable: %s` (pending Luna pass; plan 3 Task 3). `%s` is one of `engine.probe.reason.*` |
+| `engine.probe.reason.not_json` | `not ffprobe's JSON` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.reason.trailing` | `data after ffprobe's JSON` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.reason.negative` | `stream %d has a negative field` (pending Luna pass; plan 3 Task 3). `%d` is the stream's position |
+| `engine.probe.reason.rate` | `stream %d avg_frame_rate: not a rational of non-negative integers`, and the same with `r_frame_rate` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.reason.rotate` | `stream %d rotate tag is not an integer` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.reason.duration` | `format duration: not a duration`, `stream %d duration: not a duration` (pending Luna pass; plan 3 Task 3) |
+| `engine.probe.no_duration` | `codec: the source has no duration in its header or its packets` (pending Luna pass; plan 3 Task 3) |
+| `engine.child.failed` | `codec: child process: %s: %s`, or without the second `%s` (pending Luna pass; plan 3 Task 3). The first `%s` is one of `cannot become a subreaper`, `no pipe`, `cannot start <binary path>`, `the child outlived SIGKILL`, `descendants outlived the cleanup`, `a pipe stayed open`, `wait failed`; the second is the system's error |
+| `engine.child.unsupported` | `codec: child processes need Linux` (pending Luna pass; plan 3 Task 3). Only off Linux, where the handler never runs |
diff --git a/internal/mediahandler/fakeffmpeg_test.go b/internal/mediahandler/fakeffmpeg_test.go
new file mode 100644
index 000000000..6116aab12
--- /dev/null
+++ b/internal/mediahandler/fakeffmpeg_test.go
@@ -0,0 +1,209 @@
+package mediahandler
+
+import (
+ "embed"
+ "encoding/json"
+ "fmt"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// The fake ffmpeg and ffprobe: the test binary re-executed as either,
+// with fakeEnv naming a scenario. TestMain runs the scenario instead of
+// the tests, so the fake takes ffmpeg's own arguments, never the test
+// flags. Tasks 4 to 7 add their scenarios to fakeScenarios.
+//
+// A test points Config.FFprobe (or FFmpeg) at fakeBinary(t) and passes
+// the scenario through Config.extraEnv, since runChild gives every
+// child an explicit environment and nothing of the parent's.
+const (
+ // fakeEnv names the scenario.
+ fakeEnv = "MEDIA_FAKE"
+ // fakeRecordEnv, when set, is a file the fake appends one JSON line
+ // to per run: its arguments and its environment.
+ fakeRecordEnv = "MEDIA_FAKE_RECORD"
+ // fakeNoPacketsEnv, when set, makes a probe fake fail its packet
+ // pass.
+ fakeNoPacketsEnv = "MEDIA_FAKE_NOPACKETS"
+)
+
+// probeFixtures are the ffprobe answers in testdata/probe. Each is
+// ffprobe 7.1's -of json shape with every tags object removed; the
+// <name>.packets.csv beside one is its answer to the packet pass. The
+// four named for Paul's files are stand-ins until plan 1's spike saves
+// the real ones (testdata/probe/stand-ins.txt).
+//
+//go:embed testdata/probe
+var probeFixtures embed.FS
+
+// fakeScenarios are the fakes by name; "probe-<fixture>" is handled by
+// fakeProbe. Each answers the process's exit code.
+var fakeScenarios = map[string]func(args []string) int{
+ // block never exits by itself: it waits for a signal it never gets.
+ "block": func([]string) int { return blockForever() },
+ // fail prints to stderr and exits 1.
+ "fail": func([]string) int {
+ fmt.Fprintln(os.Stderr, "fake: Invalid data found when processing input")
+ return 1
+ },
+ // env prints the fake's environment to stdout, one entry a line.
+ "env": func([]string) int {
+ for _, kv := range os.Environ() {
+ fmt.Println(kv)
+ }
+ return 0
+ },
+ // flood writes a whole, valid ffprobe answer followed by 2 MiB of
+ // white space: its first MiB parses, but it is more than probe
+ // reads.
+ "flood": func([]string) int {
+ if code := fakeProbe("wav-mono", nil); code != 0 {
+ return code
+ }
+ line := strings.Repeat(" ", 1023) + "\n"
+ for range 2048 {
+ if _, err := os.Stdout.WriteString(line); err != nil {
+ return 1
+ }
+ }
+ return 0
+ },
+ // noisy writes 100 KiB to stderr (each line numbered) and exits 1.
+ "noisy": func([]string) int {
+ for i := range 1000 {
+ fmt.Fprintf(os.Stderr, "line %04d %s\n", i, strings.Repeat("x", 92))
+ }
+ return 1
+ },
+}
+
+func TestMain(m *testing.M) {
+ if scenario := os.Getenv(fakeEnv); scenario != "" {
+ os.Exit(runFake(scenario, os.Args[1:]))
+ }
+ os.Exit(m.Run())
+}
+
+// runFake records the run, if asked, and runs the scenario.
+func runFake(scenario string, args []string) int {
+ if path := os.Getenv(fakeRecordEnv); path != "" {
+ line, _ := json.Marshal(fakeRun{Scenario: scenario, Args: args, Env: os.Environ()})
+ f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600)
+ if err != nil {
+ return 97
+ }
+ _, err = f.Write(append(line, '\n'))
+ if f.Close() != nil || err != nil {
+ return 97
+ }
+ }
+ if name, ok := strings.CutPrefix(scenario, "probe-"); ok {
+ return fakeProbe(name, args)
+ }
+ if f := fakeScenarios[scenario]; f != nil {
+ return f(args)
+ }
+ fmt.Fprintf(os.Stderr, "fake: unknown scenario %q\n", scenario)
+ return 98
+}
+
+// fakeProbe prints testdata/probe/<name>.json, or <name>.packets.csv
+// when the arguments ask for the packet pass (exit 1 when the fixture
+// has none).
+func fakeProbe(name string, args []string) int {
+ file := name + ".json"
+ for i, a := range args {
+ if a == "-show_entries" && i+1 < len(args) && strings.HasPrefix(args[i+1], "packet=") {
+ if os.Getenv(fakeNoPacketsEnv) != "" {
+ fmt.Fprintln(os.Stderr, "fake: the packet pass fails")
+ return 1
+ }
+ file = name + ".packets.csv"
+ }
+ }
+ b, err := probeFixtures.ReadFile("testdata/probe/" + file)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "fake: no fixture %s\n", file)
+ return 1
+ }
+ if _, err := os.Stdout.Write(b); err != nil {
+ return 1
+ }
+ return 0
+}
+
+// blockForever waits on a signal nothing sends. signal.Notify keeps the
+// runtime from calling it a deadlock; a fake that must outlive a test
+// is ended with SIGKILL (and SIGKILL only: SIGTERM and SIGHUP are
+// caught here too).
+func blockForever() int {
+ c := make(chan os.Signal, 1)
+ signal.Notify(c, hostileSignals...)
+ for {
+ <-c
+ }
+}
+
+// hostileSignals are the signals a blocking fake catches and ignores.
+var hostileSignals = []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGHUP}
+
+// fakeRun is one recorded run of the fake.
+type fakeRun struct {
+ Scenario string
+ Args []string
+ Env []string
+}
+
+// fakeBinary is the test binary's path, for Config.FFprobe and FFmpeg.
+func fakeBinary(t *testing.T) string {
+ t.Helper()
+ exe, err := os.Executable()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return exe
+}
+
+// fakeConfig is a Config whose ffprobe and ffmpeg are the fake running
+// scenario, recording each run to a file it answers. Its scratch has
+// in, out and tmp.
+func fakeConfig(t *testing.T, scenario string) (Config, string) {
+ t.Helper()
+ record := filepath.Join(t.TempDir(), "runs.jsonl")
+ cfg := Config{
+ FFmpeg: fakeBinary(t),
+ FFprobe: fakeBinary(t),
+ Scratch: t.TempDir(),
+ Logf: t.Logf,
+ extraEnv: []string{fakeEnv + "=" + scenario, fakeRecordEnv + "=" + record},
+ }
+ if err := prepareScratch(cfg.Scratch); err != nil {
+ t.Fatal(err)
+ }
+ return cfg.withDefaults(), record
+}
+
+// fakeRuns reads the runs recorded in path; none when it does not exist.
+func fakeRuns(t *testing.T, path string) []fakeRun {
+ t.Helper()
+ b, err := os.ReadFile(path)
+ if os.IsNotExist(err) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var runs []fakeRun
+ for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") {
+ var r fakeRun
+ if err := json.Unmarshal([]byte(line), &r); err != nil {
+ t.Fatalf("record %q: %v", line, err)
+ }
+ runs = append(runs, r)
+ }
+ return runs
+}
diff --git a/internal/mediahandler/handler.go b/internal/mediahandler/handler.go
index f302d7c16..61c67add0 100644
--- a/internal/mediahandler/handler.go
+++ b/internal/mediahandler/handler.go
@@ -1,7 +1,7 @@
// Package mediahandler is the codec container's handler (spec §5.5, §6):
// it reads the payload, downloads the source with the signed transfer,
-// and (later tasks of plan 3) sniffs, probes, converts, collects the
-// outputs, uploads them and writes the result object.
+// sniffs, probes and checks it, and (later tasks of plan 3) converts,
+// collects the outputs, uploads them and writes the result object.
//
// It never logs a transfer, a URL, a query, a header or the payload, and
// no error it makes carries one (preflight F6): the presigned URLs hold
@@ -56,6 +56,12 @@ type Config struct {
// idle makes the per-read idle timer; nil is newIdleTimer. Tests
// replace it to fire the timer by hand.
idle func(d time.Duration, f func()) idleTimer
+ // probeTimeout bounds the probe; 0 is probeTimeout (60 s). Tests
+ // shorten it.
+ probeTimeout time.Duration
+ // extraEnv is appended to every child's environment (childEnv).
+ // Tests only: it names the fake ffmpeg's scenario.
+ extraEnv []string
}
// withDefaults fills every unset field.
@@ -127,6 +133,11 @@ func Run(ctx context.Context, cfg Config, payload string) int {
return media.ExitFailed
}
err = download(ctx, cfg, p, sourcePath(cfg))
+ if err == nil {
+ // Sniff, probe and check (spec §6). The encodes (plan 3 Tasks 4
+ // and 5) take the demuxer and the facts.
+ _, _, err = inspectSource(ctx, cfg, p)
+ }
if err == nil {
err = errNotBuilt
}
diff --git a/internal/mediahandler/probe.go b/internal/mediahandler/probe.go
new file mode 100644
index 000000000..946ef43ae
--- /dev/null
+++ b/internal/mediahandler/probe.go
@@ -0,0 +1,619 @@
+package mediahandler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// probeTimeout bounds the probe, both passes (spec §6: a probe over
+// 60 s is unreadable).
+const probeTimeout = 60 * time.Second
+
+// maxProbeOutput is the most of ffprobe's JSON the handler reads; more
+// is unreadable.
+const maxProbeOutput = 1 << 20
+
+// codecWhitelist is every run's -codec_whitelist (plan 3's Global
+// Constraints): the decoders for the codecs check accepts.
+const codecWhitelist = "h264,hevc,vp8,vp9,av1,libdav1d,aac,opus,libopus,vorbis,libvorbis,mp3,mp3float,flac," +
+ "pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_f64be,pcm_alaw,pcm_mulaw"
+
+// videoCodecs are the video codec names check accepts (spec §6).
+var videoCodecs = map[string]bool{"h264": true, "hevc": true, "vp8": true, "vp9": true, "av1": true}
+
+// audioCodecs are the audio codec names check accepts: AAC, Opus,
+// Vorbis, MP3, FLAC, and exactly the PCM codecs the decoder allow-list
+// names (preflight F18: any other pcm_* would pass the check and then
+// be refused by ffmpeg as unreadable).
+var audioCodecs = func() map[string]bool {
+ m := map[string]bool{"aac": true, "opus": true, "vorbis": true, "mp3": true, "flac": true}
+ for _, name := range strings.Split(codecWhitelist, ",") {
+ if strings.HasPrefix(name, "pcm_") {
+ m[name] = true
+ }
+ }
+ return m
+}()
+
+// maxPixels is media.MaxDimensions' width times height.
+var maxPixels = func() int64 {
+ w, h, _ := strings.Cut(media.MaxDimensions, "x")
+ wn, err1 := strconv.ParseInt(w, 10, 64)
+ hn, err2 := strconv.ParseInt(h, 10, 64)
+ if err1 != nil || err2 != nil {
+ panic("media.MaxDimensions is not <w>x<h>")
+ }
+ return wn * hn
+}()
+
+// grantedByClass is JobLimits.GrantedBy when the class's granted
+// duration bounds the job (internal/mediajobs/dispatch.go); anything
+// else is the allowance.
+const grantedByClass = "class"
+
+// refuseDolbyVision5 is the spike's ruling (plan 1): true refuses Dolby
+// Vision profile 5 as unsupported_hdr; false decodes it as HEVC and
+// tone-maps it. Provisional: false until the spike report says
+// otherwise. A variable so the test can set it.
+var refuseDolbyVision5 = false
+
+// maxDurationMS is where a parsed duration saturates: far over every
+// maximum, so a header claiming more is source_too_long, and far under
+// int64's range, so a sum of two cannot overflow.
+const maxDurationMS = int64(1) << 50
+
+// probeFacts are what the checks and the encodes need from ffprobe.
+// An absent stream's index is -1. Rotation is the display matrix's, in
+// ffprobe's sense (degrees counter-clockwise: an iPhone portrait clip
+// is -90), one of -90, 0, 90, 180.
+type probeFacts struct {
+ VideoIndex, AudioIndex int
+ Width, Height, Rotation int
+ FPS float64
+ HDR bool
+ DolbyVisionProfile int
+ VideoCodec, AudioCodec string
+ Channels int
+ DurationMS int64
+}
+
+// probeArgs are ffprobe's arguments for the source: the shared input
+// options, then extra, then the fixed input path. -loglevel error
+// keeps the source's metadata (a title, a comment, a location) off
+// stderr and so out of the task's log (preflight F19). ffprobe prints
+// no progress, so it takes no -nostats.
+func probeArgs(cfg Config, demuxer string, extra ...string) []string {
+ args := []string{"-hide_banner", "-loglevel", "error", "-protocol_whitelist", "file", "-f", demuxer}
+ if demuxer == "mov" {
+ args = append(args, "-enable_drefs", "0")
+ }
+ args = append(args, "-codec_whitelist", codecWhitelist)
+ args = append(args, extra...)
+ return append(args, "-i", sourcePath(cfg))
+}
+
+// probe runs ffprobe on the source with the sniffed demuxer forced and
+// answers its facts. The duration is the header's (parseProbe); when it
+// has none, a second pass reads the chosen stream's packets (the video,
+// else the audio) and takes the largest pts+duration. The two passes
+// share one probeTimeout. Failures:
+//
+// - ffprobe failing, overrunning maxProbeOutput, answering what
+// parseProbe refuses, or missing probeTimeout: unreadable;
+// - a stream to time but no packet time: unreadable;
+// - ffprobe not starting, or its cleanup failing: engine_failed;
+// - ctx ending (the task stopping): ctx's error.
+func probe(ctx context.Context, cfg Config, demuxer string) (probeFacts, error) {
+ timeout := cfg.probeTimeout
+ if timeout <= 0 {
+ timeout = probeTimeout
+ }
+ pctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ dir := filepath.Join(cfg.Scratch, "tmp")
+
+ out := &capBuffer{max: maxProbeOutput}
+ tail, err := runChildTo(pctx, cfg, cfg.FFprobe, probeArgs(cfg, demuxer, "-show_format", "-show_streams", "-of", "json"), dir, out)
+ if err := probeFailed(ctx, cfg, tail, err); err != nil {
+ return probeFacts{}, err
+ }
+ if out.over {
+ // engine.probe.unusable (pending Luna pass).
+ cfg.Logf("codec: ffprobe's answer is over %d bytes", maxProbeOutput)
+ return probeFacts{}, jobError{media.CodeUnreadable}
+ }
+ f, err := parseProbe(out.buf.Bytes())
+ if err != nil {
+ // engine.probe.unparsable (pending Luna pass). err names a
+ // field or a fixed reason, never a value.
+ cfg.Logf("codec: ffprobe's answer is unusable: %v", err)
+ return probeFacts{}, jobError{media.CodeUnreadable}
+ }
+ if f.DurationMS > 0 {
+ return f, nil
+ }
+ index := f.VideoIndex
+ if index < 0 {
+ index = f.AudioIndex
+ }
+ if index < 0 {
+ // Nothing to time: check answers no_video or no_audio first.
+ return f, nil
+ }
+ var pm packetMax
+ tail, err = runChildTo(pctx, cfg, cfg.FFprobe, probeArgs(cfg, demuxer,
+ "-select_streams", strconv.Itoa(index), "-show_entries", "packet=pts_time,duration_time", "-of", "csv=p=0"), dir, &pm)
+ if err := probeFailed(ctx, cfg, tail, err); err != nil {
+ return probeFacts{}, err
+ }
+ if f.DurationMS = pm.result(); f.DurationMS <= 0 {
+ // engine.probe.no_duration (pending Luna pass).
+ cfg.Logf("codec: the source has no duration in its header or its packets")
+ return probeFacts{}, jobError{media.CodeUnreadable}
+ }
+ return f, nil
+}
+
+// probeFailed maps one ffprobe run's outcome: nil for a clean exit;
+// ctx's error when the task is stopping; engine_failed as runChild
+// gave it; anything else unreadable, logged with ffprobe's stderr tail
+// (quoted, so it stays one line and cannot forge another).
+func probeFailed(ctx context.Context, cfg Config, tail []byte, err error) error {
+ var je jobError
+ switch {
+ case err == nil:
+ return nil
+ case ctx.Err() != nil:
+ return ctx.Err()
+ case errors.As(err, &je) && je.code == media.CodeEngineFailed:
+ return err
+ case errors.Is(err, context.DeadlineExceeded):
+ // engine.probe.timeout (pending Luna pass).
+ cfg.Logf("codec: ffprobe did not finish in time")
+ return jobError{media.CodeUnreadable}
+ }
+ // engine.probe.failed (pending Luna pass). The tail is ffprobe's
+ // stderr at -loglevel error: its errors, never the payload.
+ cfg.Logf("codec: ffprobe failed: %q", tail)
+ return jobError{media.CodeUnreadable}
+}
+
+// ffprobe's -of json answer, the parts parseProbe reads.
+type ffOutput struct {
+ Streams []ffStream `json:"streams"`
+ Format struct {
+ Duration string `json:"duration"`
+ } `json:"format"`
+}
+
+type ffStream struct {
+ Index int `json:"index"`
+ CodecType string `json:"codec_type"`
+ CodecName string `json:"codec_name"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ AvgFrameRate string `json:"avg_frame_rate"`
+ RFrameRate string `json:"r_frame_rate"`
+ ColorTransfer string `json:"color_transfer"`
+ Channels int `json:"channels"`
+ Duration string `json:"duration"`
+ Disposition struct {
+ AttachedPic int `json:"attached_pic"`
+ } `json:"disposition"`
+ Tags struct {
+ Rotate string `json:"rotate"`
+ } `json:"tags"`
+ SideData []struct {
+ Type string `json:"side_data_type"`
+ Rotation *float64 `json:"rotation"`
+ DVProfile *int `json:"dv_profile"`
+ } `json:"side_data_list"`
+}
+
+// Side data types, as ffprobe names them.
+const (
+ sideDisplayMatrix = "Display Matrix"
+ sideDolbyVision = "DOVI configuration record"
+)
+
+// parseProbe reads ffprobe's -show_format -show_streams -of json
+// answer. ffprobe is trusted to answer in its shape, but it has read
+// hostile input, so parseProbe refuses anything negative or malformed
+// rather than pass it on. Rules (plan 3 Task 3):
+//
+// - streams whose disposition.attached_pic is 1 (cover art) are
+// skipped; the first remaining video and the first audio stream are
+// taken, and every other stream is ignored;
+// - rotation from the display matrix side data, else the rotate tag
+// (clockwise, so negated), rounded to a multiple of 90;
+// - FPS from avg_frame_rate, r_frame_rate only when the average is
+// 0/0 (or absent);
+// - HDR when color_transfer is smpte2084 or arib-std-b67, or Dolby
+// Vision side data is present;
+// - duration from format.duration, else the longest of the taken
+// streams' durations, else 0 (probe's packet pass), rounded up to
+// the millisecond.
+func parseProbe(b []byte) (probeFacts, error) {
+ var out ffOutput
+ dec := json.NewDecoder(bytes.NewReader(b))
+ if err := dec.Decode(&out); err != nil {
+ // A json error can quote the input: never pass it on.
+ return probeFacts{}, errors.New("not ffprobe's JSON")
+ }
+ if _, err := dec.Token(); err != io.EOF {
+ return probeFacts{}, errors.New("data after ffprobe's JSON")
+ }
+ f := probeFacts{VideoIndex: -1, AudioIndex: -1}
+ var video, audio *ffStream
+ for i := range out.Streams {
+ s := &out.Streams[i]
+ if s.Index < 0 || s.Width < 0 || s.Height < 0 || s.Channels < 0 {
+ return probeFacts{}, fmt.Errorf("stream %d has a negative field", i)
+ }
+ if s.Disposition.AttachedPic == 1 {
+ continue
+ }
+ switch {
+ case s.CodecType == "video" && video == nil:
+ video = s
+ case s.CodecType == "audio" && audio == nil:
+ audio = s
+ }
+ }
+ var err error
+ if video != nil {
+ if err = videoFacts(&f, video); err != nil {
+ return probeFacts{}, err
+ }
+ }
+ if audio != nil {
+ f.AudioIndex, f.AudioCodec, f.Channels = audio.Index, audio.CodecName, audio.Channels
+ }
+ if f.DurationMS, err = parseSecondsMS(out.Format.Duration); err != nil {
+ return probeFacts{}, fmt.Errorf("format duration: %w", err)
+ }
+ if f.DurationMS == 0 {
+ for _, s := range []*ffStream{video, audio} {
+ if s == nil {
+ continue
+ }
+ ms, err := parseSecondsMS(s.Duration)
+ if err != nil {
+ return probeFacts{}, fmt.Errorf("stream %d duration: %w", s.Index, err)
+ }
+ f.DurationMS = max(f.DurationMS, ms)
+ }
+ }
+ return f, nil
+}
+
+// videoFacts fills f from the taken video stream.
+func videoFacts(f *probeFacts, s *ffStream) error {
+ f.VideoIndex, f.VideoCodec, f.Width, f.Height = s.Index, s.CodecName, s.Width, s.Height
+ fps, err := parseRate(s.AvgFrameRate)
+ if err != nil {
+ return fmt.Errorf("stream %d avg_frame_rate: %w", s.Index, err)
+ }
+ if fps < 0 {
+ if fps, err = parseRate(s.RFrameRate); err != nil {
+ return fmt.Errorf("stream %d r_frame_rate: %w", s.Index, err)
+ }
+ }
+ f.FPS = max(fps, 0)
+ f.HDR = s.ColorTransfer == "smpte2084" || s.ColorTransfer == "arib-std-b67"
+ matrix := false
+ for _, sd := range s.SideData {
+ switch sd.Type {
+ case sideDisplayMatrix:
+ if sd.Rotation != nil && !matrix {
+ f.Rotation, matrix = quarterTurns(*sd.Rotation), true
+ }
+ case sideDolbyVision:
+ f.HDR = true
+ if sd.DVProfile != nil {
+ f.DolbyVisionProfile = *sd.DVProfile
+ }
+ }
+ }
+ if !matrix && s.Tags.Rotate != "" {
+ r, err := strconv.Atoi(s.Tags.Rotate)
+ if err != nil {
+ return fmt.Errorf("stream %d rotate tag is not an integer", s.Index)
+ }
+ f.Rotation = quarterTurns(-float64(r))
+ }
+ return nil
+}
+
+// quarterTurns rounds degrees to the nearest multiple of 90 in
+// (-180, 180].
+func quarterTurns(deg float64) int {
+ q := int(math.Round(math.Mod(deg, 360)/90)) * 90 // -360..360
+ switch {
+ case q <= -180:
+ q += 360
+ case q > 180:
+ q -= 360
+ }
+ return q
+}
+
+// parseRate reads an ffprobe rational "num/den" of non-negative
+// integers. "0/0" and "" are no rate, answered as -1.
+func parseRate(s string) (float64, error) {
+ if s == "" || s == "0/0" {
+ return -1, nil
+ }
+ n, d, ok := strings.Cut(s, "/")
+ num, err1 := strconv.ParseUint(n, 10, 63)
+ den, err2 := strconv.ParseUint(d, 10, 63)
+ if !ok || err1 != nil || err2 != nil || den == 0 {
+ return 0, errors.New("not a rational of non-negative integers")
+ }
+ return float64(num) / float64(den), nil
+}
+
+// parseSecondsMS reads a duration ffprobe prints as decimal seconds
+// ("12.345000"), rounded up to the millisecond. "" and "N/A" are no
+// duration (0). Anything but digits with at most one point (a sign, an
+// exponent, NaN, Inf) is an error. Past maxDurationMS it saturates.
+func parseSecondsMS(s string) (int64, error) {
+ if s == "" || s == "N/A" {
+ return 0, nil
+ }
+ us, ok := parseMicros(s)
+ if !ok || us < 0 {
+ return 0, errors.New("not a duration")
+ }
+ return microsToMS(us), nil
+}
+
+// microsToMS rounds microseconds up to milliseconds.
+func microsToMS(us int64) int64 {
+ if us <= 0 {
+ return us / 1000
+ }
+ return min((us+999)/1000, maxDurationMS)
+}
+
+// maxMicros is maxDurationMS in microseconds: where parseMicros
+// saturates.
+const maxMicros = maxDurationMS * 1000
+
+// parseMicros reads [-]digits[.digits] as microseconds, rounding a
+// seventh decimal or later up (toward +inf), saturating at ±maxMicros.
+func parseMicros(s string) (int64, bool) {
+ neg := strings.HasPrefix(s, "-")
+ s = strings.TrimPrefix(s, "-")
+ whole, frac, _ := strings.Cut(s, ".")
+ if whole == "" || !allDigits(whole) || !allDigits(frac) || (strings.Contains(s, ".") && frac == "") {
+ return 0, false
+ }
+ var us int64
+ for _, c := range whole {
+ us = us*10 + int64(c-'0')
+ if us > maxMicros/1_000_000 {
+ if neg {
+ return -maxMicros, true
+ }
+ return maxMicros, true
+ }
+ }
+ us *= 1_000_000
+ scale := int64(100_000)
+ rest := false
+ for i, c := range frac {
+ if i < 6 {
+ us += int64(c-'0') * scale
+ scale /= 10
+ } else if c != '0' {
+ rest = true
+ }
+ }
+ if neg {
+ return -us, true // rounding a negative toward +inf drops the rest
+ }
+ if rest {
+ us++
+ }
+ return min(us, maxMicros), true
+}
+
+func allDigits(s string) bool {
+ for i := 0; i < len(s); i++ {
+ if s[i] < '0' || s[i] > '9' {
+ return false
+ }
+ }
+ return true
+}
+
+// check applies spec §6's checks to f in the spec's order and answers
+// the first failure as a jobError, or nil:
+//
+// 1. no video stream (video-720p) or no audio stream (audio-aac);
+// 2. video codec not h264, hevc, vp8, vp9 or av1 (video-720p only);
+// 3. audio codec not aac, opus, vorbis, mp3, flac or an allow-listed
+// pcm_* (any taken audio stream: a video's too);
+// 4. (video-720p) a side over media.MaxSide, or more pixels than
+// media.MaxDimensions: source_dimensions (no positive size:
+// unreadable);
+// 5. (video-720p) over media.MaxFPS: source_frame_rate;
+// 6. longer than MaxHiMS (video above 1080p, media.Above1080p) or
+// MaxMS: source_too_long (no positive duration: unreadable);
+// 7. longer than GrantedMS: needs_long_class when the class granted
+// it, else allowance_exceeded;
+// 8. Dolby Vision profile 5, only when refuseDolbyVision5:
+// unsupported_hdr.
+//
+// An unknown preset is engine_failed: the payload was validated.
+func check(f probeFacts, preset string, l media.JobLimits) error {
+ video := preset == media.PresetVideo720p
+ switch {
+ case video && f.VideoIndex < 0:
+ return jobError{media.CodeNoVideo}
+ case preset == media.PresetAudioAAC && f.AudioIndex < 0:
+ return jobError{media.CodeNoAudio}
+ case !video && preset != media.PresetAudioAAC:
+ return jobError{media.CodeEngineFailed}
+ case video && !videoCodecs[f.VideoCodec]:
+ return jobError{media.CodeUnsupportedVideoCodec}
+ case f.AudioIndex >= 0 && !audioCodecs[f.AudioCodec]:
+ return jobError{media.CodeUnsupportedAudioCodec}
+ }
+ if video {
+ switch {
+ case f.Width <= 0 || f.Height <= 0:
+ return jobError{media.CodeUnreadable}
+ case f.Width > media.MaxSide || f.Height > media.MaxSide || int64(f.Width)*int64(f.Height) > maxPixels:
+ return jobError{media.CodeSourceDimensions}
+ case f.FPS < 0:
+ return jobError{media.CodeUnreadable}
+ case f.FPS > media.MaxFPS:
+ return jobError{media.CodeSourceFrameRate}
+ }
+ }
+ if f.DurationMS <= 0 {
+ return jobError{media.CodeUnreadable}
+ }
+ maxMS := l.MaxMS
+ if video && media.Above1080p(f.Width, f.Height) {
+ maxMS = l.MaxHiMS
+ }
+ if f.DurationMS > maxMS {
+ return jobError{media.CodeSourceTooLong}
+ }
+ if f.DurationMS > l.GrantedMS {
+ if l.GrantedBy == grantedByClass {
+ return jobError{media.CodeNeedsLongClass}
+ }
+ return jobError{media.CodeAllowanceExceeded}
+ }
+ if video && refuseDolbyVision5 && f.DolbyVisionProfile == 5 {
+ return jobError{media.CodeUnsupportedHDR}
+ }
+ return nil
+}
+
+// inspectSource sniffs, probes and checks the downloaded source,
+// answering the demuxer and facts the encodes use. Sniff refusing it
+// means ffprobe never runs.
+func inspectSource(ctx context.Context, cfg Config, p media.Payload) (string, probeFacts, error) {
+ head, err := readHead(sourcePath(cfg))
+ if err != nil {
+ // engine.codec.source_unopenable (pending Luna pass). The error
+ // names the scratch path only.
+ cfg.Logf("codec: the downloaded source cannot be read: %v", err)
+ return "", probeFacts{}, jobError{media.CodeEngineFailed}
+ }
+ demuxer, err := sniff(head, p.Preset)
+ if err != nil {
+ return "", probeFacts{}, err
+ }
+ f, err := probe(ctx, cfg, demuxer)
+ if err != nil {
+ return "", probeFacts{}, err
+ }
+ if err := check(f, p.Preset, p.Limits); err != nil {
+ return "", probeFacts{}, err
+ }
+ return demuxer, f, nil
+}
+
+// capBuffer keeps the first max bytes written to it and notes whether
+// more came; it never fails a write, so the child is never blocked or
+// killed by a full pipe.
+type capBuffer struct {
+ buf bytes.Buffer
+ max int
+ over bool
+}
+
+func (c *capBuffer) Write(p []byte) (int, error) {
+ if room := c.max - c.buf.Len(); len(p) > room {
+ c.over = true
+ c.buf.Write(p[:max(room, 0)])
+ } else {
+ c.buf.Write(p)
+ }
+ return len(p), nil
+}
+
+// maxPacketLine is the longest packet line packetMax reads; a longer
+// one is skipped.
+const maxPacketLine = 128
+
+// packetMax reads the packet pass's "pts_time,duration_time" lines as
+// they stream and keeps the largest pts+duration, in microseconds; a
+// line that does not parse is skipped. It holds one line at a time,
+// whatever the stream's length.
+type packetMax struct {
+ line []byte
+ long bool // the current line passed maxPacketLine
+ best int64
+ found bool
+}
+
+func (p *packetMax) Write(b []byte) (int, error) {
+ for _, c := range b {
+ if c == '\n' {
+ p.endLine()
+ continue
+ }
+ if len(p.line) >= maxPacketLine {
+ p.long = true
+ continue
+ }
+ p.line = append(p.line, c)
+ }
+ return len(b), nil
+}
+
+func (p *packetMax) endLine() {
+ line, long := strings.TrimSpace(string(p.line)), p.long
+ p.line, p.long = p.line[:0], false
+ if long {
+ return
+ }
+ pts, dur, ok := strings.Cut(line, ",")
+ if !ok || strings.Contains(dur, ",") {
+ return
+ }
+ end, ok := parseMicros(pts)
+ if !ok {
+ return
+ }
+ if dur != "N/A" {
+ d, ok := parseMicros(dur)
+ if !ok || d < 0 {
+ return
+ }
+ end += d
+ }
+ if !p.found || end > p.best {
+ p.best, p.found = end, true
+ }
+}
+
+// result is the largest end seen, rounded up to the millisecond; 0 for
+// none (or none after zero). A last line without a newline counts.
+func (p *packetMax) result() int64 {
+ if len(p.line) > 0 || p.long {
+ p.endLine()
+ }
+ if !p.found || p.best <= 0 {
+ return 0
+ }
+ return microsToMS(p.best)
+}
diff --git a/internal/mediahandler/probe_test.go b/internal/mediahandler/probe_test.go
new file mode 100644
index 000000000..af193624f
--- /dev/null
+++ b/internal/mediahandler/probe_test.go
@@ -0,0 +1,722 @@
+package mediahandler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// fixture reads testdata/probe/<name>.json.
+func fixture(t testing.TB, name string) []byte {
+ t.Helper()
+ b, err := probeFixtures.ReadFile("testdata/probe/" + name + ".json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// TestParseProbeFixtures: the facts each fixture yields. The chrome
+// WebM has no duration in its header: parseProbe answers 0 and probe
+// runs the packet pass (TestDurationFromPacketsWhenTheHeaderHasNone).
+func TestParseProbeFixtures(t *testing.T) {
+ cases := map[string]probeFacts{
+ "iphone-hevc-hlg-portrait": {VideoIndex: 0, AudioIndex: 1, Width: 1920, Height: 1080, Rotation: -90, FPS: 30, HDR: true, VideoCodec: "hevc", AudioCodec: "aac", Channels: 2, DurationMS: 12345},
+ "dolby-vision-8-4": {VideoIndex: 0, AudioIndex: 1, Width: 3840, Height: 2160, Rotation: -90, FPS: 60, HDR: true, DolbyVisionProfile: 8, VideoCodec: "hevc", AudioCodec: "aac", Channels: 2, DurationMS: 8000},
+ "vfr-screen-recording": {VideoIndex: 0, AudioIndex: -1, Width: 2880, Height: 1800, FPS: 30000.0 / 1001, VideoCodec: "h264", DurationMS: 95200},
+ "chrome-webm-opus": {VideoIndex: -1, AudioIndex: 0, AudioCodec: "opus", Channels: 1, DurationMS: 0},
+ "dolby-vision-5": {VideoIndex: 0, AudioIndex: -1, Width: 1920, Height: 1080, FPS: 24000.0 / 1001, HDR: true, DolbyVisionProfile: 5, VideoCodec: "hevc", DurationMS: 20020},
+ "mp3-cover-art": {VideoIndex: -1, AudioIndex: 0, AudioCodec: "mp3", Channels: 2, DurationMS: 215485},
+ "m4a-cover-art": {VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 2, DurationMS: 180000},
+ "mka-cover-art": {VideoIndex: -1, AudioIndex: 1, AudioCodec: "flac", Channels: 2, DurationMS: 240500},
+ "h264-4k60": {VideoIndex: 0, AudioIndex: 1, Width: 3840, Height: 2160, FPS: 60, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 30000},
+ "h264-120fps": {VideoIndex: 0, AudioIndex: -1, Width: 1920, Height: 1080, FPS: 120, VideoCodec: "h264", DurationMS: 10000},
+ "bomb-30000": {VideoIndex: 0, AudioIndex: -1, Width: 30000, Height: 30000, FPS: 1, VideoCodec: "h264", DurationMS: 1000},
+ "lying-10h": {VideoIndex: 0, AudioIndex: -1, Width: 1280, Height: 720, FPS: 30, VideoCodec: "h264", DurationMS: 36000000},
+ "wav-mono": {VideoIndex: -1, AudioIndex: 0, AudioCodec: "pcm_s16le", Channels: 1, DurationMS: 62500},
+ "aac-6ch": {VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 6, DurationMS: 300011},
+ }
+ entries, err := probeFixtures.ReadDir("testdata/probe")
+ if err != nil {
+ t.Fatal(err)
+ }
+ seen := 0
+ for _, e := range entries {
+ name, ok := strings.CutSuffix(e.Name(), ".json")
+ if !ok {
+ continue
+ }
+ seen++
+ want, ok := cases[name]
+ if !ok {
+ t.Errorf("fixture %s has no expected facts", name)
+ continue
+ }
+ got, err := parseProbe(fixture(t, name))
+ if err != nil {
+ t.Errorf("%s: %v", name, err)
+ continue
+ }
+ if got != want {
+ t.Errorf("%s:\n got %+v\nwant %+v", name, got, want)
+ }
+ }
+ if seen != len(cases) {
+ t.Errorf("%d fixtures, %d expected", seen, len(cases))
+ }
+}
+
+// TestParseProbeRules: rotation from the display matrix, else the
+// rotate tag (whose sign is the other way about); FPS from the average
+// unless it is 0/0; HDR from the transfer or Dolby Vision side data;
+// duration from the format, else the longest taken stream.
+func TestParseProbeRules(t *testing.T) {
+ type c struct {
+ name string
+ json string
+ want func(probeFacts) bool
+ }
+ v := func(extra string) string {
+ return `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":640,"height":360,"avg_frame_rate":"25/1","r_frame_rate":"25/1"` + extra + `}],"format":{"duration":"1.5"}}`
+ }
+ cases := []c{
+ {"rotate tag 90 is matrix -90", v(`,"tags":{"rotate":"90"}`), func(f probeFacts) bool { return f.Rotation == -90 }},
+ {"rotate tag 270 is matrix 90", v(`,"tags":{"rotate":"270"}`), func(f probeFacts) bool { return f.Rotation == 90 }},
+ {"rotate tag 180", v(`,"tags":{"rotate":"180"}`), func(f probeFacts) bool { return f.Rotation == 180 }},
+ {"matrix wins over the tag", v(`,"tags":{"rotate":"90"},"side_data_list":[{"side_data_type":"Display Matrix","rotation":180}]`), func(f probeFacts) bool { return f.Rotation == 180 }},
+ {"matrix -180 is 180", v(`,"side_data_list":[{"side_data_type":"Display Matrix","rotation":-180}]`), func(f probeFacts) bool { return f.Rotation == 180 }},
+ {"matrix 270 is -90", v(`,"side_data_list":[{"side_data_type":"Display Matrix","rotation":270}]`), func(f probeFacts) bool { return f.Rotation == -90 }},
+ {"matrix 89.6 rounds to 90", v(`,"side_data_list":[{"side_data_type":"Display Matrix","rotation":89.6}]`), func(f probeFacts) bool { return f.Rotation == 90 }},
+ {"matrix 1e300 is a multiple of 90", v(`,"side_data_list":[{"side_data_type":"Display Matrix","rotation":1e300}]`), func(f probeFacts) bool { return f.Rotation%90 == 0 && f.Rotation > -180 && f.Rotation <= 180 }},
+ {"no rotation", v(``), func(f probeFacts) bool { return f.Rotation == 0 }},
+ {"pq is hdr", v(`,"color_transfer":"smpte2084"`), func(f probeFacts) bool { return f.HDR }},
+ {"hlg is hdr", v(`,"color_transfer":"arib-std-b67"`), func(f probeFacts) bool { return f.HDR }},
+ {"bt709 is not hdr", v(`,"color_transfer":"bt709"`), func(f probeFacts) bool { return !f.HDR }},
+ {"dolby vision side data is hdr", v(`,"side_data_list":[{"side_data_type":"DOVI configuration record","dv_profile":7}]`), func(f probeFacts) bool { return f.HDR && f.DolbyVisionProfile == 7 }},
+ {"duration from the format", v(``), func(f probeFacts) bool { return f.DurationMS == 1500 }},
+ {"sub-millisecond rounds up", `{"streams":[{"index":0,"codec_type":"audio","codec_name":"aac","channels":2}],"format":{"duration":"1.0001"}}`, func(f probeFacts) bool { return f.DurationMS == 1001 }},
+ {"no format duration: the longest taken stream", `{"streams":[{"index":0,"codec_type":"video","codec_name":"vp9","width":2,"height":2,"duration":"3.000000"},{"index":1,"codec_type":"audio","codec_name":"opus","duration":"4.250000"},{"index":2,"codec_type":"audio","codec_name":"opus","duration":"99.0"}],"format":{}}`, func(f probeFacts) bool { return f.DurationMS == 4250 }},
+ {"format duration N/A", `{"streams":[{"index":0,"codec_type":"audio","codec_name":"aac","duration":"2.0"}],"format":{"duration":"N/A"}}`, func(f probeFacts) bool { return f.DurationMS == 2000 }},
+ {"a huge duration saturates", `{"streams":[{"index":0,"codec_type":"audio","codec_name":"aac"}],"format":{"duration":"99999999999999999999999.5"}}`, func(f probeFacts) bool { return f.DurationMS == maxDurationMS }},
+ {"no streams", `{"streams":[],"format":{"duration":"1"}}`, func(f probeFacts) bool { return f.VideoIndex == -1 && f.AudioIndex == -1 }},
+ {"no stream list", `{"format":{"duration":"1"}}`, func(f probeFacts) bool { return f.VideoIndex == -1 && f.AudioIndex == -1 }},
+ {"second video ignored", `{"streams":[{"index":0,"codec_type":"video","codec_name":"av1","width":10,"height":20},{"index":1,"codec_type":"video","codec_name":"mpeg2video","width":30000,"height":30000}],"format":{"duration":"1"}}`, func(f probeFacts) bool { return f.VideoCodec == "av1" && f.Width == 10 }},
+ }
+ for _, c := range cases {
+ f, err := parseProbe([]byte(c.json))
+ if err != nil {
+ t.Errorf("%s: %v", c.name, err)
+ continue
+ }
+ if !c.want(f) {
+ t.Errorf("%s: %+v", c.name, f)
+ }
+ }
+ // What parseProbe refuses: it is ffprobe's output, but ffprobe has
+ // read hostile input.
+ for name, j := range map[string]string{
+ "not json": `ffprobe: error`,
+ "trailing data": `{"streams":[]} {}`,
+ "negative width": `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":-1,"height":2}]}`,
+ "negative channels": `{"streams":[{"index":0,"codec_type":"audio","codec_name":"aac","channels":-2}]}`,
+ "negative index": `{"streams":[{"index":-1,"codec_type":"audio","codec_name":"aac"}]}`,
+ "negative duration": `{"streams":[],"format":{"duration":"-5.0"}}`,
+ "nan duration": `{"streams":[],"format":{"duration":"NaN"}}`,
+ "inf duration": `{"streams":[],"format":{"duration":"Inf"}}`,
+ "exponent duration": `{"streams":[],"format":{"duration":"1e9"}}`,
+ "numeric duration": `{"streams":[],"format":{"duration":12}}`,
+ "bad stream dur": `{"streams":[{"index":0,"codec_type":"audio","codec_name":"aac","duration":"x"}],"format":{}}`,
+ "negative frame rate": `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":2,"height":2,"avg_frame_rate":"-30/1"}]}`,
+ "zero denominator": `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":2,"height":2,"avg_frame_rate":"30/0"}]}`,
+ "rational garbage": `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":2,"height":2,"avg_frame_rate":"thirty"}]}`,
+ "bad rotate tag": `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":2,"height":2,"tags":{"rotate":"up"}}]}`,
+ "a top-level array": `[]`,
+ } {
+ if f, err := parseProbe([]byte(j)); err == nil {
+ t.Errorf("%s: parseProbe accepted it: %+v", name, f)
+ }
+ }
+}
+
+// TestFrameRateUsesTheAverage (Review Focus 2): a VFR screen recording
+// whose r_frame_rate is 120/1 averages 29.97 and converts; a true
+// 120 fps source is refused; r_frame_rate counts only when the average
+// is 0/0.
+func TestFrameRateUsesTheAverage(t *testing.T) {
+ l := media.JobLimits{GrantedMS: 600000, GrantedBy: grantedByClass, MaxMS: 7200000, MaxHiMS: 1800000}
+ vfr, err := parseProbe(fixture(t, "vfr-screen-recording"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := check(vfr, media.PresetVideo720p, l); err != nil {
+ t.Errorf("VFR recording (avg 29.97, r 120): %v, want it to convert", err)
+ }
+ fast, err := parseProbe(fixture(t, "h264-120fps"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code := codeOf(check(fast, media.PresetVideo720p, l)); code != media.CodeSourceFrameRate {
+ t.Errorf("true 120 fps: %s, want source_frame_rate", code)
+ }
+ for _, c := range []struct {
+ avg, r string
+ want float64
+ }{
+ {"0/0", "120/1", 120},
+ {"0/0", "0/0", 0},
+ {"", "24/1", 24},
+ {"30000/1001", "120/1", 30000.0 / 1001},
+ {"60/1", "90000/1", 60},
+ } {
+ j := `{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":2,"height":2,"avg_frame_rate":"` + c.avg + `","r_frame_rate":"` + c.r + `"}]}`
+ f, err := parseProbe([]byte(j))
+ if err != nil || f.FPS != c.want {
+ t.Errorf("avg %q r %q: FPS %v, %v; want %v", c.avg, c.r, f.FPS, err, c.want)
+ }
+ }
+}
+
+// TestAttachedPictureIsNotVideo (Review Focus 4, preflight F17): an M4A
+// or MKA with cover art is no_video under video-720p, not
+// unsupported_video_codec; under audio-aac it and the MP3 convert. (An
+// MP3 under video-720p never gets here: TestSniffTable.)
+func TestAttachedPictureIsNotVideo(t *testing.T) {
+ l := media.JobLimits{GrantedMS: 7200000, GrantedBy: grantedByClass, MaxMS: 28800000}
+ for _, name := range []string{"m4a-cover-art", "mka-cover-art"} {
+ f, err := parseProbe(fixture(t, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code := codeOf(check(f, media.PresetVideo720p, l)); code != media.CodeNoVideo {
+ t.Errorf("%s under video-720p: %s, want no_video", name, code)
+ }
+ }
+ for _, name := range []string{"m4a-cover-art", "mka-cover-art", "mp3-cover-art"} {
+ f, err := parseProbe(fixture(t, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := check(f, media.PresetAudioAAC, l); err != nil {
+ t.Errorf("%s under audio-aac: %v, want it to convert", name, err)
+ }
+ }
+}
+
+// limitsFor are generous limits for preset: the checks under test are
+// the only ones that can fail.
+func limitsFor(preset string) media.JobLimits {
+ if preset == media.PresetAudioAAC {
+ return media.JobLimits{GrantedMS: 28800000, GrantedBy: grantedByClass, MaxMS: 28800000}
+ }
+ return media.JobLimits{GrantedMS: 7200000, GrantedBy: grantedByClass, MaxMS: 7200000, MaxHiMS: 1800000}
+}
+
+// goodVideo passes every video-720p check.
+func goodVideo() probeFacts {
+ return probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 1920, Height: 1080, FPS: 30, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 60000}
+}
+
+// TestCheckTable: each check alone, at its boundary.
+func TestCheckTable(t *testing.T) {
+ video, audio := media.PresetVideo720p, media.PresetAudioAAC
+ type c struct {
+ name string
+ preset string
+ edit func(*probeFacts, *media.JobLimits)
+ want string
+ }
+ cases := []c{
+ {"good video", video, func(*probeFacts, *media.JobLimits) {}, ""},
+ {"video without audio", video, func(f *probeFacts, _ *media.JobLimits) { f.AudioIndex, f.AudioCodec = -1, "" }, ""},
+ {"no video", video, func(f *probeFacts, _ *media.JobLimits) { f.VideoIndex = -1 }, media.CodeNoVideo},
+ {"no audio", audio, func(f *probeFacts, _ *media.JobLimits) { f.AudioIndex = -1 }, media.CodeNoAudio},
+ {"audio ignores the video", audio, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec, f.Width, f.FPS = "mpeg4", 30000, 500 }, ""},
+ {"mpeg4 video", video, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec = "mpeg4" }, media.CodeUnsupportedVideoCodec},
+ {"prores video", video, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec = "prores" }, media.CodeUnsupportedVideoCodec},
+ {"ac3 audio under video", video, func(f *probeFacts, _ *media.JobLimits) { f.AudioCodec = "ac3" }, media.CodeUnsupportedAudioCodec},
+ {"alac audio", audio, func(f *probeFacts, _ *media.JobLimits) { f.AudioCodec = "alac" }, media.CodeUnsupportedAudioCodec},
+ {"4096 wide", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = media.MaxSide, 2000 }, ""},
+ {"4097 wide", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = media.MaxSide+1, 100 }, media.CodeSourceDimensions},
+ {"4097 tall", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 100, media.MaxSide+1 }, media.CodeSourceDimensions},
+ {"3840x2160 exactly", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 3840, 2160 }, ""},
+ {"2160x3840 exactly", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 2160, 3840 }, ""},
+ {"4096x2026: one pixel row over", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 4096, 2026 }, media.CodeSourceDimensions},
+ {"4096x2025 fits", video, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 4096, 2025 }, ""},
+ {"zero width", video, func(f *probeFacts, _ *media.JobLimits) { f.Width = 0 }, media.CodeUnreadable},
+ {"negative height", video, func(f *probeFacts, _ *media.JobLimits) { f.Height = -1080 }, media.CodeUnreadable},
+ {"60 fps", video, func(f *probeFacts, _ *media.JobLimits) { f.FPS = media.MaxFPS }, ""},
+ {"60.01 fps", video, func(f *probeFacts, _ *media.JobLimits) { f.FPS = 60.01 }, media.CodeSourceFrameRate},
+ {"negative fps", video, func(f *probeFacts, _ *media.JobLimits) { f.FPS = -1 }, media.CodeUnreadable},
+ {"no duration", video, func(f *probeFacts, _ *media.JobLimits) { f.DurationMS = 0 }, media.CodeUnreadable},
+ {"negative duration", audio, func(f *probeFacts, _ *media.JobLimits) { f.DurationMS = -1 }, media.CodeUnreadable},
+ {"at the maximum", video, func(f *probeFacts, l *media.JobLimits) { f.DurationMS = l.MaxMS }, ""},
+ {"over the maximum", video, func(f *probeFacts, l *media.JobLimits) { f.DurationMS = l.MaxMS + 1 }, media.CodeSourceTooLong},
+ {"1080p portrait uses the maximum", video, func(f *probeFacts, l *media.JobLimits) {
+ f.Width, f.Height, f.DurationMS = 1080, 1920, l.MaxHiMS+1
+ }, ""},
+ {"above 1080p uses the hi maximum", video, func(f *probeFacts, l *media.JobLimits) {
+ f.Width, f.Height, f.DurationMS = 2560, 1440, l.MaxHiMS+1
+ }, media.CodeSourceTooLong},
+ {"above 1080p at the hi maximum", video, func(f *probeFacts, l *media.JobLimits) {
+ f.Width, f.Height, f.DurationMS = 1440, 2560, l.MaxHiMS
+ }, ""},
+ {"1920x1081 is above 1080p", video, func(f *probeFacts, l *media.JobLimits) {
+ f.Width, f.Height, f.DurationMS = 1920, 1081, l.MaxHiMS+1
+ }, media.CodeSourceTooLong},
+ {"audio has no hi maximum", audio, func(f *probeFacts, l *media.JobLimits) {
+ f.Width, f.Height, f.DurationMS = 3840, 2160, l.MaxMS
+ }, ""},
+ {"over the class grant", video, func(f *probeFacts, l *media.JobLimits) { l.GrantedMS = 600000; f.DurationMS = 600001 }, media.CodeNeedsLongClass},
+ {"at the class grant", video, func(f *probeFacts, l *media.JobLimits) { l.GrantedMS = 600000; f.DurationMS = 600000 }, ""},
+ {"over the allowance", audio, func(f *probeFacts, l *media.JobLimits) {
+ l.GrantedMS, l.GrantedBy = 60000, "allowance"
+ f.DurationMS = 60001
+ }, media.CodeAllowanceExceeded},
+ {"an unknown granter is the allowance", audio, func(f *probeFacts, l *media.JobLimits) {
+ l.GrantedMS, l.GrantedBy = 60000, ""
+ f.DurationMS = 60001
+ }, media.CodeAllowanceExceeded},
+ {"dolby vision 5 converts by default", video, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec, f.HDR, f.DolbyVisionProfile = "hevc", true, 5 }, ""},
+ {"unknown preset", "video-4k", func(*probeFacts, *media.JobLimits) {}, media.CodeEngineFailed},
+ }
+ for _, pc := range []string{"pcm_u8", "pcm_s16le", "pcm_s16be", "pcm_s24le", "pcm_s24be", "pcm_s32le", "pcm_s32be", "pcm_f32le", "pcm_f32be", "pcm_f64le", "pcm_f64be", "pcm_alaw", "pcm_mulaw", "aac", "opus", "vorbis", "mp3", "flac"} {
+ cases = append(cases, c{"audio " + pc, audio, func(f *probeFacts, _ *media.JobLimits) { f.AudioCodec = pc }, ""})
+ }
+ // Preflight F18: only the decoder allow-list's PCM names.
+ for _, pc := range []string{"pcm_s16le_planar", "pcm_bluray", "pcm_s8", "pcm_dvd", "pcm_s24daud", "pcm_", "pcm_f16le", "mp3float", "libopus"} {
+ cases = append(cases, c{"audio " + pc, audio, func(f *probeFacts, _ *media.JobLimits) { f.AudioCodec = pc }, media.CodeUnsupportedAudioCodec})
+ }
+ for _, vc := range []string{"h264", "hevc", "vp8", "vp9", "av1"} {
+ cases = append(cases, c{"video " + vc, video, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec = vc }, ""})
+ }
+ for _, vc := range []string{"libdav1d", "mjpeg", "png", "H264", ""} {
+ cases = append(cases, c{"video " + vc, video, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec = vc }, media.CodeUnsupportedVideoCodec})
+ }
+ for _, c := range cases {
+ f, l := goodVideo(), limitsFor(c.preset)
+ if c.preset == audio {
+ f = probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 2, DurationMS: 60000}
+ }
+ c.edit(&f, &l)
+ got := ""
+ if err := check(f, c.preset, l); err != nil {
+ got = codeOf(err)
+ }
+ if got != c.want {
+ t.Errorf("%s: check = %q, want %q (%+v)", c.name, got, c.want, f)
+ }
+ }
+}
+
+// TestDolbyVision5RefusedWhenTheSpikeSaysSo: with refuseDolbyVision5
+// set, profile 5 is unsupported_hdr, and nothing else is.
+func TestDolbyVision5RefusedWhenTheSpikeSaysSo(t *testing.T) {
+ old := refuseDolbyVision5
+ refuseDolbyVision5 = true
+ t.Cleanup(func() { refuseDolbyVision5 = old })
+ dv5, err := parseProbe(fixture(t, "dolby-vision-5"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code := codeOf(check(dv5, media.PresetVideo720p, limitsFor(media.PresetVideo720p))); code != media.CodeUnsupportedHDR {
+ t.Errorf("dolby vision 5: %s, want unsupported_hdr", code)
+ }
+ dv8, err := parseProbe(fixture(t, "dolby-vision-8-4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := check(dv8, media.PresetVideo720p, limitsFor(media.PresetVideo720p)); err != nil {
+ t.Errorf("dolby vision 8.4: %v, want it to convert", err)
+ }
+}
+
+// TestCheckOrder: a source failing several checks reports the first in
+// spec §6's order. Each row fails its own check and every later one.
+func TestCheckOrder(t *testing.T) {
+ worst := func() (probeFacts, media.JobLimits) {
+ // Every check fails: no audio stream, wrong codecs, too big,
+ // too fast, too long for everything, Dolby Vision 5.
+ return probeFacts{VideoIndex: -1, AudioIndex: 2, Width: 30000, Height: 30000, FPS: 240, VideoCodec: "mpeg4", AudioCodec: "ac3", DurationMS: 99999999, DolbyVisionProfile: 5, HDR: true},
+ media.JobLimits{GrantedMS: 600000, GrantedBy: grantedByClass, MaxMS: 7200000, MaxHiMS: 1800000}
+ }
+ old := refuseDolbyVision5
+ refuseDolbyVision5 = true
+ t.Cleanup(func() { refuseDolbyVision5 = old })
+ steps := []struct {
+ want string
+ fix func(*probeFacts, *media.JobLimits)
+ }{
+ {media.CodeNoVideo, func(f *probeFacts, _ *media.JobLimits) { f.VideoIndex = 0 }},
+ {media.CodeUnsupportedVideoCodec, func(f *probeFacts, _ *media.JobLimits) { f.VideoCodec = "hevc" }},
+ {media.CodeUnsupportedAudioCodec, func(f *probeFacts, _ *media.JobLimits) { f.AudioCodec = "aac" }},
+ {media.CodeSourceDimensions, func(f *probeFacts, _ *media.JobLimits) { f.Width, f.Height = 3840, 2160 }},
+ {media.CodeSourceFrameRate, func(f *probeFacts, _ *media.JobLimits) { f.FPS = 30 }},
+ {media.CodeSourceTooLong, func(f *probeFacts, _ *media.JobLimits) { f.DurationMS = 1800000 }},
+ {media.CodeNeedsLongClass, func(f *probeFacts, _ *media.JobLimits) { f.DurationMS = 600000 }},
+ {media.CodeUnsupportedHDR, func(f *probeFacts, _ *media.JobLimits) { f.DolbyVisionProfile = 8 }},
+ {"", nil},
+ }
+ f, l := worst()
+ for _, s := range steps {
+ got := ""
+ if err := check(f, media.PresetVideo720p, l); err != nil {
+ got = codeOf(err)
+ }
+ if got != s.want {
+ t.Fatalf("check = %q, want %q (%+v)", got, s.want, f)
+ }
+ if s.fix != nil {
+ s.fix(&f, &l)
+ }
+ }
+}
+
+// TestLyingDurationIsTooLong: a header claiming 10 hours over a
+// 4-second stream is believed (the header is what the job is held to),
+// and is source_too_long, not converted.
+func TestLyingDurationIsTooLong(t *testing.T) {
+ f, err := parseProbe(fixture(t, "lying-10h"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code := codeOf(check(f, media.PresetVideo720p, limitsFor(media.PresetVideo720p))); code != media.CodeSourceTooLong {
+ t.Errorf("lying 10 h: %s, want source_too_long", code)
+ }
+}
+
+// TestBombIsDimensions: a 30000x30000 header is source_dimensions
+// before anything decodes it; so are a side over MaxSide and a frame
+// over MaxDimensions' pixels.
+func TestBombIsDimensions(t *testing.T) {
+ f, err := parseProbe(fixture(t, "bomb-30000"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code := codeOf(check(f, media.PresetVideo720p, limitsFor(media.PresetVideo720p))); code != media.CodeSourceDimensions {
+ t.Errorf("30000x30000: %s, want source_dimensions", code)
+ }
+ if maxPixels != 3840*2160 {
+ t.Errorf("maxPixels = %d, want media.MaxDimensions' 3840x2160", maxPixels)
+ }
+ // The 4K60 fixture is at every video limit, and converts.
+ ok, err := parseProbe(fixture(t, "h264-4k60"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := check(ok, media.PresetVideo720p, limitsFor(media.PresetVideo720p)); err != nil {
+ t.Errorf("4K60: %v", err)
+ }
+}
+
+// FuzzParseProbe: arbitrary bytes never panic, and never yield facts
+// that pass check with a negative or zero size, frame rate or duration,
+// or a negative stream index.
+func FuzzParseProbe(f *testing.F) {
+ entries, err := probeFixtures.ReadDir("testdata/probe")
+ if err != nil {
+ f.Fatal(err)
+ }
+ for _, e := range entries {
+ if b, err := probeFixtures.ReadFile("testdata/probe/" + e.Name()); err == nil {
+ f.Add(b)
+ }
+ }
+ f.Add([]byte(`{"streams":[{"index":0,"codec_type":"video","codec_name":"h264","width":-1,"height":-1}],"format":{"duration":"-1"}}`))
+ f.Fuzz(func(t *testing.T, b []byte) {
+ facts, err := parseProbe(b)
+ if err != nil {
+ return
+ }
+ if facts.Channels < 0 || facts.DurationMS < 0 || facts.FPS < 0 || facts.Width < 0 || facts.Height < 0 {
+ t.Fatalf("parseProbe yielded %+v", facts)
+ }
+ for _, preset := range []string{media.PresetVideo720p, media.PresetAudioAAC} {
+ if check(facts, preset, limitsFor(preset)) != nil {
+ continue
+ }
+ if facts.DurationMS <= 0 {
+ t.Fatalf("%s: check passed %+v", preset, facts)
+ }
+ if preset == media.PresetVideo720p && (facts.VideoIndex < 0 || facts.Width <= 0 || facts.Height <= 0 || facts.FPS < 0) {
+ t.Fatalf("%s: check passed %+v", preset, facts)
+ }
+ if preset == media.PresetAudioAAC && facts.AudioIndex < 0 {
+ t.Fatalf("%s: check passed %+v", preset, facts)
+ }
+ }
+ })
+}
+
+// needChildren skips a test that starts processes where runChild does
+// not (procs_other.go): the handler runs only on Linux.
+func needChildren(t *testing.T) {
+ t.Helper()
+ if runtime.GOOS != "linux" {
+ t.Skip("runChild is Linux-only")
+ }
+}
+
+// TestProbeArgs: ffprobe runs with the demuxer forced, the protocol and
+// decoder allow-lists, drefs off for mov, -loglevel error (preflight
+// F19: no source metadata reaches stderr) and the fixed input path, and
+// with an environment of its own.
+func TestProbeArgs(t *testing.T) {
+ needChildren(t)
+ t.Setenv(media.PayloadEnv, "a payload that must not reach the child")
+ cfg, record := fakeConfig(t, "probe-iphone-hevc-hlg-portrait")
+ if _, err := probe(context.Background(), cfg, "mov"); err != nil {
+ t.Fatal(err)
+ }
+ cfg2, record2 := fakeConfig(t, "probe-chrome-webm-opus")
+ if _, err := probe(context.Background(), cfg2, "matroska"); err != nil {
+ t.Fatal(err)
+ }
+ runs := append(fakeRuns(t, record), fakeRuns(t, record2)...)
+ if len(runs) != 3 {
+ t.Fatalf("%d ffprobe runs, want 3 (the mov, the webm and its packet pass)", len(runs))
+ }
+ want := func(demuxer string, cfg Config, extra ...string) []string {
+ a := []string{"-hide_banner", "-loglevel", "error", "-protocol_whitelist", "file", "-f", demuxer}
+ if demuxer == "mov" {
+ a = append(a, "-enable_drefs", "0")
+ }
+ a = append(a, "-codec_whitelist", "h264,hevc,vp8,vp9,av1,libdav1d,aac,opus,libopus,vorbis,libvorbis,mp3,mp3float,flac,pcm_u8,pcm_s16le,pcm_s16be,pcm_s24le,pcm_s24be,pcm_s32le,pcm_s32be,pcm_f32le,pcm_f32be,pcm_f64le,pcm_f64be,pcm_alaw,pcm_mulaw")
+ a = append(a, extra...)
+ return append(a, "-i", filepath.Join(cfg.Scratch, "in", "source"))
+ }
+ for i, w := range [][]string{
+ want("mov", cfg, "-show_format", "-show_streams", "-of", "json"),
+ want("matroska", cfg2, "-show_format", "-show_streams", "-of", "json"),
+ want("matroska", cfg2, "-select_streams", "0", "-show_entries", "packet=pts_time,duration_time", "-of", "csv=p=0"),
+ } {
+ if !slices.Equal(runs[i].Args, w) {
+ t.Errorf("run %d args:\n got %q\nwant %q", i, runs[i].Args, w)
+ }
+ for _, kv := range runs[i].Env {
+ if strings.Contains(kv, "payload") {
+ t.Errorf("run %d: the child's environment holds %q", i, kv)
+ }
+ }
+ }
+}
+
+// TestDurationFromPacketsWhenTheHeaderHasNone (Review Focus 3): a
+// Chrome MediaRecorder WebM with no duration anywhere in its header
+// gets one from a second ffprobe pass over the chosen stream's packets,
+// the largest pts+duration (a packet without a duration counts its pts;
+// lines that do not parse are skipped), and converts.
+func TestDurationFromPacketsWhenTheHeaderHasNone(t *testing.T) {
+ needChildren(t)
+ cfg, record := fakeConfig(t, "probe-chrome-webm-opus")
+ f, err := probe(context.Background(), cfg, "matroska")
+ if err != nil {
+ t.Fatal(err)
+ }
+ // 5.980000 + 0.020000 = 6.000000 s.
+ if f.DurationMS != 6000 {
+ t.Errorf("DurationMS = %d, want 6000", f.DurationMS)
+ }
+ if err := check(f, media.PresetAudioAAC, limitsFor(media.PresetAudioAAC)); err != nil {
+ t.Errorf("check: %v, want it to convert", err)
+ }
+ if n := len(fakeRuns(t, record)); n != 2 {
+ t.Errorf("%d ffprobe runs, want 2", n)
+ }
+ // A source whose header has a duration gets one pass only.
+ cfg, record = fakeConfig(t, "probe-wav-mono")
+ if _, err := probe(context.Background(), cfg, "wav"); err != nil {
+ t.Fatal(err)
+ }
+ if n := len(fakeRuns(t, record)); n != 1 {
+ t.Errorf("%d ffprobe runs for a source with a duration, want 1", n)
+ }
+}
+
+// TestPacketDuration: the packet pass's parser.
+func TestPacketDuration(t *testing.T) {
+ for _, c := range []struct {
+ in string
+ want int64
+ }{
+ {"0.000000,0.020000\n1.000000,0.020000\n", 1020},
+ {"1.0,N/A\n0.5,0.1\n", 1000},
+ {"-0.021333,0.021333\n0.000000,0.021333\n", 22},
+ {"garbage\n2.0,0.5\nNaN,1\n1e9,1\n", 2500},
+ {"2.0,0.5", 2500}, // no final newline
+ {"3.0,0.25,side\n", 0},
+ {strings.Repeat("9", 300) + ",1\n1.0,0.0\n", 1000}, // an overlong line is skipped
+ {"", 0},
+ {"N/A,N/A\n", 0},
+ } {
+ var p packetMax
+ if _, err := p.Write([]byte(c.in)); err != nil {
+ t.Fatal(err)
+ }
+ if got := p.result(); got != c.want {
+ t.Errorf("%q: %d, want %d", c.in, got, c.want)
+ }
+ }
+ // Written a byte at a time, the same.
+ var p packetMax
+ for _, b := range []byte("0.5,0.5\n7.25,0.75\n") {
+ _, _ = p.Write([]byte{b})
+ }
+ if got := p.result(); got != 8000 {
+ t.Errorf("bytewise: %d, want 8000", got)
+ }
+}
+
+// TestProbeFailuresAreUnreadable: ffprobe failing, its output past
+// 1 MiB or not JSON, and a header without a duration whose packets give
+// none, are each unreadable. A missing ffprobe is engine_failed.
+func TestProbeFailuresAreUnreadable(t *testing.T) {
+ needChildren(t)
+ for _, scenario := range []string{"fail", "flood", "env", "probe-chrome-webm-opus-nopackets"} {
+ cfg, _ := fakeConfig(t, scenario)
+ if scenario == "probe-chrome-webm-opus-nopackets" {
+ // The JSON of the webm, whose packet pass then fails.
+ cfg.extraEnv = []string{fakeEnv + "=probe-chrome-webm-opus", fakeNoPacketsEnv + "=1"}
+ }
+ if _, err := probe(context.Background(), cfg, "matroska"); codeOf(err) != media.CodeUnreadable {
+ t.Errorf("%s: %s, want unreadable", scenario, codeOf(err))
+ }
+ }
+ cfg, _ := fakeConfig(t, "probe-wav-mono")
+ cfg.FFprobe = filepath.Join(t.TempDir(), "no-ffprobe")
+ if _, err := probe(context.Background(), cfg, "wav"); codeOf(err) != media.CodeEngineFailed {
+ t.Errorf("missing ffprobe: %s, want engine_failed", codeOf(err))
+ }
+}
+
+// TestProbeTimeoutIsUnreadable: an ffprobe that never finishes is
+// stopped at the probe's timeout (60 s; 100 ms here) and is unreadable.
+// The task itself ending is not the probe's failure: it answers the
+// context's error.
+func TestProbeTimeoutIsUnreadable(t *testing.T) {
+ needChildren(t)
+ if probeTimeout != 60*time.Second {
+ t.Errorf("probeTimeout = %s, want 60 s (spec §6)", probeTimeout)
+ }
+ cfg, _ := fakeConfig(t, "block")
+ cfg.probeTimeout = 100 * time.Millisecond
+ var logs []string
+ cfg.Logf = func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) }
+ start := time.Now()
+ _, err := probe(context.Background(), cfg, "mov")
+ if codeOf(err) != media.CodeUnreadable {
+ t.Errorf("timeout: %s, want unreadable", codeOf(err))
+ }
+ if !slices.Equal(logs, []string{"codec: ffprobe did not finish in time"}) {
+ t.Errorf("timeout logs %q", logs)
+ }
+ if d := time.Since(start); d > 10*time.Second {
+ t.Errorf("probe took %s to stop a blocked ffprobe", d)
+ }
+
+ cfg.probeTimeout = time.Hour
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan error, 1)
+ go func() { _, err := probe(ctx, cfg, "mov"); done <- err }()
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("task stopped: %v, want context.Canceled", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("probe did not return within 10 s of its context ending")
+ }
+}
+
+// TestProbeLogsTheStderrTail: a failing ffprobe's stderr reaches the
+// log on one line, quoted, at most 64 KiB, its last lines kept.
+func TestProbeLogsTheStderrTail(t *testing.T) {
+ needChildren(t)
+ cfg, _ := fakeConfig(t, "noisy")
+ var logs []string
+ cfg.Logf = func(format string, args ...any) { logs = append(logs, strings.TrimSpace(fmt.Sprintf(format, args...))) }
+ if _, err := probe(context.Background(), cfg, "mov"); codeOf(err) != media.CodeUnreadable {
+ t.Fatalf("%s, want unreadable", codeOf(err))
+ }
+ if len(logs) != 1 {
+ t.Fatalf("logs %q, want one line", logs)
+ }
+ l := logs[0]
+ if strings.Contains(l, "\n") || len(l) > stderrTailBytes*2+100 {
+ t.Errorf("log line: %d bytes, newline %v", len(l), strings.Contains(l, "\n"))
+ }
+ if !strings.Contains(l, "line 0999") || strings.Contains(l, "line 0000") {
+ t.Errorf("the tail is not the end of stderr: %.200q", l)
+ }
+}
+
+// TestRunInspectsTheSource: Run sniffs the downloaded source and probes
+// and checks it. A source that is not a family is unsupported_container
+// and ffprobe never runs; a bomb is source_dimensions.
+func TestRunInspectsTheSource(t *testing.T) {
+ needChildren(t)
+ for _, c := range []struct {
+ name, scenario string
+ head []byte
+ want string
+ probes int
+ }{
+ {"a pdf", "probe-h264-4k60", []byte("%PDF-1.7\n"), "codec: failed: unsupported_container", 0},
+ {"an mp3 under video-720p", "probe-mp3-cover-art", headID3, "codec: failed: unsupported_container", 0},
+ {"a bomb", "probe-bomb-30000", headMP4, "codec: failed: source_dimensions", 1},
+ {"cover art only", "probe-m4a-cover-art", headM4A, "codec: failed: no_video", 1},
+ {"a good 4K60", "probe-h264-4k60", headMP4, "codec: source downloaded; conversion is not built in this image", 1},
+ } {
+ h := newHarness(t)
+ data := append(append([]byte(nil), c.head...), randomBytes(t, 1024)...)
+ p := h.s.payload(t, media.PresetVideo720p, data, mib)
+ p.Limits.MaxHiMS = 1800000
+ fc, record := fakeConfig(t, c.scenario)
+ cfg := h.cfg
+ cfg.Scratch = t.TempDir()
+ cfg.FFprobe, cfg.extraEnv = fc.FFprobe, fc.extraEnv
+ if code := Run(context.Background(), cfg, marshal(t, p)); code != media.ExitFailed {
+ t.Errorf("%s: Run = %d", c.name, code)
+ }
+ if logs := h.Logs(); !slices.Contains(logs, c.want) {
+ t.Errorf("%s: logs %q, want %q", c.name, logs, c.want)
+ }
+ if n := len(fakeRuns(t, record)); n != c.probes {
+ t.Errorf("%s: ffprobe ran %d times, want %d", c.name, n, c.probes)
+ }
+ }
+}
+
+// TestCodecWhitelistMatchesTheChecks: every codec check accepts
+// decodes under the decoder allow-list (codec names, which name the
+// decoders here except mp3float, libdav1d, libopus and libvorbis).
+func TestCodecWhitelistMatchesTheChecks(t *testing.T) {
+ list := strings.Split(codecWhitelist, ",")
+ for name := range videoCodecs {
+ if !slices.Contains(list, name) {
+ t.Errorf("video codec %s is not in the decoder allow-list", name)
+ }
+ }
+ for name := range audioCodecs {
+ if !slices.Contains(list, name) {
+ t.Errorf("audio codec %s is not in the decoder allow-list", name)
+ }
+ }
+ for _, name := range list {
+ if strings.HasPrefix(name, "pcm_") && !audioCodecs[name] {
+ t.Errorf("allow-listed %s is refused by check", name)
+ }
+ }
+ if _, err := os.Stat("testdata/probe/stand-ins.txt"); err != nil {
+ t.Errorf("the stand-in fixtures are not marked: %v", err)
+ }
+}
diff --git a/internal/mediahandler/procs.go b/internal/mediahandler/procs.go
new file mode 100644
index 000000000..ab3f2af60
--- /dev/null
+++ b/internal/mediahandler/procs.go
@@ -0,0 +1,63 @@
+package mediahandler
+
+import (
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+// stderrTailBytes is how much of a child's stderr runChild keeps for
+// the task's log: the last 64 KiB.
+const stderrTailBytes = 64 << 10
+
+// reapBudget bounds runChild's cleanup: from the SIGKILL to the last
+// descendant reaped. Past it the run is engine_failed.
+const reapBudget = 5 * time.Second
+
+// childEnv is every child's whole environment: a fixed PATH and locale,
+// and HOME and TMPDIR in the scratch's tmp, so nothing a child writes
+// on its own lands outside the scratch. Nothing of the handler's own
+// environment is passed on (the codec has already removed the payload
+// from it, but credentials or a proxy set by a runner must not reach
+// ffmpeg either). Config.extraEnv is for tests only.
+func childEnv(cfg Config) []string {
+ tmp := filepath.Join(cfg.Scratch, "tmp")
+ env := []string{"PATH=/usr/bin:/bin", "LC_ALL=C", "HOME=" + tmp, "TMPDIR=" + tmp}
+ return append(env, cfg.extraEnv...)
+}
+
+// tail keeps the last n bytes written to it. It is safe to read while
+// a drain goroutine still writes (runChild's early returns).
+type tail struct {
+ mu sync.Mutex
+ n int
+ buf []byte
+}
+
+func newTail(n int) *tail { return &tail{n: n} }
+
+func (t *tail) Write(p []byte) (int, error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if len(p) >= t.n {
+ t.buf = append(t.buf[:0], p[len(p)-t.n:]...)
+ return len(p), nil
+ }
+ t.buf = append(t.buf, p...)
+ if len(t.buf) > 2*t.n {
+ // Trim now and then, not on every write.
+ t.buf = append(t.buf[:0], t.buf[len(t.buf)-t.n:]...)
+ }
+ return len(p), nil
+}
+
+// Bytes answers a copy of the last n bytes.
+func (t *tail) Bytes() []byte {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ b := t.buf
+ if len(b) > t.n {
+ b = b[len(b)-t.n:]
+ }
+ return append([]byte(nil), b...)
+}
diff --git a/internal/mediahandler/procs_linux.go b/internal/mediahandler/procs_linux.go
new file mode 100644
index 000000000..43cb5e186
--- /dev/null
+++ b/internal/mediahandler/procs_linux.go
@@ -0,0 +1,275 @@
+//go:build linux
+
+package mediahandler
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "os"
+ "os/exec"
+ "runtime"
+ "strconv"
+ "sync"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// childMu makes runChild one at a time: its cleanup kills and reaps
+// every child of the handler, so a second run alongside would be
+// killed by the first's cleanup.
+var childMu sync.Mutex
+
+// runChild runs one ffmpeg or ffprobe (name, an absolute path) with
+// args in dir, its stdout discarded, and answers the last
+// stderrTailBytes of its stderr for the task's log. See runChildTo.
+func runChild(ctx context.Context, cfg Config, name string, args []string, dir string) (stderrTail []byte, err error) {
+ return runChildTo(ctx, cfg, name, args, dir, io.Discard)
+}
+
+// runChildTo is runChild with the child's stdout copied to stdout.
+//
+// The child, and everything it starts, is dead and reaped when this
+// returns, so nothing reads /scratch/out while a descendant could still
+// write there (spec §6):
+//
+// - the handler is a child subreaper (PR_SET_CHILD_SUBREAPER), so a
+// descendant whose parent dies, even one that called setsid, is
+// re-parented to the handler and not to the container's init;
+// - the child has its own process group, gets SIGKILL if the thread
+// that started it ends (Pdeathsig; that thread is locked to this
+// goroutine from Start to the end of the wait, preflight F35), and
+// has an explicit, minimal environment (childEnv) and no stdin;
+// - when it exits or ctx ends: SIGKILL to its process group (the
+// group cannot be reused while the unreaped child holds it), the
+// direct child reaped by cmd.Wait first (F35), then, repeatedly,
+// SIGKILL to every remaining child of the handler (from
+// /proc/*/stat) and wait4(-1, WNOHANG), until ECHILD; all of it
+// within reapBudget, else engine_failed.
+//
+// It answers nil for exit 0; ctx's error when ctx ended first;
+// unreadable for any other exit; engine_failed when the child cannot
+// start or the cleanup fails. Errors carry no argument: the reasons
+// for engine_failed go to cfg.Logf.
+func runChildTo(ctx context.Context, cfg Config, name string, args []string, dir string, stdout io.Writer) (stderrTail []byte, err error) {
+ childMu.Lock()
+ defer childMu.Unlock()
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); err != nil {
+ return nil, childFailed(cfg, "cannot become a subreaper", err)
+ }
+ outR, outW, err := os.Pipe()
+ if err != nil {
+ return nil, childFailed(cfg, "no pipe", err)
+ }
+ errR, errW, err := os.Pipe()
+ if err != nil {
+ outR.Close()
+ outW.Close()
+ return nil, childFailed(cfg, "no pipe", err)
+ }
+ cmd := &exec.Cmd{
+ Path: name,
+ Args: append([]string{name}, args...),
+ Dir: dir,
+ Env: childEnv(cfg),
+ Stdout: outW,
+ Stderr: errW,
+ SysProcAttr: &syscall.SysProcAttr{
+ Setpgid: true,
+ Pdeathsig: syscall.SIGKILL,
+ },
+ }
+ // Pdeathsig is the starting thread's: hold it until the child is
+ // reaped.
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+ startErr := cmd.Start()
+ outW.Close()
+ errW.Close()
+ if startErr != nil {
+ outR.Close()
+ errR.Close()
+ return nil, childFailed(cfg, "cannot start "+name, startErr)
+ }
+ pid := cmd.Process.Pid
+ exited := make(chan struct{})
+ // Started before the drains: the last goroutine started tends to run
+ // next on this thread, and one parked in waitid would hide a missing
+ // LockOSThread from TestRunChildSurvivesThreadExits. With the lock,
+ // the order does not matter.
+ go func() {
+ defer close(exited)
+ waitExited(pid)
+ }()
+ tail := newTail(stderrTailBytes)
+ outDone, errDone := drain(stdout, outR), drain(tail, errR)
+
+ var ctxErr error
+ select {
+ case <-exited:
+ case <-ctx.Done():
+ ctxErr = ctx.Err()
+ }
+ budget := time.NewTimer(reapBudget)
+ defer budget.Stop()
+ _ = unix.Kill(-pid, unix.SIGKILL)
+ select {
+ case <-exited:
+ case <-budget.C:
+ return tail.Bytes(), childFailed(cfg, "the child outlived SIGKILL", nil)
+ }
+ waitErr := cmd.Wait()
+ if err := reapDescendants(budget.C); err != nil {
+ return tail.Bytes(), childFailed(cfg, "descendants outlived the cleanup", err)
+ }
+ for _, done := range []<-chan struct{}{outDone, errDone} {
+ select {
+ case <-done:
+ case <-budget.C:
+ return tail.Bytes(), childFailed(cfg, "a pipe stayed open", nil)
+ }
+ }
+
+ var exitErr *exec.ExitError
+ switch {
+ case ctxErr != nil:
+ return tail.Bytes(), ctxErr
+ case waitErr == nil:
+ return tail.Bytes(), nil
+ case errors.As(waitErr, &exitErr):
+ return tail.Bytes(), jobError{media.CodeUnreadable}
+ }
+ return tail.Bytes(), childFailed(cfg, "wait failed", waitErr)
+}
+
+// childFailed logs why a child could not be run or cleaned up and
+// answers engine_failed.
+func childFailed(cfg Config, why string, err error) error {
+ // engine.child.failed (pending Luna pass). why is fixed text or a
+ // binary's path; err is the system's.
+ if err != nil {
+ cfg.Logf("codec: child process: %s: %v", why, err)
+ } else {
+ cfg.Logf("codec: child process: %s", why)
+ }
+ return jobError{media.CodeEngineFailed}
+}
+
+// waitExited returns when pid has exited, without reaping it: the
+// zombie keeps its pid and process group from being reused until
+// cmd.Wait.
+func waitExited(pid int) {
+ for {
+ var info unix.Siginfo
+ err := unix.Waitid(unix.P_PID, pid, &info, unix.WEXITED|unix.WNOWAIT, nil)
+ if !errors.Is(err, unix.EINTR) {
+ return
+ }
+ }
+}
+
+// reapPoll is how often reapDescendants looks again for children that
+// have not yet died of their SIGKILL.
+const reapPoll = 10 * time.Millisecond
+
+// reapDescendants kills every child of the handler and reaps them until
+// it has none (ECHILD). Killing a child re-parents its own children to
+// the handler (a subreaper), so each round finds the next generation.
+// It gives up when budget fires.
+func reapDescendants(budget <-chan time.Time) error {
+ tick := time.NewTicker(reapPoll)
+ defer tick.Stop()
+ self := os.Getpid()
+ for {
+ if err := killChildrenOf(self); err != nil {
+ return err
+ }
+ for {
+ var ws unix.WaitStatus
+ wpid, err := unix.Wait4(-1, &ws, unix.WNOHANG, nil)
+ switch {
+ case errors.Is(err, unix.ECHILD):
+ return nil
+ case errors.Is(err, unix.EINTR):
+ continue
+ case err != nil:
+ return err
+ }
+ if wpid == 0 {
+ break // children left, none dead yet
+ }
+ }
+ select {
+ case <-tick.C:
+ case <-budget:
+ return errors.New("children remain")
+ }
+ }
+}
+
+// killChildrenOf sends SIGKILL to every process whose parent is ppid.
+// A child of the handler stays in the process table until the handler
+// reaps it, so its pid cannot be reused between the read and the kill.
+func killChildrenOf(ppid int) error {
+ ents, err := os.ReadDir("/proc")
+ if err != nil {
+ return err
+ }
+ for _, e := range ents {
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil {
+ continue
+ }
+ b, err := os.ReadFile("/proc/" + e.Name() + "/stat")
+ if err != nil {
+ continue // gone
+ }
+ if parentFromStat(b) == ppid {
+ _ = unix.Kill(pid, unix.SIGKILL)
+ }
+ }
+ return nil
+}
+
+// parentFromStat reads the parent pid from a /proc/<pid>/stat line:
+// "pid (comm) state ppid ...". comm may hold anything, ")" included, so
+// the fields are read after the last ")". -1 when it does not parse.
+func parentFromStat(b []byte) int {
+ i := bytes.LastIndexByte(b, ')')
+ if i < 0 {
+ return -1
+ }
+ fields := bytes.Fields(b[i+1:])
+ if len(fields) < 2 {
+ return -1
+ }
+ ppid, err := strconv.Atoi(string(fields[1]))
+ if err != nil {
+ return -1
+ }
+ return ppid
+}
+
+// drain copies r to w until r ends, then closes r and closes the
+// channel it answers. A write error stops the copying but not the
+// reading, so the child never blocks on a full pipe.
+func drain(w io.Writer, r *os.File) <-chan struct{} {
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ defer r.Close()
+ _, err := io.Copy(w, r)
+ if err != nil {
+ _, _ = io.Copy(io.Discard, r)
+ }
+ }()
+ return done
+}
diff --git a/internal/mediahandler/procs_other.go b/internal/mediahandler/procs_other.go
new file mode 100644
index 000000000..201d9c1b9
--- /dev/null
+++ b/internal/mediahandler/procs_other.go
@@ -0,0 +1,24 @@
+//go:build !linux
+
+package mediahandler
+
+import (
+ "context"
+ "io"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// runChild needs Linux (a child subreaper, Pdeathsig, /proc): the
+// handler runs only in the engine's Linux image. Elsewhere it starts
+// nothing and answers engine_failed.
+func runChild(ctx context.Context, cfg Config, name string, args []string, dir string) (stderrTail []byte, err error) {
+ return runChildTo(ctx, cfg, name, args, dir, io.Discard)
+}
+
+// runChildTo is runChild with the child's stdout; see runChild.
+func runChildTo(_ context.Context, cfg Config, _ string, _ []string, _ string, _ io.Writer) ([]byte, error) {
+ // engine.child.unsupported (pending Luna pass).
+ cfg.Logf("codec: child processes need Linux")
+ return nil, jobError{media.CodeEngineFailed}
+}
diff --git a/internal/mediahandler/procs_test.go b/internal/mediahandler/procs_test.go
new file mode 100644
index 000000000..ebae010c6
--- /dev/null
+++ b/internal/mediahandler/procs_test.go
@@ -0,0 +1,482 @@
+//go:build linux
+
+package mediahandler
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// fakeFIFOEnv names a FIFO the "fifo" fakes read to its end.
+const fakeFIFOEnv = "MEDIA_FAKE_FIFO"
+
+func init() {
+ // escape: the child starts a grandchild in a new session, which
+ // starts a leaf in another; both hold the child's stderr and catch
+ // SIGTERM and SIGHUP. The child prints every pid and "ready", then
+ // exits 0. escape-block: the same, but the child then blocks.
+ fakeScenarios["escape"] = func([]string) int { return fakeEscape(false) }
+ fakeScenarios["escape-block"] = func([]string) int { return fakeEscape(true) }
+ fakeScenarios["escape-grandchild"] = fakeEscapeGrandchild
+ // pid-block prints its pid and blocks.
+ fakeScenarios["pid-block"] = func([]string) int {
+ fmt.Printf("pid %d\n", os.Getpid())
+ return blockForever()
+ }
+ // fifo prints "ready", reads fakeFIFOEnv's FIFO to its end and
+ // exits 0.
+ fakeScenarios["fifo"] = func([]string) int {
+ fmt.Println("ready")
+ f, err := os.Open(os.Getenv(fakeFIFOEnv))
+ if err != nil {
+ return 1
+ }
+ _, _ = io.Copy(io.Discard, f)
+ return 0
+ }
+ // handler is the codec process itself: it runs pid-block under
+ // runChild, its stdout passed through, and never returns.
+ fakeScenarios["handler"] = func([]string) int {
+ exe, err := os.Executable()
+ if err != nil {
+ return 1
+ }
+ cfg := Config{FFmpeg: exe, Scratch: os.TempDir(), Logf: func(string, ...any) {}, extraEnv: []string{fakeEnv + "=pid-block"}}
+ _, _ = runChildTo(context.Background(), cfg, exe, nil, "", os.Stdout)
+ return 1
+ }
+}
+
+// startSelf starts the test binary as scenario in a new session.
+func startSelf(scenario string, stdout io.Writer) (*exec.Cmd, error) {
+ exe, err := os.Executable()
+ if err != nil {
+ return nil, err
+ }
+ cmd := exec.Command(exe)
+ var env []string
+ for _, kv := range os.Environ() {
+ if !strings.HasPrefix(kv, fakeEnv+"=") {
+ env = append(env, kv)
+ }
+ }
+ cmd.Env = append(env, fakeEnv+"="+scenario)
+ cmd.Stdout = stdout
+ cmd.Stderr = os.Stderr
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ return cmd, cmd.Start()
+}
+
+func fakeEscape(block bool) int {
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ return 1
+ }
+ gc, err := startSelf("escape-grandchild", pw)
+ pw.Close()
+ if err != nil {
+ return 1
+ }
+ _ = gc.Process.Release()
+ // The grandchild prints its lines and closes its stdout.
+ lines, err := io.ReadAll(pr)
+ if err != nil {
+ return 1
+ }
+ fmt.Print(string(lines))
+ fmt.Printf("child %d\nready\n", os.Getpid())
+ if block {
+ return blockForever()
+ }
+ return 0
+}
+
+func fakeEscapeGrandchild([]string) int {
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ return 1
+ }
+ leaf, err := startSelf("pid-block", pw)
+ pw.Close()
+ if err != nil {
+ return 1
+ }
+ line, _ := bufio.NewReader(pr).ReadString('\n')
+ fmt.Printf("leaf %s", strings.TrimPrefix(line, "pid "))
+ fmt.Printf("grandchild %d\n", os.Getpid())
+ _ = leaf.Process.Release()
+ os.Stdout.Close()
+ return blockForever()
+}
+
+// lineWriter collects a child's stdout and runs onLine for each line.
+type lineWriter struct {
+ mu sync.Mutex
+ buf bytes.Buffer
+ onLine func(string)
+}
+
+func (w *lineWriter) Write(p []byte) (int, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ w.buf.Write(p)
+ for {
+ i := bytes.IndexByte(w.buf.Bytes(), '\n')
+ if i < 0 {
+ break
+ }
+ line := string(w.buf.Next(i + 1))
+ if w.onLine != nil {
+ w.onLine(strings.TrimSpace(line))
+ }
+ }
+ return len(p), nil
+}
+
+// pids answers the "<role> <pid>" lines seen.
+func pidsOf(lines []string) map[string]int {
+ out := map[string]int{}
+ for _, l := range lines {
+ role, n, ok := strings.Cut(l, " ")
+ if pid, err := strconv.Atoi(n); ok && err == nil {
+ out[role] = pid
+ }
+ }
+ return out
+}
+
+// alive reports whether pid is a process that has not exited (a
+// zombie has exited).
+func alive(pid int) bool {
+ b, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return false
+ }
+ i := bytes.LastIndexByte(b, ')')
+ if i < 0 || i+2 >= len(b) {
+ return false
+ }
+ return b[i+2] != 'Z' && b[i+2] != 'X'
+}
+
+// exists reports whether pid is in the process table at all (zombies
+// included): a process runChild reaped is not.
+func exists(pid int) bool {
+ return unix.Kill(pid, 0) == nil
+}
+
+// TestRunChildKillsEscapedDescendants: a child that forks a grandchild
+// which calls setsid (and a leaf under that, in a session of its own),
+// each holding the child's stderr and ignoring SIGTERM and SIGHUP:
+// when runChild returns, none of the three exists, not even as a
+// zombie. Once with the child exiting 0 by itself (runChild answers
+// nil: the direct child is reaped by cmd.Wait, preflight F35), once
+// with the context ending while the child blocks.
+func TestRunChildKillsEscapedDescendants(t *testing.T) {
+ for _, scenario := range []string{"escape", "escape-block"} {
+ cfg, _ := fakeConfig(t, scenario)
+ ctx, cancel := context.WithCancel(context.Background())
+ var mu sync.Mutex
+ var lines []string
+ w := &lineWriter{onLine: func(l string) {
+ mu.Lock()
+ lines = append(lines, l)
+ mu.Unlock()
+ if l == "ready" && scenario == "escape-block" {
+ cancel()
+ }
+ }}
+ start := time.Now()
+ _, err := runChildTo(ctx, cfg, cfg.FFmpeg, nil, filepath.Join(cfg.Scratch, "tmp"), w)
+ cancel()
+ took := time.Since(start)
+ mu.Lock()
+ pids := pidsOf(lines)
+ mu.Unlock()
+ switch scenario {
+ case "escape":
+ if err != nil {
+ t.Errorf("%s: runChild = %v, want nil", scenario, err)
+ }
+ case "escape-block":
+ if !errors.Is(err, context.Canceled) {
+ t.Errorf("%s: runChild = %v, want context.Canceled", scenario, err)
+ }
+ }
+ if len(pids) != 3 {
+ t.Fatalf("%s: the fake printed %q, want three pids", scenario, lines)
+ }
+ for role, pid := range pids {
+ if exists(pid) {
+ t.Errorf("%s: the %s (%d) still exists after runChild returned (alive %v)", scenario, role, pid, alive(pid))
+ _ = unix.Kill(pid, unix.SIGKILL)
+ }
+ }
+ if took > reapBudget {
+ t.Errorf("%s: runChild took %s", scenario, took)
+ }
+ }
+}
+
+// TestRunChildPdeathsig: when the handler itself dies (SIGKILL, so it
+// cleans up nothing), the child it started dies too: Pdeathsig.
+func TestRunChildPdeathsig(t *testing.T) {
+ pr, pw, err := os.Pipe()
+ if err != nil {
+ t.Fatal(err)
+ }
+ handler, err := startSelf("handler", pw)
+ pw.Close()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = handler.Process.Kill(); _ = handler.Wait() })
+ line, err := bufio.NewReader(pr).ReadString('\n')
+ if err != nil {
+ t.Fatalf("no pid from the handler's child: %v", err)
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "pid ")))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ _ = unix.Kill(pid, unix.SIGKILL)
+ var ws unix.WaitStatus
+ _, _ = unix.Wait4(pid, &ws, unix.WNOHANG, nil)
+ })
+ if err := handler.Process.Kill(); err != nil {
+ t.Fatal(err)
+ }
+ _ = handler.Wait()
+ tick := time.NewTicker(10 * time.Millisecond)
+ defer tick.Stop()
+ give := time.NewTimer(10 * time.Second)
+ defer give.Stop()
+ for alive(pid) {
+ select {
+ case <-tick.C:
+ case <-give.C:
+ t.Fatalf("the child (%d) outlived its handler by 10 s", pid)
+ }
+ }
+}
+
+// TestRunChildSurvivesThreadExits: Pdeathsig fires when the thread
+// that started the child exits, and the Go runtime ends a thread when a
+// goroutine locked to it returns. runChild holds its thread from Start
+// to the end of the wait (preflight F35), so goroutines that lock a
+// thread and return while the child runs never take the child with
+// them.
+func TestRunChildSurvivesThreadExits(t *testing.T) {
+ fifo := filepath.Join(t.TempDir(), "fifo")
+ if err := unix.Mkfifo(fifo, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cfg, _ := fakeConfig(t, "fifo")
+ cfg.extraEnv = append(cfg.extraEnv, fakeFIFOEnv+"="+fifo)
+ done := make(chan error, 1)
+ go func() {
+ _, err := runChild(context.Background(), cfg, cfg.FFmpeg, nil, "")
+ done <- err
+ }()
+ // Opening the FIFO for writing waits for the child to open it.
+ w, err := os.OpenFile(fifo, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for range 16 {
+ var wg sync.WaitGroup
+ for range 128 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ runtime.LockOSThread() // never unlocked: the thread ends with the goroutine
+ }()
+ }
+ wg.Wait()
+ runtime.Gosched()
+ }
+ w.Close()
+ select {
+ case err := <-done:
+ if err != nil {
+ t.Fatalf("runChild = %v: the child died with a thread", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("runChild did not return")
+ }
+}
+
+// TestRunChildOneAtATime: runChild's cleanup kills every child of the
+// handler, so two runs never overlap: a second waits for the first.
+func TestRunChildOneAtATime(t *testing.T) {
+ fifo := filepath.Join(t.TempDir(), "fifo")
+ if err := unix.Mkfifo(fifo, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cfgA, _ := fakeConfig(t, "fifo")
+ cfgA.extraEnv = append(cfgA.extraEnv, fakeFIFOEnv+"="+fifo)
+ ready := make(chan struct{})
+ var once sync.Once
+ doneA := make(chan error, 1)
+ go func() {
+ _, err := runChildTo(context.Background(), cfgA, cfgA.FFmpeg, nil, "", &lineWriter{onLine: func(l string) {
+ if l == "ready" {
+ once.Do(func() { close(ready) })
+ }
+ }})
+ doneA <- err
+ }()
+ select {
+ case <-ready:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the first child did not start")
+ }
+ cfgB, _ := fakeConfig(t, "env")
+ doneB := make(chan error, 1)
+ go func() {
+ _, err := runChild(context.Background(), cfgB, cfgB.FFmpeg, nil, "")
+ doneB <- err
+ }()
+ select {
+ case err := <-doneB:
+ t.Fatalf("a second runChild finished (%v) while the first child ran", err)
+ case <-time.After(300 * time.Millisecond):
+ }
+ w, err := os.OpenFile(fifo, os.O_WRONLY, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w.Close()
+ for name, c := range map[string]chan error{"first": doneA, "second": doneB} {
+ select {
+ case err := <-c:
+ if err != nil {
+ t.Errorf("%s runChild: %v", name, err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatalf("%s runChild did not return", name)
+ }
+ }
+}
+
+// TestRunChildEnvironmentIsExplicit: the child's environment is the
+// fixed minimal one (plus the test's own entries), nothing of the
+// handler's: not the payload, not a credential, not the parent's PATH.
+func TestRunChildEnvironmentIsExplicit(t *testing.T) {
+ t.Setenv(media.PayloadEnv, "secret-payload")
+ t.Setenv("AWS_SECRET_ACCESS_KEY", "secret-key")
+ t.Setenv("PATH", "/secret/bin:/usr/bin")
+ cfg, _ := fakeConfig(t, "env")
+ var out bytes.Buffer
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFmpeg, nil, "", &out); err != nil {
+ t.Fatal(err)
+ }
+ got := strings.Split(strings.TrimSpace(out.String()), "\n")
+ tmp := filepath.Join(cfg.Scratch, "tmp")
+ want := append([]string{"PATH=/usr/bin:/bin", "LC_ALL=C", "HOME=" + tmp, "TMPDIR=" + tmp}, cfg.extraEnv...)
+ slices.Sort(got)
+ slices.Sort(want)
+ if !slices.Equal(got, want) {
+ t.Errorf("child environment:\n got %q\nwant %q", got, want)
+ }
+ if strings.Contains(out.String(), "secret") {
+ t.Errorf("the child saw a secret: %q", out.String())
+ }
+}
+
+// TestRunChildOutcomes: exit 0 is nil; a non-zero exit or a death by
+// signal is unreadable; a binary that will not start is engine_failed;
+// a context that has already ended starts nothing.
+// The stderr tail is the last 64 KiB.
+func TestRunChildOutcomes(t *testing.T) {
+ cfg, _ := fakeConfig(t, "env")
+ if _, err := runChild(context.Background(), cfg, cfg.FFmpeg, nil, ""); err != nil {
+ t.Errorf("exit 0: %v", err)
+ }
+ cfg, _ = fakeConfig(t, "fail")
+ tail, err := runChild(context.Background(), cfg, cfg.FFmpeg, nil, "")
+ if codeOf(err) != media.CodeUnreadable || !bytes.Contains(tail, []byte("Invalid data")) {
+ t.Errorf("exit 1: %s, tail %q", codeOf(err), tail)
+ }
+ cfg, _ = fakeConfig(t, "noisy")
+ tail, err = runChild(context.Background(), cfg, cfg.FFmpeg, nil, "")
+ if codeOf(err) != media.CodeUnreadable || len(tail) != stderrTailBytes || !bytes.HasSuffix(tail, []byte("line 0999 "+strings.Repeat("x", 92)+"\n")) {
+ t.Errorf("noisy: %s, %d-byte tail ending %q", codeOf(err), len(tail), tail[max(0, len(tail)-40):])
+ }
+ cfg, _ = fakeConfig(t, "pid-block")
+ var pid int
+ w := &lineWriter{onLine: func(l string) {
+ if n, ok := strings.CutPrefix(l, "pid "); ok {
+ pid, _ = strconv.Atoi(n)
+ _ = unix.Kill(pid, unix.SIGSEGV)
+ }
+ }}
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFmpeg, nil, "", w); codeOf(err) != media.CodeUnreadable {
+ t.Errorf("killed by a signal: %s", codeOf(err))
+ }
+ if _, err := runChild(context.Background(), cfg, filepath.Join(t.TempDir(), "none"), nil, ""); codeOf(err) != media.CodeEngineFailed {
+ t.Errorf("no binary: %s", codeOf(err))
+ }
+ // A context already ended starts nothing: not even a start is
+ // tried (which, for a missing binary, would be engine_failed).
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := runChild(ctx, cfg, filepath.Join(t.TempDir(), "none"), nil, ""); !errors.Is(err, context.Canceled) {
+ t.Errorf("ended context: %v, want context.Canceled", err)
+ }
+}
+
+// TestStderrTail: the tail keeps the last n bytes across writes of any
+// size.
+func TestStderrTail(t *testing.T) {
+ var all []byte
+ tl := newTail(10)
+ for i, s := range []string{"abc", "defghij", "k", "", "lmnopqrstuvwxyz0123", "45"} {
+ _, _ = tl.Write([]byte(s))
+ all = append(all, s...)
+ want := all[max(0, len(all)-10):]
+ if got := tl.Bytes(); !bytes.Equal(got, want) {
+ t.Errorf("after write %d: %q, want %q", i, got, want)
+ }
+ }
+}
+
+// TestParentFromStat: the /proc/<pid>/stat parser takes the parent from
+// after the last ")", so a command name holding ") S 1" cannot lie.
+func TestParentFromStat(t *testing.T) {
+ for _, c := range []struct {
+ stat string
+ want int
+ }{
+ {"123 (ffmpeg) S 77 123 123 0 -1", 77},
+ {"123 (a) S 1 (b) R 9) S 42 1 1", 42},
+ {"123 (x y) Z 5 0", 5},
+ {"garbage", -1},
+ {"1 (x) S", -1},
+ {"1 (x) S notanumber", -1},
+ } {
+ if got := parentFromStat([]byte(c.stat)); got != c.want {
+ t.Errorf("%q: %d, want %d", c.stat, got, c.want)
+ }
+ }
+}
diff --git a/internal/mediahandler/sniff.go b/internal/mediahandler/sniff.go
new file mode 100644
index 000000000..900d1bbcb
--- /dev/null
+++ b/internal/mediahandler/sniff.go
@@ -0,0 +1,77 @@
+package mediahandler
+
+import (
+ "bytes"
+ "errors"
+ "io"
+ "os"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// sniffBytes is how much of the source sniff reads: enough for the
+// longest magic it checks (RIFF....WAVE, 12 bytes).
+const sniffBytes = 16
+
+// sniff reads the source's first bytes in Go and answers the demuxer
+// ffmpeg and ffprobe are forced to (spec §6; plan 3's Global
+// Constraints). Both presets accept ISO BMFF (`ftyp` at offset 4: MP4,
+// MOV, 3GP, M4A) as "mov" and EBML (Matroska, WebM) as "matroska";
+// audio-aac also accepts MP3 (an ID3 tag, or an MPEG audio frame
+// header) as "mp3", RIFF/WAVE as "wav", "fLaC" as "flac" and "OggS" as
+// "ogg". Anything else, an unknown preset included, is
+// unsupported_container, and no ffmpeg or ffprobe runs on it.
+func sniff(head []byte, preset string) (demuxer string, err error) {
+ if preset != media.PresetVideo720p && preset != media.PresetAudioAAC {
+ return "", jobError{media.CodeUnsupportedContainer}
+ }
+ switch {
+ case len(head) >= 8 && string(head[4:8]) == "ftyp":
+ return "mov", nil
+ case bytes.HasPrefix(head, []byte{0x1a, 0x45, 0xdf, 0xa3}):
+ return "matroska", nil
+ }
+ if preset != media.PresetAudioAAC {
+ return "", jobError{media.CodeUnsupportedContainer}
+ }
+ switch {
+ case bytes.HasPrefix(head, []byte("ID3")) || mpegAudioFrame(head):
+ return "mp3", nil
+ case len(head) >= 12 && string(head[0:4]) == "RIFF" && string(head[8:12]) == "WAVE":
+ return "wav", nil
+ case bytes.HasPrefix(head, []byte("fLaC")):
+ return "flac", nil
+ case bytes.HasPrefix(head, []byte("OggS")):
+ return "ogg", nil
+ }
+ return "", jobError{media.CodeUnsupportedContainer}
+}
+
+// mpegAudioFrame reports whether head starts with an MPEG audio frame
+// header: 11 sync bits, and none of the reserved values (version 01,
+// layer 00, bitrate index 1111, sample rate index 11). Layer 00 is
+// also how an AAC ADTS header starts, which is not MP3.
+func mpegAudioFrame(head []byte) bool {
+ if len(head) < 3 || head[0] != 0xff || head[1]&0xe0 != 0xe0 {
+ return false
+ }
+ version, layer := (head[1]>>3)&3, (head[1]>>1)&3
+ bitrate, rate := head[2]>>4, (head[2]>>2)&3
+ return version != 1 && layer != 0 && bitrate != 15 && rate != 3
+}
+
+// readHead reads up to sniffBytes from the start of path; a shorter
+// file answers what it has.
+func readHead(path string) ([]byte, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, err
+ }
+ defer f.Close()
+ head := make([]byte, sniffBytes)
+ n, err := io.ReadFull(f, head)
+ if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
+ return nil, err
+ }
+ return head[:n], nil
+}
diff --git a/internal/mediahandler/sniff_test.go b/internal/mediahandler/sniff_test.go
new file mode 100644
index 000000000..572ae00b0
--- /dev/null
+++ b/internal/mediahandler/sniff_test.go
@@ -0,0 +1,137 @@
+package mediahandler
+
+import (
+ "bytes"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// Heads for each family, as the first bytes of a real file would be.
+var (
+ headMP4 = []byte("\x00\x00\x00\x20ftypisom\x00\x00\x02\x00isomiso2avc1mp41")
+ headMOV = []byte("\x00\x00\x00\x14ftypqt \x00\x00\x00\x00qt ")
+ headM4A = []byte("\x00\x00\x00\x1cftypM4A \x00\x00\x00\x00M4A mp42isom")
+ headMKV = []byte("\x1a\x45\xdf\xa3\x9f\x42\x86\x81\x01\x42\xf7\x81\x01\x42\xf2\x81\x04webm")
+ headID3 = []byte("ID3\x04\x00\x00\x00\x00\x0f\x76TIT2")
+ headMPEG = []byte("\xff\xfb\x90\x64\x00\x00\x00\x00") // MPEG-1 layer III, 128 kbit/s, 44.1 kHz
+ headWAV = []byte("RIFF\x24\x08\x00\x00WAVEfmt \x10\x00\x00\x00")
+ headFLAC = []byte("fLaC\x00\x00\x00\x22\x12\x00\x12\x00")
+ headOGG = []byte("OggS\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00")
+)
+
+// TestSniffTable: each family under each preset, and what is refused.
+// Spec §6 and plan 3's Global Constraints: ISO BMFF and Matroska for
+// both presets, MP3, WAV, FLAC and Ogg for audio-aac only; anything
+// else is unsupported_container. An MP3 under video-720p is refused
+// here, before ffprobe runs (preflight F17).
+func TestSniffTable(t *testing.T) {
+ const (
+ video = media.PresetVideo720p
+ audio = media.PresetAudioAAC
+ none = ""
+ )
+ cases := []struct {
+ name string
+ head []byte
+ video, audio string // the demuxer, or none for unsupported_container
+ }{
+ {"mp4", headMP4, "mov", "mov"},
+ {"mov", headMOV, "mov", "mov"},
+ {"m4a", headM4A, "mov", "mov"},
+ {"matroska/webm", headMKV, "matroska", "matroska"},
+ {"mp3 with ID3", headID3, none, "mp3"},
+ {"mp3 frame sync", headMPEG, none, "mp3"},
+ {"mpeg-2 layer iii frame", []byte("\xff\xf3\x64\xc4"), none, "mp3"},
+ {"wav", headWAV, none, "wav"},
+ {"flac", headFLAC, none, "flac"},
+ {"ogg", headOGG, none, "ogg"},
+ {"hls playlist", []byte("#EXTM3U\n#EXT-X-VERSION:7\n"), none, none},
+ {"xml", []byte("<?xml version=\"1.0\"?><MPD"), none, none},
+ {"pdf", []byte("%PDF-1.7\n%\xe2\xe3\xcf\xd3\n"), none, none},
+ {"empty", nil, none, none},
+ {"seven bytes of an mp4", headMP4[:7], none, none},
+ {"ftyp at offset 0", []byte("ftypisom\x00\x00\x02\x00"), none, none},
+ {"riff not wave", []byte("RIFF\x24\x08\x00\x00AVI LIST"), none, none},
+ {"riff too short", []byte("RIFF\x24\x08\x00\x00WAV"), none, none},
+ {"aac adts (layer 00)", []byte("\xff\xf1\x50\x80\x02\x1f\xfc"), none, none},
+ {"mpeg reserved version", []byte("\xff\xeb\x90\x64"), none, none},
+ {"mpeg bad bitrate", []byte("\xff\xfb\xf0\x64"), none, none},
+ {"mpeg bad sample rate", []byte("\xff\xfb\x9c\x64"), none, none},
+ {"two bytes of sync", []byte("\xff\xfb"), none, none},
+ {"png", []byte("\x89PNG\r\n\x1a\n"), none, none},
+ {"html", []byte("<!doctype html><html>"), none, none},
+ }
+ for _, c := range cases {
+ for _, pc := range []struct{ preset, want string }{{video, c.video}, {audio, c.audio}} {
+ got, err := sniff(c.head, pc.preset)
+ if pc.want == none {
+ if codeOf(err) != media.CodeUnsupportedContainer || got != "" {
+ t.Errorf("%s under %s: sniff = %q, %s; want unsupported_container", c.name, pc.preset, got, codeOf(err))
+ }
+ continue
+ }
+ if err != nil || got != pc.want {
+ t.Errorf("%s under %s: sniff = %q, %s; want %q", c.name, pc.preset, got, codeOf(err), pc.want)
+ }
+ }
+ }
+ // An unknown preset accepts nothing, not even an MP4.
+ if got, err := sniff(headMP4, "video-4k"); codeOf(err) != media.CodeUnsupportedContainer || got != "" {
+ t.Errorf("unknown preset: sniff = %q, %s", got, codeOf(err))
+ }
+}
+
+// magicPresent reports whether head carries the magic of the family
+// the demuxer stands for: the property FuzzSniff holds sniff to,
+// written separately from sniff.
+func magicPresent(head []byte, demuxer string) bool {
+ switch demuxer {
+ case "mov":
+ return len(head) >= 8 && string(head[4:8]) == "ftyp"
+ case "matroska":
+ return bytes.HasPrefix(head, []byte{0x1a, 0x45, 0xdf, 0xa3})
+ case "mp3":
+ if bytes.HasPrefix(head, []byte("ID3")) {
+ return true
+ }
+ return len(head) >= 3 && head[0] == 0xff && head[1]&0xe0 == 0xe0 &&
+ (head[1]>>3)&3 != 1 && (head[1]>>1)&3 != 0 && head[2]>>4 != 15 && (head[2]>>2)&3 != 3
+ case "wav":
+ return len(head) >= 12 && string(head[0:4]) == "RIFF" && string(head[8:12]) == "WAVE"
+ case "flac":
+ return bytes.HasPrefix(head, []byte("fLaC"))
+ case "ogg":
+ return bytes.HasPrefix(head, []byte("OggS"))
+ }
+ return false
+}
+
+// FuzzSniff: sniff never panics, answers a demuxer or
+// unsupported_container and nothing else, never answers a family whose
+// magic is absent, and answers an audio-only family only for audio-aac.
+func FuzzSniff(f *testing.F) {
+ for _, h := range [][]byte{headMP4, headMOV, headM4A, headMKV, headID3, headMPEG, headWAV, headFLAC, headOGG, nil, []byte("#EXTM3U"), []byte("%PDF-1.7")} {
+ f.Add(h, true)
+ f.Add(h, false)
+ }
+ f.Fuzz(func(t *testing.T, head []byte, video bool) {
+ preset := media.PresetAudioAAC
+ if video {
+ preset = media.PresetVideo720p
+ }
+ got, err := sniff(head, preset)
+ if err != nil {
+ if got != "" || codeOf(err) != media.CodeUnsupportedContainer {
+ t.Fatalf("sniff = %q, %v", got, err)
+ }
+ return
+ }
+ if !magicPresent(head, got) {
+ t.Fatalf("sniff answered %q for % x, whose magic is absent", got, head)
+ }
+ if video && got != "mov" && got != "matroska" {
+ t.Fatalf("sniff answered %q under video-720p", got)
+ }
+ })
+}
diff --git a/internal/mediahandler/testdata/probe/aac-6ch.json b/internal/mediahandler/testdata/probe/aac-6ch.json
new file mode 100644
index 000000000..44e3023e3
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/aac-6ch.json
@@ -0,0 +1,23 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "aac",
+ "profile": "LC",
+ "codec_type": "audio",
+ "sample_rate": "48000",
+ "channels": 6,
+ "channel_layout": "5.1",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "300.010667",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "300.010667"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/bomb-30000.json b/internal/mediahandler/testdata/probe/bomb-30000.json
new file mode 100644
index 000000000..d7539c0ad
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/bomb-30000.json
@@ -0,0 +1,23 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "profile": "High",
+ "codec_type": "video",
+ "width": 30000,
+ "height": 30000,
+ "pix_fmt": "yuv420p",
+ "r_frame_rate": "1/1",
+ "avg_frame_rate": "1/1",
+ "duration": "1.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "1.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/chrome-webm-opus.json b/internal/mediahandler/testdata/probe/chrome-webm-opus.json
new file mode 100644
index 000000000..412000367
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/chrome-webm-opus.json
@@ -0,0 +1,25 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "opus",
+ "codec_type": "audio",
+ "sample_fmt": "fltp",
+ "sample_rate": "48000",
+ "channels": 1,
+ "channel_layout": "mono",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "time_base": "1/1000",
+ "start_pts": 0,
+ "start_time": "0.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "matroska,webm",
+ "start_time": "0.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/chrome-webm-opus.packets.csv b/internal/mediahandler/testdata/probe/chrome-webm-opus.packets.csv
new file mode 100644
index 000000000..251c9c4af
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/chrome-webm-opus.packets.csv
@@ -0,0 +1,7 @@
+0.000000,0.020000
+0.020000,0.020000
+0.040000,0.020000
+5.960000,N/A
+5.980000,0.020000
+4.000000,0.020000
+N/A,0.020000
diff --git a/internal/mediahandler/testdata/probe/dolby-vision-5.json b/internal/mediahandler/testdata/probe/dolby-vision-5.json
new file mode 100644
index 000000000..4ca7643b5
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/dolby-vision-5.json
@@ -0,0 +1,26 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "hevc",
+ "profile": "Main 10",
+ "codec_type": "video",
+ "width": 1920,
+ "height": 1080,
+ "pix_fmt": "yuv420p10le",
+ "r_frame_rate": "24000/1001",
+ "avg_frame_rate": "24000/1001",
+ "duration": "20.020000",
+ "disposition": {"default": 1, "attached_pic": 0},
+ "side_data_list": [
+ {"side_data_type": "DOVI configuration record", "dv_version_major": 1, "dv_version_minor": 0, "dv_profile": 5, "dv_level": 6, "rpu_present_flag": 1, "el_present_flag": 0, "bl_present_flag": 1, "dv_bl_signal_compatibility_id": 0}
+ ]
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "20.020000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/dolby-vision-8-4.json b/internal/mediahandler/testdata/probe/dolby-vision-8-4.json
new file mode 100644
index 000000000..258bf5db7
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/dolby-vision-8-4.json
@@ -0,0 +1,41 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "hevc",
+ "profile": "Main 10",
+ "codec_type": "video",
+ "width": 3840,
+ "height": 2160,
+ "pix_fmt": "yuv420p10le",
+ "color_space": "bt2020nc",
+ "color_transfer": "arib-std-b67",
+ "color_primaries": "bt2020",
+ "r_frame_rate": "60/1",
+ "avg_frame_rate": "60/1",
+ "duration": "8.000000",
+ "disposition": {"default": 1, "attached_pic": 0},
+ "side_data_list": [
+ {"side_data_type": "DOVI configuration record", "dv_version_major": 1, "dv_version_minor": 0, "dv_profile": 8, "dv_level": 9, "rpu_present_flag": 1, "el_present_flag": 0, "bl_present_flag": 1, "dv_bl_signal_compatibility_id": 4, "dv_md_compression": "none"},
+ {"side_data_type": "Display Matrix", "displaymatrix": "\n00000000: 0 65536 0\n00000001: -65536 0 0\n00000002: 0 0 1073741824\n", "rotation": -90}
+ ]
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_type": "audio",
+ "sample_rate": "48000",
+ "channels": 2,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "7.989000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 2,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "8.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/h264-120fps.json b/internal/mediahandler/testdata/probe/h264-120fps.json
new file mode 100644
index 000000000..6b8536a45
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/h264-120fps.json
@@ -0,0 +1,23 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "profile": "High",
+ "codec_type": "video",
+ "width": 1920,
+ "height": 1080,
+ "pix_fmt": "yuv420p",
+ "r_frame_rate": "120/1",
+ "avg_frame_rate": "120/1",
+ "duration": "10.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "10.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/h264-4k60.json b/internal/mediahandler/testdata/probe/h264-4k60.json
new file mode 100644
index 000000000..8072ec4d0
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/h264-4k60.json
@@ -0,0 +1,34 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "profile": "High",
+ "codec_type": "video",
+ "width": 3840,
+ "height": 2160,
+ "pix_fmt": "yuv420p",
+ "r_frame_rate": "60/1",
+ "avg_frame_rate": "60/1",
+ "duration": "30.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "codec_type": "audio",
+ "sample_rate": "48000",
+ "channels": 2,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "30.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 2,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "30.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json b/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json
new file mode 100644
index 000000000..82816e975
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json
@@ -0,0 +1,59 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "hevc",
+ "profile": "Main 10",
+ "codec_type": "video",
+ "codec_tag_string": "hvc1",
+ "width": 1920,
+ "height": 1080,
+ "coded_width": 1920,
+ "coded_height": 1080,
+ "pix_fmt": "yuv420p10le",
+ "color_range": "tv",
+ "color_space": "bt2020nc",
+ "color_transfer": "arib-std-b67",
+ "color_primaries": "bt2020",
+ "r_frame_rate": "30/1",
+ "avg_frame_rate": "30/1",
+ "time_base": "1/600",
+ "duration": "12.345000",
+ "disposition": {"default": 1, "dub": 0, "original": 0, "comment": 0, "lyrics": 0, "karaoke": 0, "forced": 0, "hearing_impaired": 0, "visual_impaired": 0, "clean_effects": 0, "attached_pic": 0, "timed_thumbnails": 0, "non_diegetic": 0, "captions": 0, "descriptions": 0, "metadata": 0, "dependent": 0, "still_image": 0, "multilayer": 0},
+ "side_data_list": [
+ {"side_data_type": "Display Matrix", "displaymatrix": "\n00000000: 0 65536 0\n00000001: -65536 0 0\n00000002: 0 0 1073741824\n", "rotation": -90}
+ ]
+ },
+ {
+ "index": 1,
+ "codec_name": "aac",
+ "profile": "LC",
+ "codec_type": "audio",
+ "sample_fmt": "fltp",
+ "sample_rate": "44100",
+ "channels": 2,
+ "channel_layout": "stereo",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "12.329796",
+ "disposition": {"default": 1, "attached_pic": 0}
+ },
+ {
+ "index": 2,
+ "codec_type": "data",
+ "codec_tag_string": "mebx",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "12.345000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 3,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "12.345000",
+ "size": "20480000",
+ "bit_rate": "13271000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/lying-10h.json b/internal/mediahandler/testdata/probe/lying-10h.json
new file mode 100644
index 000000000..c8db0553d
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/lying-10h.json
@@ -0,0 +1,23 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "profile": "High",
+ "codec_type": "video",
+ "width": 1280,
+ "height": 720,
+ "pix_fmt": "yuv420p",
+ "r_frame_rate": "30/1",
+ "avg_frame_rate": "30/1",
+ "duration": "4.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "matroska,webm",
+ "duration": "36000.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/m4a-cover-art.json b/internal/mediahandler/testdata/probe/m4a-cover-art.json
new file mode 100644
index 000000000..0172ea08c
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/m4a-cover-art.json
@@ -0,0 +1,32 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "aac",
+ "profile": "LC",
+ "codec_type": "audio",
+ "sample_rate": "44100",
+ "channels": 2,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "180.000000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ },
+ {
+ "index": 1,
+ "codec_name": "png",
+ "codec_type": "video",
+ "width": 1400,
+ "height": 1400,
+ "r_frame_rate": "90000/1",
+ "avg_frame_rate": "0/0",
+ "disposition": {"default": 0, "attached_pic": 1}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 2,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "180.000000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/mka-cover-art.json b/internal/mediahandler/testdata/probe/mka-cover-art.json
new file mode 100644
index 000000000..e7a199d32
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/mka-cover-art.json
@@ -0,0 +1,30 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "mjpeg",
+ "codec_type": "video",
+ "width": 500,
+ "height": 500,
+ "r_frame_rate": "90000/1",
+ "avg_frame_rate": "0/0",
+ "disposition": {"default": 0, "attached_pic": 1}
+ },
+ {
+ "index": 1,
+ "codec_name": "flac",
+ "codec_type": "audio",
+ "sample_rate": "96000",
+ "channels": 2,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 2,
+ "format_name": "matroska,webm",
+ "duration": "240.500000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/mp3-cover-art.json b/internal/mediahandler/testdata/probe/mp3-cover-art.json
new file mode 100644
index 000000000..917c1f959
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/mp3-cover-art.json
@@ -0,0 +1,34 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "mp3",
+ "codec_type": "audio",
+ "sample_fmt": "fltp",
+ "sample_rate": "44100",
+ "channels": 2,
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "215.484082",
+ "disposition": {"default": 0, "attached_pic": 0}
+ },
+ {
+ "index": 1,
+ "codec_name": "mjpeg",
+ "profile": "Baseline",
+ "codec_type": "video",
+ "width": 600,
+ "height": 600,
+ "r_frame_rate": "90000/1",
+ "avg_frame_rate": "0/0",
+ "duration": "215.484082",
+ "disposition": {"default": 0, "attached_pic": 1}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 2,
+ "format_name": "mp3",
+ "duration": "215.484082"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/stand-ins.txt b/internal/mediahandler/testdata/probe/stand-ins.txt
new file mode 100644
index 000000000..541c7ea4a
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/stand-ins.txt
@@ -0,0 +1,13 @@
+Stand-ins, hand-written in ffprobe 7.1's -of json shape (plan 3 Task 3;
+preflight section 4). Plan 1's spike replaces the first four with the
+answers it saves from Paul's files, every tags object removed:
+
+iphone-hevc-hlg-portrait.json an iPhone HEVC HLG portrait
+dolby-vision-8-4.json a Dolby Vision 8.4
+vfr-screen-recording.json a VFR screen recording
+chrome-webm-opus.json a Chrome WebM Opus without duration
+chrome-webm-opus.packets.csv its packet pass
+
+The rest are hand-written by design: dolby-vision-5, mp3-cover-art,
+m4a-cover-art, mka-cover-art (preflight F17), h264-4k60, h264-120fps,
+bomb-30000, lying-10h, wav-mono, aac-6ch.
diff --git a/internal/mediahandler/testdata/probe/vfr-screen-recording.json b/internal/mediahandler/testdata/probe/vfr-screen-recording.json
new file mode 100644
index 000000000..23823d8ca
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/vfr-screen-recording.json
@@ -0,0 +1,24 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "h264",
+ "profile": "High",
+ "codec_type": "video",
+ "width": 2880,
+ "height": 1800,
+ "pix_fmt": "yuv420p",
+ "color_transfer": "bt709",
+ "r_frame_rate": "120/1",
+ "avg_frame_rate": "30000/1001",
+ "duration": "95.200000",
+ "disposition": {"default": 1, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "mov,mp4,m4a,3gp,3g2,mj2",
+ "duration": "95.200000"
+ }
+}
diff --git a/internal/mediahandler/testdata/probe/wav-mono.json b/internal/mediahandler/testdata/probe/wav-mono.json
new file mode 100644
index 000000000..74dad149b
--- /dev/null
+++ b/internal/mediahandler/testdata/probe/wav-mono.json
@@ -0,0 +1,23 @@
+{
+ "streams": [
+ {
+ "index": 0,
+ "codec_name": "pcm_s16le",
+ "codec_type": "audio",
+ "sample_fmt": "s16",
+ "sample_rate": "44100",
+ "channels": 1,
+ "channel_layout": "mono",
+ "r_frame_rate": "0/0",
+ "avg_frame_rate": "0/0",
+ "duration": "62.500000",
+ "disposition": {"default": 0, "attached_pic": 0}
+ }
+ ],
+ "format": {
+ "filename": "/scratch/in/source",
+ "nb_streams": 1,
+ "format_name": "wav",
+ "duration": "62.500000"
+ }
+}