carlos / platform Public

media: encodes, the byte-range playlist and child cleanup

Plan 3 Task 4 (provisional on plan 1's spike report). The video-720p
and audio-aac ffmpeg arguments (videoArgs, posterArgs, audioArgs, all
from cfg.Scratch), targetSize, readFMP4 over the fragmented MP4 the
encodes write (ftyp, moov, moof/mdat pairs, nothing else), and the HLS
version 7 byte-range playlist written in Go. packageOutput clamps the
reported duration to the grant (preflight F15).

Encodes run through runChild. A death by SIGKILL (the OOM killer) is
engine_failed for an encode; any other failure or signal stays
unreadable, and the probe is unchanged. A poster sought past the end
of the video stream is taken again from the first frame.

testdata/fmp4 was made by Debian 13's ffmpeg 7.1.5 with these exact
arguments (args.txt, provenance.txt); real-binary tests skip unless
CARLOS_MEDIA_FFMPEG and CARLOS_MEDIA_FFPROBE are set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8fb8fa990e5389edc40ef5cf1567e7d116d1dbad parent a409347
23 files changed, +4,365 −1
  • docs/superpowers/notes/media-conversion-copy-deck.md +4 −0
  • internal/mediahandler/encode_linux_test.go +193 −0
  • internal/mediahandler/ffmpeg.go +226 −0
  • internal/mediahandler/ffmpeg_test.go +485 −0
  • internal/mediahandler/fmp4.go +591 −0
  • internal/mediahandler/fmp4_synth_test.go +415 −0
  • internal/mediahandler/fmp4_test.go +459 −0
  • internal/mediahandler/geometry.go +38 −0
  • internal/mediahandler/playlist.go +131 −0
  • internal/mediahandler/procs.go +20 −0
  • internal/mediahandler/procs_linux.go +5 −1
  • internal/mediahandler/realencode_test.go +366 −0
  • internal/mediahandler/testdata/fmp4/args.txt +4 −0
  • internal/mediahandler/testdata/fmp4/audio.mp4 binary
  • internal/mediahandler/testdata/fmp4/audio.mp4.duration +1 −0
  • internal/mediahandler/testdata/fmp4/audio.mp4.packets.csv +423 −0
  • internal/mediahandler/testdata/fmp4/provenance.txt +39 −0
  • internal/mediahandler/testdata/fmp4/video-noaudio.mp4 binary
  • internal/mediahandler/testdata/fmp4/video-noaudio.mp4.duration +1 −0
  • internal/mediahandler/testdata/fmp4/video-noaudio.mp4.packets.csv +270 −0
  • internal/mediahandler/testdata/fmp4/video.mp4 binary
  • internal/mediahandler/testdata/fmp4/video.mp4.duration +1 −0
  • internal/mediahandler/testdata/fmp4/video.mp4.packets.csv +693 −0
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md
index 3909de6fc..54bd870bf 100644
--- a/docs/superpowers/notes/media-conversion-copy-deck.md
+++ b/docs/superpowers/notes/media-conversion-copy-deck.md
@@ -563,3 +563,7 @@ prints nothing.
| `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 |
+| `engine.encode.failed` | `codec: ffmpeg (%s) failed: %q` (pending Luna pass; plan 3 Task 4). `%s` is one of `video`, `poster`, `poster from the first frame`, `audio`; `%q` is the last 4 KiB of ffmpeg's stderr at `-loglevel error`, quoted so it stays one line |
+| `engine.encode.killed` | `codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory` (pending Luna pass; plan 3 Task 4). `%s` as `engine.encode.failed` |
+| `engine.encode.empty` | `codec: ffmpeg wrote no sample to %s` (pending Luna pass; plan 3 Task 4). `%s` is `video.mp4` or `audio.mp4` |
+| `engine.encode.unusable` | `codec: %s: %s` (pending Luna pass; plan 3 Task 4). The first `%s` is an output's name or `the output directory`; the second is the system's error or one of readFMP4's fixed reasons (a box type and a byte offset, never the file's bytes) |
diff --git a/internal/mediahandler/encode_linux_test.go b/internal/mediahandler/encode_linux_test.go
new file mode 100644
index 000000000..239fea5bd
--- /dev/null
+++ b/internal/mediahandler/encode_linux_test.go
@@ -0,0 +1,193 @@
+//go:build linux
+
+package mediahandler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "strings"
+ "syscall"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+func init() {
+ // die-<signal> kills itself with that signal.
+ for name, sig := range map[string]syscall.Signal{"die-sigkill": syscall.SIGKILL, "die-sigsegv": syscall.SIGSEGV, "die-sigabrt": syscall.SIGABRT} {
+ fakeScenarios[name] = func([]string) int {
+ _ = syscall.Kill(os.Getpid(), sig)
+ return blockForever() // until the signal lands
+ }
+ }
+ // encode writes a byte to its last argument (the output), as an
+ // encode that succeeds does; a poster sought anywhere but 0 finds no
+ // frame: it exits 1 having written a partial file, as Debian's
+ // ffmpeg 7.1.5 does past the video's end (encode-empty: exits 0
+ // having written nothing, as another build might).
+ fakeScenarios["encode"] = func(args []string) int {
+ if slices.Contains(args, "-frames:v") && argAfter(args, "-ss") != "0.000" {
+ _ = os.WriteFile(args[len(args)-1], nil, 0o600)
+ fmt.Fprintln(os.Stderr, "fake: Could not open encoder before EOF")
+ return 1
+ }
+ return fakeWriteOutput(args)
+ }
+ fakeScenarios["encode-empty"] = func(args []string) int {
+ if slices.Contains(args, "-frames:v") && argAfter(args, "-ss") != "0.000" {
+ return 0
+ }
+ return fakeWriteOutput(args)
+ }
+ // encode-poster-fails fails every poster.
+ fakeScenarios["encode-poster-fails"] = func(args []string) int {
+ if slices.Contains(args, "-frames:v") {
+ fmt.Fprintln(os.Stderr, "fake: Invalid data found when processing input")
+ return 1
+ }
+ return fakeWriteOutput(args)
+ }
+ // encode-poster-killed is killed by SIGKILL on the poster.
+ fakeScenarios["encode-poster-killed"] = func(args []string) int {
+ if slices.Contains(args, "-frames:v") {
+ _ = syscall.Kill(os.Getpid(), syscall.SIGKILL)
+ return blockForever()
+ }
+ return fakeWriteOutput(args)
+ }
+}
+
+// fakeWriteOutput writes one byte to the last argument, the output,
+// which must not exist: ffmpeg without -y, its stdin closed, refuses
+// to overwrite.
+func fakeWriteOutput(args []string) int {
+ f, err := os.OpenFile(args[len(args)-1], os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err == nil {
+ _, err = f.Write([]byte{1})
+ err = errors.Join(err, f.Close())
+ }
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "fake:", err)
+ return 1
+ }
+ return 0
+}
+
+// TestEncodeOutcomes: a clean exit is nil; a failure or a crash by a
+// signal is unreadable, its stderr tail logged; a SIGKILL (the OOM
+// killer) is engine_failed; a stopping task is its context's error; a
+// binary that will not start is engine_failed.
+func TestEncodeOutcomes(t *testing.T) {
+ for _, c := range []struct {
+ scenario, want, log string
+ }{
+ {"env", "nil", ""},
+ {"fail", media.CodeUnreadable, `ffmpeg (video) failed: "fake: Invalid data`},
+ {"die-sigsegv", media.CodeUnreadable, "ffmpeg (video) failed"},
+ {"die-sigabrt", media.CodeUnreadable, "ffmpeg (video) failed"},
+ {"die-sigkill", media.CodeEngineFailed, "killed by SIGKILL"},
+ } {
+ cfg, _ := fakeConfig(t, c.scenario)
+ var logs []string
+ cfg.Logf = func(format string, args ...any) { logs = append(logs, fmt.Sprintf(format, args...)) }
+ err := encode(context.Background(), cfg, "video", []string{"-i", "x"})
+ if got := codeOf(err); got != c.want {
+ t.Errorf("%s: %s, want %s", c.scenario, got, c.want)
+ }
+ if c.log != "" && !strings.Contains(strings.Join(logs, "\n"), c.log) {
+ t.Errorf("%s: logged %q, want %q", c.scenario, logs, c.log)
+ }
+ }
+ // The probe still calls a death by SIGKILL unreadable: only the
+ // encodes tell it apart.
+ cfg, _ := fakeConfig(t, "die-sigkill")
+ if _, err := probe(context.Background(), cfg, "mov", media.PresetVideo720p); codeOf(err) != media.CodeUnreadable {
+ t.Errorf("probe killed by SIGKILL: %s, want unreadable", codeOf(err))
+ }
+ cfg, _ = fakeConfig(t, "block")
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err := encode(ctx, cfg, "video", nil); !errors.Is(err, context.Canceled) {
+ t.Errorf("a stopping task: %v", err)
+ }
+ cfg.FFmpeg = "/nonexistent/ffmpeg"
+ if err := encode(context.Background(), cfg, "video", nil); codeOf(err) != media.CodeEngineFailed {
+ t.Errorf("no binary: %s", codeOf(err))
+ }
+}
+
+// TestEncodeVideoRunsVideoThenPoster: the video encode, then the
+// poster at 1 s; when that finds no frame (a header duration longer
+// than the video: ffmpeg fails, or exits 0 having written nothing), the
+// poster again from the first frame, over whatever the first run left.
+// Each run is the builders' arguments. A failed video encode starts no
+// poster; a poster at 0 or killed by SIGKILL is not run again.
+func TestEncodeVideoRunsVideoThenPoster(t *testing.T) {
+ f := goodVideo()
+ f.DurationMS = 3000
+ p := videoPayload(3000)
+ first := f
+ first.DurationMS = 0
+ for _, scenario := range []string{"encode", "encode-empty"} {
+ cfg, record := fakeConfig(t, scenario)
+ if err := encodeVideo(context.Background(), cfg, p, "mov", f); err != nil {
+ t.Fatalf("%s: %v", scenario, err)
+ }
+ runs := fakeRuns(t, record)
+ want := [][]string{videoArgs(cfg, f, p, "mov"), posterArgs(cfg, f, p, "mov"), posterArgs(cfg, first, p, "mov")}
+ if len(runs) != len(want) {
+ t.Fatalf("%s: %d runs, want %d", scenario, len(runs), len(want))
+ }
+ for i, r := range runs {
+ if !slices.Equal(r.Args, want[i]) {
+ t.Errorf("%s: run %d:\n got %q\nwant %q", scenario, i, r.Args, want[i])
+ }
+ }
+ for _, n := range []string{"video.mp4", "poster.jpg"} {
+ if b, err := os.ReadFile(outPath(cfg, n)); err != nil || len(b) != 1 {
+ t.Errorf("%s: %s: %d bytes, %v", scenario, n, len(b), err)
+ }
+ }
+ }
+ for _, c := range []struct {
+ scenario string
+ durationMS int64
+ want string
+ runs int
+ }{
+ // A poster found on the first try.
+ {"encode", 0, "nil", 2},
+ // A poster at 0 that fails is not tried again; one at 1 s is,
+ // once.
+ {"encode-poster-fails", 0, media.CodeUnreadable, 2},
+ {"encode-poster-fails", 3000, media.CodeUnreadable, 3},
+ {"encode-poster-killed", 3000, media.CodeEngineFailed, 2},
+ {"fail", 3000, media.CodeUnreadable, 1},
+ } {
+ cfg, record := fakeConfig(t, c.scenario)
+ f.DurationMS = c.durationMS
+ if err := encodeVideo(context.Background(), cfg, p, "mov", f); codeOf(err) != c.want {
+ t.Errorf("%s at %d ms: %s, want %s", c.scenario, c.durationMS, codeOf(err), c.want)
+ }
+ if n := len(fakeRuns(t, record)); n != c.runs {
+ t.Errorf("%s at %d ms: %d runs, want %d", c.scenario, c.durationMS, n, c.runs)
+ }
+ }
+}
+
+// TestEncodeAudioRunsAudioArgs: one run, audioArgs with the gain.
+func TestEncodeAudioRunsAudioArgs(t *testing.T) {
+ cfg, record := fakeConfig(t, "encode")
+ f := probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 2, DurationMS: 5000}
+ p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)}
+ if err := encodeAudio(context.Background(), cfg, p, "mov", f, -2.5); err != nil {
+ t.Fatal(err)
+ }
+ runs := fakeRuns(t, record)
+ if len(runs) != 1 || !slices.Equal(runs[0].Args, audioArgs(cfg, f, p, "mov", -2.5)) {
+ t.Errorf("runs %+v", runs)
+ }
+}
diff --git a/internal/mediahandler/ffmpeg.go b/internal/mediahandler/ffmpeg.go
new file mode 100644
index 000000000..13a9ea5d0
--- /dev/null
+++ b/internal/mediahandler/ffmpeg.go
@@ -0,0 +1,226 @@
+package mediahandler
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "math"
+ "os"
+ "path/filepath"
+ "strconv"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// The encoder settings plan 1's spike settles (provisional until its
+// report: plan 3 Task 4).
+const (
+ x264Preset = "veryfast"
+ x264CRF = 23
+)
+
+// The muxer settings: one fragmented MP4 with 4 s fragments, its
+// header first (empty_moov), each fragment's offsets relative to its
+// own moof (default_base_moof), and no mfra trailer (skip_trailer), so
+// the file is ftyp, moov, then moof/mdat pairs, which is what readFMP4
+// accepts. Video cuts a fragment at the first keyframe at least 4 s on
+// (keyframes come every 2 s); audio has no keyframe to wait for, so
+// the fragment duration itself is the trigger. TestMuxerArgsMatchTheFixtures
+// holds these to the arguments that made testdata/fmp4.
+const (
+ videoMovflags = "+frag_keyframe+empty_moov+default_base_moof+skip_trailer"
+ audioMovflags = "+empty_moov+default_base_moof+skip_trailer"
+ fragmentMicros = "4000000"
+)
+
+// sdrFilter scales to the output size; hdrFilter scales, then tone-maps
+// PQ or HLG to BT.709 SDR (spike: the chain and operator plan 1
+// confirms). %d:%d is the output size.
+const (
+ sdrFilter = "scale=%d:%d:flags=bicubic,format=yuv420p"
+ hdrFilter = "scale=%d:%d:flags=bicubic,zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709," +
+ "tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p"
+)
+
+// The outputs' names, in media.OutputNames order.
+var (
+ videoNames = media.OutputNames(media.PresetVideo720p) // video.mp4, video.m3u8, poster.jpg
+ audioNames = media.OutputNames(media.PresetAudioAAC) // audio.mp4, audio.m3u8, peaks.json
+)
+
+// outPath is <scratch>/out/<name>.
+func outPath(cfg Config, name string) string { return filepath.Join(cfg.Scratch, "out", name) }
+
+// msSeconds formats milliseconds as seconds with three decimals, as
+// ffmpeg's -t and -ss take them: 90500 is "90.500". A negative value is
+// "0.000".
+func msSeconds(ms int64) string {
+ ms = max(ms, 0)
+ return fmt.Sprintf("%d.%03d", ms/1000, ms%1000)
+}
+
+// stripArgs follow the maps of every encode: no subtitle or data
+// stream, none of the source's metadata or chapters (its location
+// included, spec §5.1), and at most the granted duration.
+func stripArgs(p media.Payload) []string {
+ return []string{"-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", msSeconds(p.Limits.GrantedMS)}
+}
+
+// videoFilter is the -vf of the video encode and the poster: the scale
+// to targetSize, with the tone map for an HDR source.
+func videoFilter(f probeFacts) string {
+ w, h := targetSize(f.Width, f.Height, f.Rotation)
+ if f.HDR {
+ return fmt.Sprintf(hdrFilter, w, h)
+ }
+ return fmt.Sprintf(sdrFilter, w, h)
+}
+
+// videoArgs are video-720p's encode: the chosen video stream (and audio
+// stream, when there is one) of the source, at most the granted
+// duration, to H.264 High at most 1280x720 and 30 fps with a keyframe
+// every 2 s, and AAC-LC stereo 48 kHz 128 kbit/s or no audio, in
+// <scratch>/out/video.mp4 (spec §5.1). The order is plan 3 Task 4's.
+func videoArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []string {
+ args := ffmpegInputArgs(cfg, demuxer)
+ args = append(args, "-map", "0:"+strconv.Itoa(f.VideoIndex))
+ if f.AudioIndex >= 0 {
+ args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex))
+ }
+ args = append(args, stripArgs(p)...)
+ args = append(args, "-vf", videoFilter(f),
+ "-c:v", "libx264", "-profile:v", "high", "-preset", x264Preset, "-crf", strconv.Itoa(x264CRF),
+ "-maxrate", "2500k", "-bufsize", "5000k", "-pix_fmt", "yuv420p", "-fpsmax", "30",
+ "-force_key_frames", "expr:gte(t,n_forced*2)", "-sc_threshold", "0")
+ if f.AudioIndex >= 0 {
+ args = append(args, "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-ar", "48000")
+ } else {
+ args = append(args, "-an")
+ }
+ return append(args, "-f", "mp4", "-movflags", videoMovflags, "-min_frag_duration", fragmentMicros,
+ outPath(cfg, videoNames[0]))
+}
+
+// posterTime is where the poster is taken, in milliseconds: 1 s in, or
+// the midpoint of a source shorter than 2 s (spec §5.1).
+func posterTime(durationMS int64) int64 {
+ if durationMS < 2000 {
+ return max(durationMS, 0) / 2
+ }
+ return 1000
+}
+
+// posterArgs are the poster's: the video stream alone, sought to
+// posterTime before the input (-ss is an input option there), through
+// the video encode's filter, one JPEG frame at
+// <scratch>/out/poster.jpg. The muxer is named (image2, one image), as
+// every output's is, rather than guessed from the file name.
+func posterArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []string {
+ in := ffmpegInputArgs(cfg, demuxer)
+ // -ss goes just before -i, after the other input options.
+ args := append([]string{}, in[:len(in)-2]...)
+ args = append(args, "-ss", msSeconds(posterTime(f.DurationMS)))
+ args = append(args, in[len(in)-2:]...)
+ args = append(args, "-map", "0:"+strconv.Itoa(f.VideoIndex), "-an")
+ args = append(args, stripArgs(p)...)
+ return append(args, "-vf", videoFilter(f), "-frames:v", "1", "-q:v", "3",
+ "-f", "image2", "-update", "1", outPath(cfg, videoNames[2]))
+}
+
+// audioArgs are audio-aac's encode: the chosen audio stream, at most
+// the granted duration, at 48 kHz, mono for a mono source and stereo
+// otherwise (more channels mixed down), with the one linear gain
+// gainDB (plan 3 Task 5; a gain that is not a finite number is none),
+// to AAC-LC at 64 or 128 kbit/s in <scratch>/out/audio.mp4 (spec §5.1).
+func audioArgs(cfg Config, f probeFacts, p media.Payload, demuxer string, gainDB float64) []string {
+ layout, rate := "stereo", "128k"
+ if f.Channels == 1 {
+ layout, rate = "mono", "64k"
+ }
+ if math.IsNaN(gainDB) || math.IsInf(gainDB, 0) {
+ gainDB = 0
+ }
+ args := ffmpegInputArgs(cfg, demuxer)
+ args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex), "-vn")
+ args = append(args, stripArgs(p)...)
+ return append(args,
+ "-af", "aformat=channel_layouts="+layout+":sample_rates=48000,volume="+strconv.FormatFloat(gainDB, 'f', 2, 64)+"dB",
+ "-c:a", "aac", "-b:a", rate,
+ "-f", "mp4", "-movflags", audioMovflags, "-frag_duration", fragmentMicros,
+ outPath(cfg, audioNames[0]))
+}
+
+// encodeVideo runs video-720p's two encodes through runChild: the
+// video, then the poster. A poster sought past the end of the video
+// stream (a header duration longer than the video's) finds no frame:
+// Debian's ffmpeg 7.1.5 then fails to open the JPEG encoder and exits
+// 1 (another build may exit 0 having written nothing). Either way,
+// when the poster was sought past 0, it is taken again from the first
+// frame, and only that run's failure fails the job.
+func encodeVideo(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts) error {
+ if err := encode(ctx, cfg, "video", videoArgs(cfg, f, p, demuxer)); err != nil {
+ return err
+ }
+ poster := outPath(cfg, videoNames[2])
+ err := encode(ctx, cfg, "poster", posterArgs(cfg, f, p, demuxer))
+ var je jobError
+ switch {
+ case posterTime(f.DurationMS) == 0:
+ return err
+ case err == nil:
+ if _, serr := os.Lstat(poster); !errors.Is(serr, fs.ErrNotExist) {
+ return nil // collect checks what is there
+ }
+ case !errors.As(err, &je) || je.code != media.CodeUnreadable:
+ return err // a stopping task, or the engine's failure
+ }
+ if err := os.Remove(poster); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return packageFailed(cfg, videoNames[2], err)
+ }
+ first := f
+ first.DurationMS = 0 // posterTime 0
+ return encode(ctx, cfg, "poster from the first frame", posterArgs(cfg, first, p, demuxer))
+}
+
+// encodeAudio runs audio-aac's encode through runChild.
+func encodeAudio(ctx context.Context, cfg Config, p media.Payload, demuxer string, f probeFacts, gainDB float64) error {
+ return encode(ctx, cfg, "audio", audioArgs(cfg, f, p, demuxer, gainDB))
+}
+
+// encodeLogTail is how much of a failed encode's stderr reaches the log.
+const encodeLogTail = 4 << 10
+
+// encode runs one ffmpeg encode (what names it in the log) in
+// <scratch>/tmp and maps its outcome:
+//
+// - a clean exit: nil;
+// - ctx ending (the task stopping): ctx's error;
+// - engine_failed from runChild (no start, a failed cleanup): as is;
+// - death by SIGKILL: engine_failed. Nothing in the handler sends it
+// before the child has exited or ctx has ended, so it is the
+// kernel's OOM killer (the task's memory, not the source, is what
+// ran out), and the operator, not the tenant, has to act;
+// - any other failure, a crash by another signal included:
+// unreadable, logged with the last encodeLogTail bytes of ffmpeg's
+// stderr (quoted, so it stays one line), which -loglevel error
+// keeps to errors, never the source's metadata (preflight F19).
+func encode(ctx context.Context, cfg Config, what string, args []string) error {
+ tail, err := runChild(ctx, cfg, cfg.FFmpeg, args, filepath.Join(cfg.Scratch, "tmp"))
+ 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 killedBySIGKILL(err):
+ // engine.encode.killed (pending Luna pass).
+ cfg.Logf("codec: ffmpeg (%s) was killed by SIGKILL, likely out of memory", what)
+ return jobError{media.CodeEngineFailed}
+ }
+ // engine.encode.failed (pending Luna pass).
+ cfg.Logf("codec: ffmpeg (%s) failed: %q", what, tail[max(0, len(tail)-encodeLogTail):])
+ return jobError{media.CodeUnreadable}
+}
diff --git a/internal/mediahandler/ffmpeg_test.go b/internal/mediahandler/ffmpeg_test.go
new file mode 100644
index 000000000..6cd6ecba2
--- /dev/null
+++ b/internal/mediahandler/ffmpeg_test.go
@@ -0,0 +1,485 @@
+package mediahandler
+
+import (
+ "bytes"
+ "math"
+ "os"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// TestTargetSizeTable: the output box is 1280x720 or 720x1280, never
+// upscaled, the rotation applied first, integer arithmetic, each side
+// even and at least 2 (plan 3 Task 4's table).
+func TestTargetSizeTable(t *testing.T) {
+ for _, c := range []struct{ w, h, rot, ow, oh int }{
+ {1920, 1080, 0, 1280, 720},
+ {1080, 1920, 0, 720, 1280},
+ {1920, 1080, -90, 720, 1280},
+ {1920, 1080, 90, 720, 1280},
+ {1920, 1080, 180, 1280, 720},
+ {640, 360, 0, 640, 360},
+ {640, 360, -90, 360, 640},
+ // 1281·720 = 922,320 < 721·1280 = 922,880: height-limited,
+ // 1281·720/721 = 1279, rounded down to even.
+ {1281, 721, 0, 1278, 720},
+ {3840, 2160, 0, 1280, 720},
+ // Portrait box 720x1280: 1000·1280 < 3000·720, height-limited,
+ // 1000·1280/3000 = 426.
+ {1000, 3000, 0, 426, 1280},
+ {4000, 2, 0, 1280, 2},
+ {2, 4000, 0, 2, 1280},
+ // Square: the landscape box, height-limited.
+ {1000, 1000, 0, 720, 720},
+ // Odd sides inside the box: rounded down to even.
+ {641, 361, 0, 640, 360},
+ {1, 1, 0, 2, 2},
+ // Exactly the box, and one pixel over it on each side.
+ {1280, 720, 0, 1280, 720},
+ {1281, 720, 0, 1280, 718},
+ {1280, 721, 0, 1278, 720},
+ // The largest sources check admits.
+ {4096, 2025, 0, 1280, 632},
+ {2160, 3840, 0, 720, 1280},
+ } {
+ ow, oh := targetSize(c.w, c.h, c.rot)
+ if ow != c.ow || oh != c.oh {
+ t.Errorf("%dx%d rotation %d: %dx%d, want %dx%d", c.w, c.h, c.rot, ow, oh, c.ow, c.oh)
+ }
+ }
+}
+
+// TestTargetSizeProperties: over a sweep of sizes, the output fits its
+// box, is never larger than the (rotated) source, keeps the aspect
+// within a pixel and a half of rounding, and is even.
+func TestTargetSizeProperties(t *testing.T) {
+ for w := 1; w <= 4096; w += 37 {
+ for h := 1; h <= 4096; h += 41 {
+ ow, oh := targetSize(w, h, 0)
+ bw, bh := 1280, 720
+ if w < h {
+ bw, bh = 720, 1280
+ }
+ if ow%2 != 0 || oh%2 != 0 || ow < 2 || oh < 2 || ow > bw || oh > bh {
+ t.Fatalf("%dx%d: %dx%d", w, h, ow, oh)
+ }
+ if ow > max(w, 2) || oh > max(h, 2) {
+ t.Fatalf("%dx%d: upscaled to %dx%d", w, h, ow, oh)
+ }
+ if w >= 64 && h >= 64 {
+ // ow/oh against w/h, in the output's pixels.
+ if d := math.Abs(float64(ow) - float64(oh)*float64(w)/float64(h)); d > 2 && math.Abs(float64(oh)-float64(ow)*float64(h)/float64(w)) > 2 {
+ t.Fatalf("%dx%d: %dx%d loses the aspect", w, h, ow, oh)
+ }
+ }
+ }
+ }
+}
+
+// videoPayload is a video-720p payload granting grantedMS.
+func videoPayload(grantedMS int64) media.Payload {
+ l := limitsFor(media.PresetVideo720p)
+ l.GrantedMS = grantedMS
+ return media.Payload{Preset: media.PresetVideo720p, Limits: l}
+}
+
+// inputPrefix is every encode's arguments up to the input, for the
+// scratch /scratch: ffmpegInputArgs, written out.
+func inputPrefix(demuxer string) []string {
+ args := []string{"-hide_banner", "-nostats", "-loglevel", "error", "-nostdin", "-protocol_whitelist", "file", "-f", demuxer}
+ if demuxer == "mov" {
+ args = append(args, "-enable_drefs", "0")
+ }
+ return append(args, "-max_pixels", "16777216", "-codec_whitelist", codecWhitelist, "-i", "/scratch/in/source")
+}
+
+// TestVideoArgsSDRLandscape: the exact arguments for a 1080p H.264 with
+// audio granted 61.5 s.
+func TestVideoArgsSDRLandscape(t *testing.T) {
+ cfg := Config{Scratch: "/scratch"}
+ f := goodVideo() // 1920x1080 h264, audio at 1
+ got := videoArgs(cfg, f, videoPayload(61500), "mov")
+ want := append(inputPrefix("mov"),
+ "-map", "0:0", "-map", "0:1",
+ "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "61.500",
+ "-vf", "scale=1280:720:flags=bicubic,format=yuv420p",
+ "-c:v", "libx264", "-profile:v", "high", "-preset", "veryfast", "-crf", "23",
+ "-maxrate", "2500k", "-bufsize", "5000k", "-pix_fmt", "yuv420p", "-fpsmax", "30",
+ "-force_key_frames", "expr:gte(t,n_forced*2)", "-sc_threshold", "0",
+ "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-ar", "48000",
+ "-f", "mp4", "-movflags", "+frag_keyframe+empty_moov+default_base_moof+skip_trailer",
+ "-min_frag_duration", "4000000", "/scratch/out/video.mp4")
+ if !slices.Equal(got, want) {
+ t.Errorf("videoArgs:\n got %q\nwant %q", got, want)
+ }
+ // Every path is under cfg.Scratch (F21).
+ other := videoArgs(Config{Scratch: "/elsewhere"}, f, videoPayload(61500), "mov")
+ if strings.Contains(strings.Join(other, " "), "/scratch") {
+ t.Errorf("a path outside cfg.Scratch: %q", other)
+ }
+}
+
+// TestVideoArgsPortraitHDR (Review Focus 1): an iPhone portrait clip,
+// HEVC HLG with a -90 rotation, and a Dolby Vision 8.4 one. Both get a
+// 720x1280 output with the tone map, the video and the poster alike.
+func TestVideoArgsPortraitHDR(t *testing.T) {
+ cfg := Config{Scratch: "/scratch"}
+ hdr := "scale=720:1280:flags=bicubic,zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709," +
+ "tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p"
+ for _, name := range []string{"iphone-hevc-hlg-portrait", "dolby-vision-8-4"} {
+ f, err := parseProbe(fixture(t, name), media.PresetVideo720p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !f.HDR || (f.Rotation != -90 && f.Rotation != 90) {
+ t.Fatalf("%s: the fixture is not a rotated HDR portrait: %+v", name, f)
+ }
+ for what, args := range map[string][]string{
+ "video": videoArgs(cfg, f, videoPayload(60000), "mov"),
+ "poster": posterArgs(cfg, f, videoPayload(60000), "mov"),
+ } {
+ if vf := argAfter(args, "-vf"); vf != hdr {
+ t.Errorf("%s %s: -vf %q, want %q", name, what, vf, hdr)
+ }
+ }
+ }
+ // An SDR portrait source (1080x1920, no rotation) has no tone map.
+ f := goodVideo()
+ f.Width, f.Height = 1080, 1920
+ if vf := argAfter(videoArgs(cfg, f, videoPayload(60000), "mov"), "-vf"); vf != "scale=720:1280:flags=bicubic,format=yuv420p" {
+ t.Errorf("SDR portrait: -vf %q", vf)
+ }
+}
+
+// argAfter is the argument after the last flag in args, "" if none.
+func argAfter(args []string, flag string) string {
+ for i := len(args) - 2; i >= 0; i-- {
+ if args[i] == flag {
+ return args[i+1]
+ }
+ }
+ return ""
+}
+
+// TestVideoWithoutAudio (Review Focus 5): a source with no audio maps
+// the video alone and asks for no audio; the real ffmpeg's file from
+// those arguments (testdata/fmp4/video-noaudio.mp4) is one track and
+// yields a valid playlist.
+func TestVideoWithoutAudio(t *testing.T) {
+ cfg := Config{Scratch: "/scratch"}
+ f := goodVideo()
+ f.AudioIndex, f.AudioCodec, f.Channels = -1, "", 0
+ args := videoArgs(cfg, f, videoPayload(60000), "mov")
+ joined := strings.Join(args, " ")
+ if strings.Count(joined, "-map ") != 1 || !strings.Contains(joined, "-map 0:0 ") {
+ t.Errorf("maps: %q", args)
+ }
+ if !slices.Contains(args, "-an") || slices.Contains(args, "-c:a") {
+ t.Errorf("audio options: %q", args)
+ }
+ b := readFixture(t, "video-noaudio.mp4")
+ initLen, frags, durationMS, err := readFMP4(bytes.NewReader(b), int64(len(b)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if n := bytes.Count(b[:initLen], []byte("trak")); n != 1 {
+ t.Errorf("%d tracks, want 1", n)
+ }
+ var pl bytes.Buffer
+ if err := writePlaylist(&pl, "video.mp4", initLen, frags); err != nil {
+ t.Fatal(err)
+ }
+ checkPlaylist(t, pl.String(), "video.mp4", initLen, int64(len(b)), durationMS)
+}
+
+// TestPosterTime: 1 s in, or the midpoint of a source under 2 s.
+func TestPosterTime(t *testing.T) {
+ for _, c := range []struct {
+ ms int64
+ want string
+ }{
+ {5000, "1.000"}, {1500, "0.750"}, {2000, "1.000"}, {1999, "0.999"}, {1, "0.000"}, {0, "0.000"}, {7200000, "1.000"},
+ } {
+ if got := msSeconds(posterTime(c.ms)); got != c.want {
+ t.Errorf("%d ms: %s, want %s", c.ms, got, c.want)
+ }
+ f := goodVideo()
+ f.DurationMS = c.ms
+ if got := argAfter(posterArgs(Config{Scratch: "/scratch"}, f, videoPayload(7200000), "mov"), "-ss"); got != c.want {
+ t.Errorf("%d ms: posterArgs -ss %s, want %s", c.ms, got, c.want)
+ }
+ }
+}
+
+// TestPosterArgs: the exact poster arguments; -ss is an input option,
+// just before -i.
+func TestPosterArgs(t *testing.T) {
+ f := goodVideo()
+ f.DurationMS = 1500
+ got := posterArgs(Config{Scratch: "/scratch"}, f, videoPayload(1500), "matroska")
+ in := inputPrefix("matroska")
+ want := slices.Concat(in[:len(in)-2], []string{"-ss", "0.750"}, in[len(in)-2:], []string{
+ "-map", "0:0", "-an", "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "1.500",
+ "-vf", "scale=1280:720:flags=bicubic,format=yuv420p", "-frames:v", "1", "-q:v", "3",
+ "-f", "image2", "-update", "1", "/scratch/out/poster.jpg"})
+ if !slices.Equal(got, want) {
+ t.Errorf("posterArgs:\n got %q\nwant %q", got, want)
+ }
+}
+
+// TestAudioArgsMonoAndStereo: mono 64k for a mono source; stereo 128k
+// for stereo, 5.1 or an unknown channel count; the gain with two
+// decimals, and none when it is not a finite number.
+func TestAudioArgsMonoAndStereo(t *testing.T) {
+ cfg := Config{Scratch: "/scratch"}
+ p := media.Payload{Preset: media.PresetAudioAAC, Limits: limitsFor(media.PresetAudioAAC)}
+ p.Limits.GrantedMS = 7200000
+ f := probeFacts{VideoIndex: -1, AudioIndex: 2, AudioCodec: "flac", Channels: 1, DurationMS: 5000}
+ want := append(inputPrefix("matroska"),
+ "-map", "0:2", "-vn", "-sn", "-dn", "-map_metadata", "-1", "-map_chapters", "-1", "-t", "7200.000",
+ "-af", "aformat=channel_layouts=mono:sample_rates=48000,volume=-3.25dB",
+ "-c:a", "aac", "-b:a", "64k",
+ "-f", "mp4", "-movflags", "+empty_moov+default_base_moof+skip_trailer", "-frag_duration", "4000000",
+ "/scratch/out/audio.mp4")
+ if got := audioArgs(cfg, f, p, "matroska", -3.25); !slices.Equal(got, want) {
+ t.Errorf("mono:\n got %q\nwant %q", got, want)
+ }
+ for _, ch := range []int{2, 6, 0} {
+ f.Channels = ch
+ got := audioArgs(cfg, f, p, "matroska", 1)
+ if af := argAfter(got, "-af"); af != "aformat=channel_layouts=stereo:sample_rates=48000,volume=1.00dB" {
+ t.Errorf("%d channels: -af %q", ch, af)
+ }
+ if br := argAfter(got, "-b:a"); br != "128k" {
+ t.Errorf("%d channels: -b:a %q", ch, br)
+ }
+ }
+ for _, g := range []float64{math.NaN(), math.Inf(1), math.Inf(-1)} {
+ if af := argAfter(audioArgs(cfg, f, p, "matroska", g), "-af"); !strings.HasSuffix(af, ",volume=0.00dB") {
+ t.Errorf("gain %v: -af %q", g, af)
+ }
+ }
+}
+
+// TestPlaylistGolden: the exact playlist for three fragments.
+func TestPlaylistGolden(t *testing.T) {
+ frags := []fragment{
+ {Offset: 1276, Length: 196386, DurationS: 4},
+ {Offset: 197662, Length: 204818, DurationS: 4.0213333},
+ {Offset: 402480, Length: 51611, DurationS: 0.9995},
+ }
+ var b bytes.Buffer
+ if err := writePlaylist(&b, "video.mp4", 1276, frags); err != nil {
+ t.Fatal(err)
+ }
+ want := `#EXTM3U
+#EXT-X-VERSION:7
+#EXT-X-TARGETDURATION:5
+#EXT-X-PLAYLIST-TYPE:VOD
+#EXT-X-INDEPENDENT-SEGMENTS
+#EXT-X-MAP:URI="video.mp4",BYTERANGE="1276@0"
+#EXTINF:4.000,
+#EXT-X-BYTERANGE:196386@1276
+video.mp4
+#EXTINF:4.021,
+#EXT-X-BYTERANGE:204818@197662
+video.mp4
+#EXTINF:1.000,
+#EXT-X-BYTERANGE:51611@402480
+video.mp4
+#EXT-X-ENDLIST
+`
+ if b.String() != want {
+ t.Errorf("playlist:\n%s\nwant:\n%s", b.String(), want)
+ }
+ // Whole 4 s fragments: the target is 4.
+ b.Reset()
+ if err := writePlaylist(&b, "audio.mp4", 700, []fragment{{700, 10, 4}, {710, 10, 4}}); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(b.String(), "#EXT-X-TARGETDURATION:4\n") {
+ t.Errorf("target for 4 s fragments:\n%s", b.String())
+ }
+}
+
+// TestPlaylistRefuses: a name that could break a line or the URI, and
+// fragments readFMP4 never answers.
+func TestPlaylistRefuses(t *testing.T) {
+ ok := []fragment{{Offset: 100, Length: 10, DurationS: 4}}
+ for name, c := range map[string]struct {
+ name string
+ initLen int64
+ frags []fragment
+ }{
+ "quote": {`a".mp4`, 100, ok},
+ "newline": {"a\n#EXT-X-ENDLIST\nb.mp4", 100, ok},
+ "slash": {"../video.mp4", 100, ok},
+ "dot first": {".mp4", 100, ok},
+ "empty name": {"", 100, ok},
+ "no header": {"v.mp4", 0, ok},
+ "no fragment": {"v.mp4", 100, nil},
+ "before the header": {"v.mp4", 101, ok},
+ "no length": {"v.mp4", 100, []fragment{{100, 0, 4}}},
+ "no duration": {"v.mp4", 100, []fragment{{100, 10, 0}}},
+ "negative duration": {"v.mp4", 100, []fragment{{100, 10, -1}}},
+ "NaN duration": {"v.mp4", 100, []fragment{{100, 10, math.NaN()}}},
+ "infinite duration": {"v.mp4", 100, []fragment{{100, 10, math.Inf(1)}}},
+ } {
+ var b bytes.Buffer
+ if err := writePlaylist(&b, c.name, c.initLen, c.frags); err == nil || b.Len() != 0 {
+ t.Errorf("%s: %v, wrote %d bytes", name, err, b.Len())
+ }
+ }
+}
+
+// checkPlaylist parses a playlist writePlaylist wrote and checks it
+// against the file it names: the header, the map, byte ranges that are
+// contiguous from the map's end to the file's, durations that sum to
+// durationMS within a millisecond and round to at most the target.
+func checkPlaylist(t *testing.T, pl, name string, initLen, size, durationMS int64) {
+ t.Helper()
+ lines := strings.Split(strings.TrimSuffix(pl, "\n"), "\n")
+ head := []string{"#EXTM3U", "#EXT-X-VERSION:7", "", "#EXT-X-PLAYLIST-TYPE:VOD", "#EXT-X-INDEPENDENT-SEGMENTS",
+ `#EXT-X-MAP:URI="` + name + `",BYTERANGE="` + itoa(initLen) + `@0"`}
+ if len(lines) < len(head)+4 || lines[len(lines)-1] != "#EXT-X-ENDLIST" {
+ t.Fatalf("playlist:\n%s", pl)
+ }
+ var target int64
+ for i, h := range head {
+ if i == 2 {
+ if !strings.HasPrefix(lines[2], "#EXT-X-TARGETDURATION:") {
+ t.Fatalf("line 3: %q", lines[2])
+ }
+ target = atoi(t, strings.TrimPrefix(lines[2], "#EXT-X-TARGETDURATION:"))
+ continue
+ }
+ if lines[i] != h {
+ t.Errorf("line %d: %q, want %q", i+1, lines[i], h)
+ }
+ }
+ body := lines[len(head) : len(lines)-1]
+ if len(body)%3 != 0 {
+ t.Fatalf("entries are not three lines each:\n%s", pl)
+ }
+ at, total := initLen, 0.0
+ for i := 0; i < len(body); i += 3 {
+ d := strings.TrimSuffix(strings.TrimPrefix(body[i], "#EXTINF:"), ",")
+ secs := parseFloat(t, d)
+ if math.Round(secs) > float64(target) {
+ t.Errorf("EXTINF %s rounds past the target %d", d, target)
+ }
+ total += secs
+ length, off, ok := strings.Cut(strings.TrimPrefix(body[i+1], "#EXT-X-BYTERANGE:"), "@")
+ if !ok || atoi(t, off) != at || body[i+2] != name {
+ t.Errorf("entry %d: %q %q at %d", i/3, body[i+1], body[i+2], at)
+ }
+ at += atoi(t, length)
+ }
+ if at != size {
+ t.Errorf("the ranges end at %d, the file at %d", at, size)
+ }
+ if math.Abs(total*1000-float64(durationMS)) > 1+float64(len(body)/3)*0.5 {
+ t.Errorf("EXTINF sum %.3f s, duration %d ms", total, durationMS)
+ }
+}
+
+// TestPackageOutput: the playlist is written beside the media file, a
+// new file; the duration is readFMP4's, clamped to the grant (F15:
+// audio.mp4's fragments sum to 9.022 s under a 9 s grant); a file with
+// no fragment is unreadable; a missing file, a symlink, a directory, a
+// broken file or an existing playlist is engine_failed, and writes no
+// playlist.
+func TestPackageOutput(t *testing.T) {
+ setup := func(t *testing.T) Config {
+ cfg := Config{Scratch: t.TempDir(), Logf: t.Logf}
+ if err := prepareScratch(cfg.Scratch); err != nil {
+ t.Fatal(err)
+ }
+ return cfg
+ }
+ audio := readFixture(t, "audio.mp4")
+ boxes := topBoxes(t, audio)
+ initLen := boxes[1].off + boxes[1].size
+ p := media.Payload{Preset: media.PresetAudioAAC, Limits: media.JobLimits{GrantedMS: 9000}}
+ for _, c := range []struct {
+ granted, want int64
+ }{{9000, 9000}, {9021, 9021}, {9022, 9022}, {60000, 9022}} {
+ cfg := setup(t)
+ if err := os.WriteFile(outPath(cfg, "audio.mp4"), audio, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ p.Limits.GrantedMS = c.granted
+ got, err := packageOutput(cfg, p, "audio.mp4", "audio.m3u8")
+ if err != nil || got != c.want {
+ t.Errorf("granted %d: %d, %v; want %d", c.granted, got, err, c.want)
+ continue
+ }
+ pl, err := os.ReadFile(outPath(cfg, "audio.m3u8"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkPlaylist(t, string(pl), "audio.mp4", initLen, int64(len(audio)), 9022)
+ if fi, err := os.Stat(outPath(cfg, "audio.m3u8")); err != nil || fi.Mode().Perm() != 0o600 {
+ t.Errorf("playlist mode: %v %v", fi.Mode(), err)
+ }
+ // A second run finds the playlist there and refuses it.
+ if _, err := packageOutput(cfg, p, "audio.mp4", "audio.m3u8"); codeOf(err) != media.CodeEngineFailed {
+ t.Errorf("an existing playlist: %s", codeOf(err))
+ }
+ }
+ for name, make := range map[string]func(cfg Config) error{
+ "missing": func(Config) error { return nil },
+ "symlink": func(cfg Config) error { return os.Symlink("/etc/passwd", outPath(cfg, "audio.mp4")) },
+ // A link to a good copy beside it, inside the directory.
+ "symlink to a sibling": func(cfg Config) error {
+ if err := os.WriteFile(outPath(cfg, "copy.mp4"), audio, 0o600); err != nil {
+ return err
+ }
+ return os.Symlink("copy.mp4", outPath(cfg, "audio.mp4"))
+ },
+ "directory": func(cfg Config) error { return os.Mkdir(outPath(cfg, "audio.mp4"), 0o700) },
+ "broken": func(cfg Config) error { return os.WriteFile(outPath(cfg, "audio.mp4"), audio[:len(audio)-1], 0o600) },
+ } {
+ cfg := setup(t)
+ if err := make(cfg); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := packageOutput(cfg, p, "audio.mp4", "audio.m3u8"); codeOf(err) != media.CodeEngineFailed {
+ t.Errorf("%s: %s, want engine_failed", name, codeOf(err))
+ }
+ if _, err := os.Lstat(outPath(cfg, "audio.m3u8")); !os.IsNotExist(err) {
+ t.Errorf("%s: a playlist was written", name)
+ }
+ }
+ cfg := setup(t)
+ if err := os.WriteFile(outPath(cfg, "audio.mp4"), audio[:boxes[2].off], 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := packageOutput(cfg, p, "audio.mp4", "audio.m3u8"); codeOf(err) != media.CodeUnreadable {
+ t.Errorf("no fragment: %s, want unreadable", codeOf(err))
+ }
+}
+
+func itoa(n int64) string { return strconv.FormatInt(n, 10) }
+
+func atoi(t *testing.T, s string) int64 {
+ t.Helper()
+ n, err := strconv.ParseInt(s, 10, 64)
+ if err != nil {
+ t.Fatalf("%q: %v", s, err)
+ }
+ return n
+}
+
+func parseFloat(t *testing.T, s string) float64 {
+ t.Helper()
+ v, err := strconv.ParseFloat(s, 64)
+ if err != nil {
+ t.Fatalf("%q: %v", s, err)
+ }
+ return v
+}
diff --git a/internal/mediahandler/fmp4.go b/internal/mediahandler/fmp4.go
new file mode 100644
index 000000000..9e7e2fbeb
--- /dev/null
+++ b/internal/mediahandler/fmp4.go
@@ -0,0 +1,591 @@
+package mediahandler
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "io"
+ "math/bits"
+)
+
+// fragment is one moof and its mdat: the byte range a playlist entry
+// names, and its duration.
+type fragment struct {
+ Offset, Length int64
+ DurationS float64
+}
+
+// Bounds on what readFMP4 reads into memory or keeps.
+const (
+ maxFragments = 1_000_000
+ // maxHeaderBox bounds a moov or a moof read whole: the encodes'
+ // are a few KiB (a 4 s fragment of 60 fps video is under 4 KiB).
+ maxHeaderBox = 4 << 20
+)
+
+// errNoFragments is a file with a header and no fragment: the encode
+// wrote no sample at all.
+var errNoFragments = errors.New("no fragment")
+
+// readFMP4 reads the fragmented MP4 the encodes write (videoArgs,
+// audioArgs) and answers the header's length, every fragment and the
+// duration in milliseconds, rounded up.
+//
+// The file must be exactly a top-level ftyp, a moov, then one or more
+// moof/mdat pairs, every box inside the file: the sequence these
+// arguments make with skip_trailer (no mfra, no free; testdata/fmp4,
+// made by Debian 13's ffmpeg 7.1.5). The timeline is the first video
+// track's (its hdlr is "vide"), else the first track's, in its mdhd
+// timescale. Each fragment's duration is the next fragment's tfdt less
+// its own, strictly increasing; the last one's is the sum of its trun
+// sample durations. Each traf must use default-base-is-moof (and no
+// base_data_offset) and carry its trun data offset, and every sample's
+// bytes must lie inside the fragment's own mdat, so a byte range names
+// whole samples. Anything else (another box or order, a box past the
+// file or its parent, a 64-bit size that does not fit, a zero-sized or
+// to-the-end box, over maxFragments fragments, a duration that
+// overflows) is an error. No error quotes the file's bytes.
+func readFMP4(r io.ReaderAt, size int64) (initLen int64, frags []fragment, durationMS int64, err error) {
+ if size <= 0 {
+ return 0, nil, 0, errors.New("empty file")
+ }
+ ftyp, err := topBox(r, 0, size, "ftyp")
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ moov, err := topBox(r, ftyp.end(), size, "moov")
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ body, err := readBody(r, moov)
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ tl, err := parseMoov(body)
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ initLen = moov.end()
+ var starts []uint64 // each fragment's tfdt on the timeline
+ var lastDur uint64 // the last fragment's trun durations
+ for off := initLen; off < size; {
+ if len(frags) == maxFragments {
+ return 0, nil, 0, fmt.Errorf("over %d fragments", maxFragments)
+ }
+ moof, err := topBox(r, off, size, "moof")
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ mdat, err := topBox(r, moof.end(), size, "mdat")
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ body, err := readBody(r, moof)
+ if err != nil {
+ return 0, nil, 0, err
+ }
+ start, dur, err := parseMoof(body, moof, mdat, tl)
+ if err != nil {
+ return 0, nil, 0, fmt.Errorf("fragment %d: %w", len(frags), err)
+ }
+ if n := len(starts); n > 0 && start <= starts[n-1] {
+ return 0, nil, 0, fmt.Errorf("fragment %d: tfdt does not increase", len(frags))
+ }
+ starts, lastDur = append(starts, start), dur
+ frags = append(frags, fragment{Offset: moof.off, Length: mdat.end() - moof.off})
+ off = mdat.end()
+ }
+ if len(frags) == 0 {
+ return 0, nil, 0, errNoFragments
+ }
+ if lastDur == 0 {
+ return 0, nil, 0, errors.New("the last fragment has no duration")
+ }
+ ts := float64(tl.timescale)
+ for i := range frags {
+ var ticks uint64
+ if i+1 < len(frags) {
+ ticks = starts[i+1] - starts[i]
+ } else {
+ ticks = lastDur
+ }
+ frags[i].DurationS = float64(ticks) / ts
+ }
+ last := starts[len(starts)-1] - starts[0]
+ total, carry := bits.Add64(last, lastDur, 0)
+ if carry != 0 {
+ return 0, nil, 0, errors.New("the duration overflows")
+ }
+ if durationMS, err = ticksToMS(total, tl.timescale); err != nil {
+ return 0, nil, 0, err
+ }
+ return initLen, frags, durationMS, nil
+}
+
+// ticksToMS is ticks/timescale seconds in milliseconds, rounded up; an
+// error past maxDurationMS.
+func ticksToMS(ticks uint64, timescale uint32) (int64, error) {
+ ts := uint64(timescale)
+ secs, rem := ticks/ts, ticks%ts
+ if secs > uint64(maxDurationMS/1000) {
+ return 0, errors.New("the duration is implausible")
+ }
+ frac := (rem*1000 + ts - 1) / ts // rem < ts < 2^32: no overflow
+ return int64(secs)*1000 + int64(frac), nil
+}
+
+// fileBox is one top-level box: its offset, header length and size.
+type fileBox struct {
+ typ string
+ off, size int64
+ hdr int64
+}
+
+func (b fileBox) end() int64 { return b.off + b.size }
+
+// topBox reads the box header at off, which must be of type want and lie
+// inside [off, limit).
+func topBox(r io.ReaderAt, off, limit int64, want string) (fileBox, error) {
+ if limit-off < 8 {
+ return fileBox{}, fmt.Errorf("want %s at %d: the file ends", want, off)
+ }
+ var h [16]byte
+ if _, err := r.ReadAt(h[:8], off); err != nil {
+ return fileBox{}, fmt.Errorf("reading the box at %d: %w", off, errRead(err))
+ }
+ b := fileBox{typ: string(h[4:8]), off: off, hdr: 8}
+ if b.typ != want {
+ return fileBox{}, fmt.Errorf("want %s at %d, found another box", want, off)
+ }
+ size := uint64(binary.BigEndian.Uint32(h[:4]))
+ if size == 1 {
+ if limit-off < 16 {
+ return fileBox{}, fmt.Errorf("%s at %d: the file ends", want, off)
+ }
+ if _, err := r.ReadAt(h[8:16], off+8); err != nil {
+ return fileBox{}, fmt.Errorf("reading the box at %d: %w", off, errRead(err))
+ }
+ size, b.hdr = binary.BigEndian.Uint64(h[8:16]), 16
+ }
+ if size < uint64(b.hdr) || size > uint64(limit-off) {
+ return fileBox{}, fmt.Errorf("%s at %d: its size does not fit the file", want, off)
+ }
+ b.size = int64(size)
+ return b, nil
+}
+
+// errRead keeps a read error's kind and nothing of the file.
+func errRead(err error) error {
+ if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
+ return errors.New("short read")
+ }
+ return err
+}
+
+// readBody reads a box's body, at most maxHeaderBox bytes.
+func readBody(r io.ReaderAt, b fileBox) ([]byte, error) {
+ n := b.size - b.hdr
+ if n > maxHeaderBox {
+ return nil, fmt.Errorf("%s at %d is over %d bytes", b.typ, b.off, maxHeaderBox)
+ }
+ buf := make([]byte, n)
+ if _, err := r.ReadAt(buf, b.off+b.hdr); err != nil {
+ return nil, fmt.Errorf("reading %s at %d: %w", b.typ, b.off, errRead(err))
+ }
+ return buf, nil
+}
+
+// child is one box inside a parent's body.
+type child struct {
+ typ string
+ off int64 // from the start of the parent's body
+ body []byte
+}
+
+// children splits a body into its boxes: they must fill it exactly.
+func children(b []byte) ([]child, error) {
+ var out []child
+ for off := 0; off < len(b); {
+ if len(b)-off < 8 {
+ return nil, errors.New("a box header is cut short")
+ }
+ size, hdr := uint64(binary.BigEndian.Uint32(b[off:])), 8
+ if size == 1 {
+ if len(b)-off < 16 {
+ return nil, errors.New("a box header is cut short")
+ }
+ size, hdr = binary.BigEndian.Uint64(b[off+8:]), 16
+ }
+ if size < uint64(hdr) || size > uint64(len(b)-off) {
+ return nil, errors.New("a box's size does not fit its parent")
+ }
+ end := off + int(size)
+ out = append(out, child{typ: string(b[off+4 : off+8]), off: int64(off), body: b[off+hdr : end]})
+ off = end
+ }
+ return out, nil
+}
+
+// timeline is what readFMP4 needs from the moov: the chosen track, its
+// timescale, and each track's trex defaults.
+type timeline struct {
+ track uint32
+ timescale uint32
+ trex map[uint32]trexDefaults
+}
+
+type trexDefaults struct{ duration, size uint32 }
+
+// track is one trak's facts.
+type track struct {
+ id, timescale uint32
+ handler string
+}
+
+// parseMoov reads the tracks and the trex defaults and chooses the
+// timeline's track: the first video track, else the first track.
+func parseMoov(b []byte) (timeline, error) {
+ boxes, err := children(b)
+ if err != nil {
+ return timeline{}, fmt.Errorf("moov: %w", err)
+ }
+ tl := timeline{trex: map[uint32]trexDefaults{}}
+ var tracks []track
+ for _, c := range boxes {
+ switch c.typ {
+ case "trak":
+ t, err := parseTrak(c.body)
+ if err != nil {
+ return timeline{}, err
+ }
+ tracks = append(tracks, t)
+ case "mvex":
+ if err := parseMvex(c.body, tl.trex); err != nil {
+ return timeline{}, err
+ }
+ }
+ }
+ if len(tracks) == 0 {
+ return timeline{}, errors.New("moov has no track")
+ }
+ chosen := tracks[0]
+ for _, t := range tracks {
+ if t.handler == "vide" {
+ chosen = t
+ break
+ }
+ }
+ if chosen.timescale == 0 {
+ return timeline{}, errors.New("the track's timescale is 0")
+ }
+ tl.track, tl.timescale = chosen.id, chosen.timescale
+ return tl, nil
+}
+
+// parseTrak reads a trak's tkhd track_ID, mdhd timescale and hdlr type.
+func parseTrak(b []byte) (track, error) {
+ var t track
+ var haveID, haveTS bool
+ boxes, err := children(b)
+ if err != nil {
+ return t, fmt.Errorf("trak: %w", err)
+ }
+ for _, c := range boxes {
+ switch c.typ {
+ case "tkhd":
+ // version, flags, then creation and modification times (32 or
+ // 64 bits each), then track_ID.
+ at := 12
+ if len(c.body) > 0 && c.body[0] == 1 {
+ at = 20
+ }
+ if len(c.body) < at+4 {
+ return t, errors.New("tkhd is cut short")
+ }
+ t.id, haveID = binary.BigEndian.Uint32(c.body[at:]), true
+ case "mdia":
+ if err := parseMdia(c.body, &t, &haveTS); err != nil {
+ return t, err
+ }
+ }
+ }
+ if !haveID || !haveTS || t.handler == "" {
+ return t, errors.New("trak lacks tkhd, mdhd or hdlr")
+ }
+ return t, nil
+}
+
+func parseMdia(b []byte, t *track, haveTS *bool) error {
+ boxes, err := children(b)
+ if err != nil {
+ return fmt.Errorf("mdia: %w", err)
+ }
+ for _, c := range boxes {
+ switch c.typ {
+ case "mdhd":
+ at := 12
+ if len(c.body) > 0 && c.body[0] == 1 {
+ at = 20
+ }
+ if len(c.body) < at+4 {
+ return errors.New("mdhd is cut short")
+ }
+ t.timescale, *haveTS = binary.BigEndian.Uint32(c.body[at:]), true
+ case "hdlr":
+ // version, flags, pre_defined, then handler_type.
+ if len(c.body) < 12 {
+ return errors.New("hdlr is cut short")
+ }
+ t.handler = string(c.body[8:12])
+ }
+ }
+ return nil
+}
+
+// parseMvex reads every trex's default sample duration and size.
+func parseMvex(b []byte, into map[uint32]trexDefaults) error {
+ boxes, err := children(b)
+ if err != nil {
+ return fmt.Errorf("mvex: %w", err)
+ }
+ for _, c := range boxes {
+ if c.typ != "trex" {
+ continue
+ }
+ // version, flags, track_ID, sample description index, duration,
+ // size, flags.
+ if len(c.body) < 24 {
+ return errors.New("trex is cut short")
+ }
+ into[binary.BigEndian.Uint32(c.body[4:])] = trexDefaults{
+ duration: binary.BigEndian.Uint32(c.body[12:]),
+ size: binary.BigEndian.Uint32(c.body[16:]),
+ }
+ }
+ return nil
+}
+
+// tfhd and trun flags (ISO/IEC 14496-12).
+const (
+ tfhdBaseDataOffset = 0x000001
+ tfhdSampleDescription = 0x000002
+ tfhdDefaultDuration = 0x000008
+ tfhdDefaultSize = 0x000010
+ tfhdDefaultFlags = 0x000020
+ tfhdDefaultBaseIsMoof = 0x020000
+
+ trunDataOffset = 0x000001
+ trunFirstSampleFlags = 0x000004
+ trunSampleDuration = 0x000100
+ trunSampleSize = 0x000200
+ trunSampleFlags = 0x000400
+ trunSampleCTO = 0x000800
+)
+
+// parseMoof reads one moof: the timeline track's tfdt and the sum of
+// its sample durations; and, for every traf, that its samples lie
+// inside mdat's body.
+func parseMoof(b []byte, moof, mdat fileBox, tl timeline) (start, dur uint64, err error) {
+ boxes, err := children(b)
+ if err != nil {
+ return 0, 0, fmt.Errorf("moof: %w", err)
+ }
+ found := false
+ for _, c := range boxes {
+ if c.typ != "traf" {
+ continue
+ }
+ id, tfdt, hasTfdt, d, err := parseTraf(c.body, moof, mdat, tl)
+ if err != nil {
+ return 0, 0, err
+ }
+ if id != tl.track {
+ continue
+ }
+ if found {
+ return 0, 0, errors.New("two trafs for the timeline's track")
+ }
+ if !hasTfdt {
+ return 0, 0, errors.New("the timeline's traf has no tfdt")
+ }
+ found, start, dur = true, tfdt, d
+ }
+ if !found {
+ return 0, 0, errors.New("no traf for the timeline's track")
+ }
+ return start, dur, nil
+}
+
+// parseTraf reads one traf: its track, tfdt, and the sum of its sample
+// durations (needed only on the timeline's track), checking that every
+// trun's samples lie inside mdat's body.
+func parseTraf(b []byte, moof, mdat fileBox, tl timeline) (id uint32, tfdt uint64, hasTfdt bool, dur uint64, err error) {
+ boxes, err := children(b)
+ if err != nil {
+ return 0, 0, false, 0, fmt.Errorf("traf: %w", err)
+ }
+ if len(boxes) == 0 || boxes[0].typ != "tfhd" {
+ return 0, 0, false, 0, errors.New("traf does not start with tfhd")
+ }
+ h, err := parseTfhd(boxes[0].body, tl)
+ if err != nil {
+ return 0, 0, false, 0, err
+ }
+ timed := h.id == tl.track
+ for _, c := range boxes[1:] {
+ switch c.typ {
+ case "tfdt":
+ if hasTfdt {
+ return 0, 0, false, 0, errors.New("two tfdt in a traf")
+ }
+ if tfdt, err = parseTfdt(c.body); err != nil {
+ return 0, 0, false, 0, err
+ }
+ hasTfdt = true
+ case "trun":
+ d, err := parseTrun(c.body, h, timed, moof, mdat)
+ if err != nil {
+ return 0, 0, false, 0, err
+ }
+ var carry uint64
+ if dur, carry = bits.Add64(dur, d, 0); carry != 0 {
+ return 0, 0, false, 0, errors.New("a fragment's duration overflows")
+ }
+ }
+ }
+ return h.id, tfdt, hasTfdt, dur, nil
+}
+
+// tfhd is a traf header with its defaults resolved against trex.
+type tfhd struct {
+ id uint32
+ duration, size uint32
+ hasDuration, hasSize bool
+}
+
+func parseTfhd(b []byte, tl timeline) (tfhd, error) {
+ if len(b) < 8 {
+ return tfhd{}, errors.New("tfhd is cut short")
+ }
+ flags := binary.BigEndian.Uint32(b) & 0xffffff
+ if flags&tfhdBaseDataOffset != 0 || flags&tfhdDefaultBaseIsMoof == 0 {
+ return tfhd{}, errors.New("tfhd is not default-base-is-moof")
+ }
+ h := tfhd{id: binary.BigEndian.Uint32(b[4:])}
+ if d, ok := tl.trex[h.id]; ok {
+ h.duration, h.size, h.hasDuration, h.hasSize = d.duration, d.size, true, true
+ }
+ at := 8
+ field := func() (uint32, error) {
+ if len(b) < at+4 {
+ return 0, errors.New("tfhd is cut short")
+ }
+ v := binary.BigEndian.Uint32(b[at:])
+ at += 4
+ return v, nil
+ }
+ if flags&tfhdSampleDescription != 0 {
+ if _, err := field(); err != nil {
+ return tfhd{}, err
+ }
+ }
+ if flags&tfhdDefaultDuration != 0 {
+ v, err := field()
+ if err != nil {
+ return tfhd{}, err
+ }
+ h.duration, h.hasDuration = v, true
+ }
+ if flags&tfhdDefaultSize != 0 {
+ v, err := field()
+ if err != nil {
+ return tfhd{}, err
+ }
+ h.size, h.hasSize = v, true
+ }
+ if flags&tfhdDefaultFlags != 0 {
+ if _, err := field(); err != nil {
+ return tfhd{}, err
+ }
+ }
+ return h, nil
+}
+
+func parseTfdt(b []byte) (uint64, error) {
+ switch {
+ case len(b) >= 12 && b[0] == 1:
+ return binary.BigEndian.Uint64(b[4:]), nil
+ case len(b) >= 8 && b[0] == 0:
+ return uint64(binary.BigEndian.Uint32(b[4:])), nil
+ }
+ return 0, errors.New("tfdt is cut short or of an unknown version")
+}
+
+// parseTrun sums one trun's sample durations (when timed) and checks
+// that its samples' bytes, from moof's start plus its data offset, lie
+// inside mdat's body.
+func parseTrun(b []byte, h tfhd, timed bool, moof, mdat fileBox) (uint64, error) {
+ if len(b) < 8 {
+ return 0, errors.New("trun is cut short")
+ }
+ flags := binary.BigEndian.Uint32(b) & 0xffffff
+ count := uint64(binary.BigEndian.Uint32(b[4:]))
+ if flags&trunDataOffset == 0 {
+ return 0, errors.New("trun has no data offset")
+ }
+ at := 8
+ if len(b) < at+4 {
+ return 0, errors.New("trun is cut short")
+ }
+ dataOff := int64(int32(binary.BigEndian.Uint32(b[at:])))
+ at += 4
+ if flags&trunFirstSampleFlags != 0 {
+ at += 4
+ }
+ per := 0
+ for _, f := range []uint32{trunSampleDuration, trunSampleSize, trunSampleFlags, trunSampleCTO} {
+ if flags&f != 0 {
+ per += 4
+ }
+ }
+ if uint64(len(b)) < uint64(at) || (uint64(len(b))-uint64(at)) < count*uint64(per) {
+ return 0, errors.New("trun's samples run past it")
+ }
+ if flags&trunSampleDuration == 0 && timed && !h.hasDuration {
+ return 0, errors.New("no sample duration for the timeline's track")
+ }
+ if flags&trunSampleSize == 0 && !h.hasSize {
+ return 0, errors.New("no sample size")
+ }
+ var dur, length uint64
+ if per == 0 {
+ // Every sample takes the defaults: no loop over a count the
+ // trun's length does not bound. Each product is under 2^64.
+ dur, length = count*uint64(h.duration), count*uint64(h.size)
+ } else {
+ // count <= len(b)/4 < 2^21 (the moof is at most maxHeaderBox),
+ // and each value is under 2^32: the sums cannot overflow.
+ for i := uint64(0); i < count; i++ {
+ d, s := uint64(h.duration), uint64(h.size)
+ p := at
+ if flags&trunSampleDuration != 0 {
+ d = uint64(binary.BigEndian.Uint32(b[p:]))
+ p += 4
+ }
+ if flags&trunSampleSize != 0 {
+ s = uint64(binary.BigEndian.Uint32(b[p:]))
+ }
+ at += per
+ dur += d
+ length += s
+ }
+ }
+ start := moof.off + dataOff
+ if start < mdat.off+mdat.hdr || start > mdat.end() || length > uint64(mdat.end()-start) {
+ return 0, errors.New("a trun's samples lie outside its mdat")
+ }
+ if !timed {
+ return 0, nil
+ }
+ return dur, nil
+}
diff --git a/internal/mediahandler/fmp4_synth_test.go b/internal/mediahandler/fmp4_synth_test.go
new file mode 100644
index 000000000..dbe2e7f44
--- /dev/null
+++ b/internal/mediahandler/fmp4_synth_test.go
@@ -0,0 +1,415 @@
+package mediahandler
+
+import (
+ "bytes"
+ "encoding/binary"
+ "math"
+ "slices"
+ "strings"
+ "testing"
+)
+
+// A small fragmented-MP4 builder, for readFMP4's refusals and the
+// parsing paths Debian's ffmpeg does not take (trex defaults, tfhd
+// defaults, a version 0 tfdt, an audio track first). What the real
+// encodes write is tested against testdata/fmp4 only (fmp4_test.go).
+
+func u32b(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) }
+func u64b(v uint64) []byte { return binary.BigEndian.AppendUint64(nil, v) }
+
+// mkbox is a box of typ around parts.
+func mkbox(typ string, parts ...[]byte) []byte {
+ body := slices.Concat(parts...)
+ return slices.Concat(u32b(uint32(8+len(body))), []byte(typ), body)
+}
+
+// full is a full box's body: version, flags, then parts.
+func full(v byte, flags uint32, parts ...[]byte) []byte {
+ return slices.Concat([]byte{v, byte(flags >> 16), byte(flags >> 8), byte(flags)}, slices.Concat(parts...))
+}
+
+type sTrack struct {
+ id uint32
+ handler string
+ timescale uint32
+ // trex defaults; noTrex leaves the track out of mvex.
+ trexDur, trexSize uint32
+ noTrex bool
+}
+
+type sTrun struct {
+ flags uint32 // besides trunDataOffset, always set unless noDataOffset
+ count uint32 // when there are no per-sample entries
+ durs, sizes []uint32
+ // dataOffsetDelta moves the computed data offset.
+ dataOffsetDelta int32
+ noDataOffset bool
+}
+
+type sTraf struct {
+ track uint32
+ tfhdFlags uint32 // 0 is tfhdDefaultBaseIsMoof
+ defDur uint32 // written when tfhdFlags has tfhdDefaultDuration
+ defSize uint32 // written when tfhdFlags has tfhdDefaultSize
+ tfdt uint64
+ tfdtV0 bool
+ noTfdt bool
+ twoTfdt bool // a second tfdt after the first
+ tfdtFirst bool // the tfdt before the tfhd
+ truns []sTrun
+}
+
+type sFile struct {
+ tracks []sTrack
+ frags [][]sTraf
+}
+
+// goodSynth is three fragments of one video track at timescale 1000:
+// 4 s, 4 s and 1 s, each two samples with per-sample durations and
+// sizes.
+func goodSynth() sFile {
+ frag := func(start uint64, d uint32) []sTraf {
+ return []sTraf{{track: 1, tfdt: start, truns: []sTrun{{flags: trunSampleDuration | trunSampleSize, durs: []uint32{d, d}, sizes: []uint32{10, 12}}}}}
+ }
+ return sFile{
+ tracks: []sTrack{{id: 1, handler: "vide", timescale: 1000}},
+ frags: [][]sTraf{frag(0, 2000), frag(4000, 2000), frag(8000, 500)},
+ }
+}
+
+func (f sFile) bytes() []byte {
+ var moov [][]byte
+ moov = append(moov, mkbox("mvhd", full(0, 0, make([]byte, 96))))
+ var trex [][]byte
+ for _, t := range f.tracks {
+ moov = append(moov, mkbox("trak",
+ mkbox("tkhd", full(0, 3, u32b(0), u32b(0), u32b(t.id), make([]byte, 68))),
+ mkbox("mdia",
+ mkbox("mdhd", full(0, 0, u32b(0), u32b(0), u32b(t.timescale), u32b(0), make([]byte, 4))),
+ mkbox("hdlr", full(0, 0, u32b(0), []byte(t.handler), make([]byte, 13))))))
+ if !t.noTrex {
+ trex = append(trex, mkbox("trex", full(0, 0, u32b(t.id), u32b(1), u32b(t.trexDur), u32b(t.trexSize), u32b(0))))
+ }
+ }
+ moov = append(moov, mkbox("mvex", trex...))
+ out := slices.Concat(mkbox("ftyp", []byte("iso5"), u32b(512), []byte("iso5iso6mp41")), mkbox("moov", moov...))
+ for i, trafs := range f.frags {
+ moofLen := len(f.moof(i, trafs, 0))
+ out = append(out, f.moof(i, trafs, moofLen)...)
+ out = append(out, mkbox("mdat", make([]byte, f.dataLen(trafs)))...)
+ }
+ return out
+}
+
+// sampleSize is a trun's default sample size: the traf's, else trex's.
+func (f sFile) sampleSize(tr sTraf) uint32 {
+ if tr.tfhdFlags&tfhdDefaultSize != 0 {
+ return tr.defSize
+ }
+ for _, t := range f.tracks {
+ if t.id == tr.track && !t.noTrex {
+ return t.trexSize
+ }
+ }
+ return 0
+}
+
+// runLen is the bytes of sample data one trun claims.
+func (f sFile) runLen(tr sTraf, r sTrun) int {
+ if r.flags&trunSampleSize != 0 {
+ n := 0
+ for _, s := range r.sizes {
+ n += int(s)
+ }
+ return n
+ }
+ count := uint64(r.count)
+ if r.flags&trunSampleDuration != 0 {
+ count = uint64(len(r.durs))
+ }
+ return int(min(count*uint64(f.sampleSize(tr)), 1<<20))
+}
+
+func (f sFile) dataLen(trafs []sTraf) int {
+ n := 0
+ for _, tr := range trafs {
+ for _, r := range tr.truns {
+ n += f.runLen(tr, r)
+ }
+ }
+ return n
+}
+
+// moof is fragment i's moof, its data offsets from moofLen (the
+// moof's own length, then the mdat header).
+func (f sFile) moof(i int, trafs []sTraf, moofLen int) []byte {
+ parts := [][]byte{mkbox("mfhd", full(0, 0, u32b(uint32(i+1))))}
+ at := moofLen + 8
+ for _, tr := range trafs {
+ flags := tr.tfhdFlags
+ if flags == 0 {
+ flags = tfhdDefaultBaseIsMoof
+ }
+ tfhd := full(0, flags, u32b(tr.track))
+ if flags&tfhdDefaultDuration != 0 {
+ tfhd = append(tfhd, u32b(tr.defDur)...)
+ }
+ if flags&tfhdDefaultSize != 0 {
+ tfhd = append(tfhd, u32b(tr.defSize)...)
+ }
+ boxes := [][]byte{mkbox("tfhd", tfhd)}
+ if !tr.noTfdt {
+ tfdt := mkbox("tfdt", full(1, 0, u64b(tr.tfdt)))
+ if tr.tfdtV0 {
+ tfdt = mkbox("tfdt", full(0, 0, u32b(uint32(tr.tfdt))))
+ }
+ boxes = append(boxes, tfdt)
+ if tr.twoTfdt {
+ boxes = append(boxes, tfdt)
+ }
+ if tr.tfdtFirst {
+ boxes[0], boxes[1] = boxes[1], boxes[0]
+ }
+ }
+ for _, r := range tr.truns {
+ flags := r.flags | trunDataOffset
+ if r.noDataOffset {
+ flags &^= trunDataOffset
+ }
+ count := r.count
+ if r.flags&(trunSampleDuration|trunSampleSize) != 0 {
+ count = uint32(max(len(r.durs), len(r.sizes)))
+ }
+ body := full(0, flags, u32b(count))
+ if !r.noDataOffset {
+ body = append(body, u32b(uint32(int32(at)+r.dataOffsetDelta))...)
+ }
+ for k := range int(count) * min(1, int(r.flags&(trunSampleDuration|trunSampleSize))) {
+ if r.flags&trunSampleDuration != 0 {
+ body = append(body, u32b(r.durs[k])...)
+ }
+ if r.flags&trunSampleSize != 0 {
+ body = append(body, u32b(r.sizes[k])...)
+ }
+ }
+ boxes = append(boxes, mkbox("trun", body))
+ at += f.runLen(tr, r)
+ }
+ parts = append(parts, mkbox("traf", boxes...))
+ }
+ return mkbox("moof", parts...)
+}
+
+// TestReadFMP4Synthetic: the paths ffmpeg's files do not take, read
+// right. Each case's fragments and duration.
+func TestReadFMP4Synthetic(t *testing.T) {
+ for name, c := range map[string]struct {
+ edit func(*sFile)
+ durs []float64
+ durationMS int64
+ }{
+ "per-sample durations": {func(*sFile) {}, []float64{4, 4, 1}, 9000},
+ "a version 0 tfdt": {func(f *sFile) {
+ for i := range f.frags {
+ f.frags[i][0].tfdtV0 = true
+ }
+ }, []float64{4, 4, 1}, 9000},
+ "trex defaults": {func(f *sFile) {
+ f.tracks[0].trexDur, f.tracks[0].trexSize = 250, 3
+ f.frags[2][0].truns[0] = sTrun{count: 4}
+ }, []float64{4, 4, 1}, 9000},
+ "tfhd defaults over trex": {func(f *sFile) {
+ f.tracks[0].trexDur, f.tracks[0].trexSize = 7, 7
+ f.frags[2][0].tfhdFlags = tfhdDefaultBaseIsMoof | tfhdDefaultDuration | tfhdDefaultSize
+ f.frags[2][0].defDur, f.frags[2][0].defSize = 500, 5
+ f.frags[2][0].truns[0] = sTrun{count: 3}
+ }, []float64{4, 4, 1.5}, 9500},
+ "two truns": {func(f *sFile) {
+ f.frags[2][0].truns = append(f.frags[2][0].truns, f.frags[2][0].truns[0])
+ }, []float64{4, 4, 2}, 10000},
+ // The timeline is the video's, whichever track comes first: the
+ // audio here runs 1 s per fragment.
+ "audio first": {func(f *sFile) {
+ f.tracks = []sTrack{{id: 2, handler: "soun", timescale: 48000}, f.tracks[0]}
+ for i := range f.frags {
+ f.frags[i] = append([]sTraf{{track: 2, tfdt: uint64(i) * 48000, truns: []sTrun{{flags: trunSampleDuration | trunSampleSize, durs: []uint32{48000}, sizes: []uint32{4}}}}}, f.frags[i]...)
+ }
+ }, []float64{4, 4, 1}, 9000},
+ // No video track: the first track's timeline.
+ "audio only": {func(f *sFile) {
+ f.tracks[0].handler = "soun"
+ }, []float64{4, 4, 1}, 9000},
+ // A fraction of a millisecond rounds up: 25,501 ticks of 3,000.
+ "rounded up": {func(f *sFile) {
+ f.tracks[0].timescale = 3000
+ for i := range f.frags {
+ f.frags[i][0].tfdt *= 3
+ }
+ f.frags[2][0].truns[0].durs = []uint32{1500, 1}
+ }, []float64{4, 4, 1501.0 / 3000}, 8501},
+ } {
+ f := goodSynth()
+ c.edit(&f)
+ b := f.bytes()
+ initLen, frags, durationMS, err := readFMP4(bytes.NewReader(b), int64(len(b)))
+ if err != nil {
+ t.Errorf("%s: %v", name, err)
+ continue
+ }
+ var got []float64
+ for _, fr := range frags {
+ got = append(got, fr.DurationS)
+ }
+ if !slices.EqualFunc(got, c.durs, func(a, b float64) bool { return math.Abs(a-b) < 1e-9 }) || durationMS != c.durationMS || !fragmentsValid(initLen, frags, int64(len(b))) {
+ t.Errorf("%s: %v, %d ms, valid %v; want %v, %d ms", name, got, durationMS, fragmentsValid(initLen, frags, int64(len(b))), c.durs, c.durationMS)
+ }
+ }
+}
+
+// TestReadFMP4SyntheticRefusals: each guard, one at a time, on an
+// otherwise valid file; the error names the reason.
+func TestReadFMP4SyntheticRefusals(t *testing.T) {
+ huge := func(f *sFile) {
+ // Every sample the default: count 2^32-1 of 2^32-1 ticks, no bytes.
+ last := &f.frags[2][0]
+ last.tfhdFlags = tfhdDefaultBaseIsMoof | tfhdDefaultDuration | tfhdDefaultSize
+ last.defDur, last.defSize = math.MaxUint32, 0
+ last.truns = []sTrun{{count: math.MaxUint32}}
+ }
+ for name, c := range map[string]struct {
+ edit func(*sFile)
+ raw func([]byte) []byte
+ want string
+ }{
+ "no track": {edit: func(f *sFile) { f.tracks = nil; f.frags = [][]sTraf{} }, want: "no track"},
+ "timescale 0": {edit: func(f *sFile) { f.tracks[0].timescale = 0 }, want: "timescale is 0"},
+ "no traf for the track": {edit: func(f *sFile) { f.frags[1][0].track = 9 }, want: "no traf for the timeline's track"},
+ "two trafs for it": {edit: func(f *sFile) { f.frags[1] = append(f.frags[1], f.frags[1][0]) }, want: "two trafs"},
+ "no tfdt": {edit: func(f *sFile) { f.frags[1][0].noTfdt = true }, want: "has no tfdt"},
+ "base data offset": {edit: func(f *sFile) {
+ f.frags[0][0].tfhdFlags = tfhdDefaultBaseIsMoof | tfhdBaseDataOffset
+ }, want: "not default-base-is-moof"},
+ "no data offset": {edit: func(f *sFile) { f.frags[0][0].truns[0].noDataOffset = true }, want: "no data offset"},
+ "data before mdat": {edit: func(f *sFile) { f.frags[0][0].truns[0].dataOffsetDelta = -1 }, want: "outside its mdat"},
+ "data past mdat": {edit: func(f *sFile) { f.frags[0][0].truns[0].dataOffsetDelta = 1 }, want: "outside its mdat"},
+ "data far past mdat": {edit: func(f *sFile) { f.frags[0][0].truns[0].dataOffsetDelta = 1 << 20 }, want: "outside its mdat"},
+ "tfdt before tfhd": {edit: func(f *sFile) { f.frags[1][0].tfdtFirst = true }, want: "does not start with tfhd"},
+ "two tfdt": {edit: func(f *sFile) { f.frags[1][0].twoTfdt = true }, want: "two tfdt"},
+ "no sample duration": {edit: func(f *sFile) {
+ f.frags[2][0].truns[0] = sTrun{flags: trunSampleSize, sizes: []uint32{1}}
+ f.tracks[0].noTrex = true
+ }, want: "no sample duration"},
+ "no sample size": {edit: func(f *sFile) {
+ f.frags[2][0].truns[0] = sTrun{flags: trunSampleDuration, durs: []uint32{1}}
+ f.tracks[0].noTrex = true
+ }, want: "no sample size"},
+ "tfdt goes back": {edit: func(f *sFile) { f.frags[2][0].tfdt = 4000 }, want: "tfdt does not increase"},
+ "the last lasts nothing": {edit: func(f *sFile) { f.frags[2][0].truns[0].durs = []uint32{0, 0} }, want: "has no duration"},
+ "an implausible duration": {edit: huge, want: "implausible"},
+ "two truns overflow": {edit: func(f *sFile) {
+ huge(f)
+ f.frags[2][0].truns = append(f.frags[2][0].truns, f.frags[2][0].truns[0])
+ }, want: "duration overflows"},
+ "the timeline overflows": {edit: func(f *sFile) {
+ huge(f)
+ f.frags[2][0].tfdt = math.MaxUint64 - 1<<31
+ }, want: "duration overflows"},
+ "a moov over the bound": {raw: func(b []byte) []byte {
+ moov := topBoxesOf(b)[1]
+ pad := mkbox("free", make([]byte, maxHeaderBox))
+ grown := slices.Concat(u32b(uint32(moov.size)+uint32(len(pad))), []byte("moov"), b[moov.off+8:moov.off+moov.size], pad)
+ return slices.Concat(b[:moov.off], grown, b[moov.off+moov.size:])
+ }, want: "is over"},
+ "a 64-bit size past the file": {raw: func(b []byte) []byte {
+ last := topBoxesOf(b)[len(topBoxesOf(b))-1]
+ grown := slices.Concat(u32b(1), []byte("mdat"), u64b(uint64(last.size)+8+1), b[last.off+8:last.off+last.size])
+ return slices.Concat(b[:last.off], grown)
+ }, want: "does not fit"},
+ "a child past its parent": {raw: func(b []byte) []byte { return growChild(b, "tfdt", 4) }, want: "does not fit its parent"},
+ "a cut-short tkhd": {raw: func(b []byte) []byte { return shrinkChild(b, "tkhd", 4) }, want: ""},
+ "a cut-short mdhd": {raw: func(b []byte) []byte { return shrinkChild(b, "mdhd", 12) }, want: ""},
+ "a cut-short hdlr": {raw: func(b []byte) []byte { return shrinkChild(b, "hdlr", 10) }, want: ""},
+ "a cut-short trex": {raw: func(b []byte) []byte { return shrinkChild(b, "trex", 4) }, want: ""},
+ "a cut-short tfhd": {raw: func(b []byte) []byte { return shrinkChild(b, "tfhd", 4) }, want: ""},
+ "a cut-short tfdt": {raw: func(b []byte) []byte { return shrinkChild(b, "tfdt", 4) }, want: ""},
+ "a cut-short trun": {raw: func(b []byte) []byte { return shrinkChild(b, "trun", 12) }, want: ""},
+ } {
+ f := goodSynth()
+ if c.edit != nil {
+ c.edit(&f)
+ }
+ b := f.bytes()
+ if c.raw != nil {
+ b = c.raw(b)
+ }
+ _, _, _, err := readFMP4(bytes.NewReader(b), int64(len(b)))
+ if err == nil || !strings.Contains(err.Error(), c.want) {
+ t.Errorf("%s: %v, want an error containing %q", name, err, c.want)
+ }
+ }
+ // The good file itself is read.
+ b := goodSynth().bytes()
+ if _, _, _, err := readFMP4(bytes.NewReader(b), int64(len(b))); err != nil {
+ t.Fatalf("the good file: %v", err)
+ }
+}
+
+// topBoxesOf is topBoxes without a testing.T.
+func topBoxesOf(b []byte) []topBoxEntry {
+ var out []topBoxEntry
+ for off := int64(0); off+8 <= int64(len(b)); {
+ size := int64(binary.BigEndian.Uint32(b[off:]))
+ if size == 1 {
+ size = int64(binary.BigEndian.Uint64(b[off+8:]))
+ }
+ if size < 8 {
+ break
+ }
+ out = append(out, topBoxEntry{string(b[off+4 : off+8]), off, size})
+ off += size
+ }
+ return out
+}
+
+// shrinkChild cuts the first box of typ (at any depth) to cut bytes of
+// body, and every box around it by as much, so the file stays whole
+// and only that box is short.
+func shrinkChild(b []byte, typ string, cut int) []byte {
+ var walk func(b []byte, base int) []byte
+ walk = func(b []byte, base int) []byte {
+ for off := 0; off+8 <= len(b); {
+ size := int(binary.BigEndian.Uint32(b[off:]))
+ if size < 8 || off+size > len(b) {
+ return b
+ }
+ name := string(b[off+4 : off+8])
+ if name == typ {
+ body := b[off+8 : off+size]
+ short := slices.Concat(u32b(uint32(8+cut)), []byte(name), body[:cut])
+ return slices.Concat(b[:off], short, b[off+size:])
+ }
+ switch name {
+ case "moov", "trak", "mdia", "mvex", "moof", "traf":
+ inner := walk(b[off+8:off+size], base+off+8)
+ if len(inner) != size-8 {
+ return slices.Concat(b[:off], u32b(uint32(8+len(inner))), []byte(name), inner, b[off+size:])
+ }
+ }
+ off += size
+ }
+ return b
+ }
+ return walk(b, 0)
+}
+
+// growChild adds n to the size field of the first box of typ inside
+// the first moof's first traf, and nothing else: it then claims bytes
+// past its parent's end.
+func growChild(b []byte, typ string, n uint32) []byte {
+ b = bytes.Clone(b)
+ moof := topBoxesOf(b)[2]
+ i := bytes.Index(b[moof.off:moof.off+moof.size], []byte(typ))
+ at := int(moof.off) + i - 4
+ binary.BigEndian.PutUint32(b[at:], binary.BigEndian.Uint32(b[at:])+n)
+ return b
+}
diff --git a/internal/mediahandler/fmp4_test.go b/internal/mediahandler/fmp4_test.go
new file mode 100644
index 000000000..974867544
--- /dev/null
+++ b/internal/mediahandler/fmp4_test.go
@@ -0,0 +1,459 @@
+package mediahandler
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// testdata/fmp4 holds three files Debian 13's ffmpeg 7.1.5 wrote with
+// this package's own videoArgs and audioArgs (TestRegenerateFMP4Fixtures;
+// args.txt is each one's exact arguments), each beside the real
+// ffprobe's packets for it (stream_index,dts_time,duration_time,size,pos:
+// ffprobe's own order).
+// They stand in for plan 1's spike fixtures until its report
+// (testdata/fmp4/provenance.txt). Nothing here is hand-built.
+
+// argsLine is one line of testdata/fmp4/args.txt: a fixture and the
+// exact ffmpeg arguments that made it.
+type argsLine struct {
+ File string `json:"file"`
+ Args []string `json:"args"`
+}
+
+func readFixture(t testing.TB, name string) []byte {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("testdata", "fmp4", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return b
+}
+
+// topBoxes walks a file's top-level boxes independently of readFMP4:
+// each one's type, offset and size.
+type topBoxEntry struct {
+ typ string
+ off, size int64
+}
+
+func topBoxes(t *testing.T, b []byte) []topBoxEntry {
+ t.Helper()
+ var out []topBoxEntry
+ for off := int64(0); off < int64(len(b)); {
+ size := int64(binary.BigEndian.Uint32(b[off:]))
+ if size == 1 {
+ size = int64(binary.BigEndian.Uint64(b[off+8:]))
+ }
+ if size < 8 || off+size > int64(len(b)) {
+ t.Fatalf("box at %d: size %d", off, size)
+ }
+ out = append(out, topBoxEntry{string(b[off+4 : off+8]), off, size})
+ off += size
+ }
+ return out
+}
+
+// packet is one line of a fixture's packets file.
+type packet struct {
+ stream int
+ dts, dur float64 // seconds; dur is NaN for N/A
+ pos, size int64
+}
+
+func readPackets(t *testing.T, name string) []packet {
+ t.Helper()
+ var out []packet
+ sc := bufio.NewScanner(bytes.NewReader(readFixture(t, name+".packets.csv")))
+ for sc.Scan() {
+ f := strings.Split(sc.Text(), ",")
+ if len(f) < 5 {
+ t.Fatalf("packet line %q", sc.Text())
+ }
+ var p packet
+ var err error
+ p.stream, _ = strconv.Atoi(f[0])
+ p.dts, _ = strconv.ParseFloat(f[1], 64)
+ if p.dur, err = strconv.ParseFloat(f[2], 64); err != nil {
+ p.dur = math.NaN()
+ }
+ p.size, _ = strconv.ParseInt(f[3], 10, 64)
+ p.pos, _ = strconv.ParseInt(f[4], 10, 64)
+ out = append(out, p)
+ }
+ return out
+}
+
+// TestReadFMP4Fixtures: for each of the real ffmpeg's files, readFMP4
+// answers the header length and fragments that an independent walk of
+// the top-level boxes finds (ftyp, moov, then moof/mdat pairs and no
+// trailer box); every packet ffprobe lists lies inside one fragment's
+// mdat; each fragment's duration is within 1 ms of the timeline
+// stream's packet times (the last one: within its packets' span); every
+// fragment but the last is 4 s (video exactly, at its 2 s keyframes;
+// audio within one AAC frame); and the duration is ffprobe's for the
+// stream, within 1 ms.
+func TestReadFMP4Fixtures(t *testing.T) {
+ const aacFrame = 1024.0 / 48000
+ for _, c := range []struct {
+ file string
+ frags int
+ durationMS int64
+ tolerance float64 // a whole fragment's distance from 4 s
+ lastTrim float64 // how much -t may trim the last frame
+ }{
+ {"video.mp4", 3, 9000, 0.0005, 0},
+ {"video-noaudio.mp4", 3, 9000, 0.0005, 0},
+ // 1,024 priming samples, then 9 s cut by -t (its last frame
+ // trimmed to 896 samples): 9.021333 s, past the grant (F15:
+ // packageOutput clamps it).
+ {"audio.mp4", 3, 9022, aacFrame, aacFrame},
+ } {
+ t.Run(c.file, func(t *testing.T) {
+ b := readFixture(t, c.file)
+ initLen, frags, durationMS, err := readFMP4(bytes.NewReader(b), int64(len(b)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxes := topBoxes(t, b)
+ var types []string
+ for _, x := range boxes {
+ types = append(types, x.typ)
+ }
+ want := []string{"ftyp", "moov"}
+ for range c.frags {
+ want = append(want, "moof", "mdat")
+ }
+ if !slices.Equal(types, want) {
+ t.Fatalf("top-level boxes %v, want %v (no trailer, no free)", types, want)
+ }
+ if initLen != boxes[0].size+boxes[1].size {
+ t.Errorf("initLen %d, want ftyp+moov %d", initLen, boxes[0].size+boxes[1].size)
+ }
+ if len(frags) != c.frags {
+ t.Fatalf("%d fragments, want %d", len(frags), c.frags)
+ }
+ for i, f := range frags {
+ moof, mdat := boxes[2+2*i], boxes[3+2*i]
+ if f.Offset != moof.off || f.Length != moof.size+mdat.size {
+ t.Errorf("fragment %d: %d@%d, want %d@%d", i, f.Length, f.Offset, moof.size+mdat.size, moof.off)
+ }
+ }
+ if !fragmentsValid(initLen, frags, int64(len(b))) {
+ t.Errorf("fragments are not contiguous over the file: %+v", frags)
+ }
+ // The packets: each inside one fragment's mdat; the timeline
+ // (stream 0: video first, or the only audio) per fragment.
+ pk := readPackets(t, c.file)
+ first := make([]float64, len(frags))
+ for i := range first {
+ first[i] = -1
+ }
+ end := 0.0
+ for _, p := range pk {
+ i := slices.IndexFunc(frags, func(f fragment) bool { return p.pos >= f.Offset && p.pos < f.Offset+f.Length })
+ mdat := boxes[3+2*max(i, 0)]
+ if i < 0 || p.pos < mdat.off+8 || p.pos+p.size > mdat.off+mdat.size {
+ t.Fatalf("packet at %d+%d is not inside a fragment's mdat", p.pos, p.size)
+ }
+ if p.stream != 0 {
+ continue
+ }
+ if first[i] < 0 {
+ first[i] = p.dts
+ }
+ if !math.IsNaN(p.dur) {
+ end = max(end, p.dts+p.dur)
+ }
+ }
+ // Whole fragments: from one's first packet to the next's. The
+ // last: its packets start before its end, and their nominal
+ // end is at most one frame past it (-t trims the last AAC
+ // frame's duration in the trun, which is what plays; ffprobe
+ // lists the frame's nominal length).
+ lastStart := 0.0
+ for _, p := range pk {
+ if p.stream == 0 {
+ lastStart = max(lastStart, p.dts)
+ }
+ }
+ for i, f := range frags {
+ if i+1 < len(frags) {
+ if got := first[i+1] - first[i]; math.Abs(got-f.DurationS) > 0.001 {
+ t.Errorf("fragment %d: %.6f s, packets say %.6f", i, f.DurationS, got)
+ }
+ if math.Abs(f.DurationS-4) > c.tolerance {
+ t.Errorf("fragment %d: %.6f s, want 4 s within %.4f", i, f.DurationS, c.tolerance)
+ }
+ continue
+ }
+ if f.DurationS <= lastStart-first[i] || f.DurationS > end-first[i]+0.001 || f.DurationS < end-first[i]-c.lastTrim-0.001 {
+ t.Errorf("last fragment: %.6f s; its packets start %.6f and end %.6f after it begins",
+ f.DurationS, lastStart-first[i], end-first[i])
+ }
+ }
+ // The whole: ffprobe's own duration of the stream.
+ probed, err := strconv.ParseFloat(strings.TrimSpace(string(readFixture(t, c.file+".duration"))), 64)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if durationMS != c.durationMS || math.Abs(float64(durationMS)/1000-probed) > 0.001 {
+ t.Errorf("durationMS %d, want %d; ffprobe says %.6f s", durationMS, c.durationMS, probed)
+ }
+ })
+ }
+}
+
+// TestMuxerArgsMatchTheFixtures: the muxer settings this package builds
+// today are the ones that made testdata/fmp4 (args.txt), so the
+// fixtures readFMP4 is tested against are what the encodes write.
+// Until plan 1's report records its own, args.txt is the record.
+func TestMuxerArgsMatchTheFixtures(t *testing.T) {
+ muxer := func(args []string) map[string]string {
+ m := map[string]string{}
+ for i, a := range args[:len(args)-1] {
+ switch a {
+ case "-f", "-movflags", "-min_frag_duration", "-frag_duration":
+ m[a] = args[i+1] // the last -f is the muxer's
+ }
+ }
+ return m
+ }
+ cfg := Config{Scratch: "/scratch"}
+ f := goodVideo()
+ p := media.Payload{Preset: media.PresetVideo720p, Limits: limitsFor(media.PresetVideo720p)}
+ built := map[string]map[string]string{
+ "video.mp4": muxer(videoArgs(cfg, f, p, "mov")),
+ "video-noaudio.mp4": muxer(videoArgs(cfg, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 160, Height: 90}, p, "mov")),
+ "audio.mp4": muxer(audioArgs(cfg, f, p, "wav", 0)),
+ }
+ lines := strings.Split(strings.TrimSpace(string(readFixture(t, "args.txt"))), "\n")
+ seen := 0
+ for _, l := range lines {
+ if strings.HasPrefix(l, "#") {
+ if !strings.Contains(l, "ffmpeg version 7.1.5-0+deb13u1") {
+ t.Errorf("the fixtures were made by %q, not Debian 13's 7.1.5", l)
+ }
+ continue
+ }
+ var a argsLine
+ if err := json.Unmarshal([]byte(l), &a); err != nil {
+ t.Fatal(err)
+ }
+ want, ok := built[a.File]
+ if !ok {
+ t.Fatalf("args.txt names %s", a.File)
+ }
+ seen++
+ if got := muxer(a.Args); !mapsEqual(got, want) {
+ t.Errorf("%s was made with %v; the encode builds %v", a.File, got, want)
+ }
+ }
+ if seen != len(built) {
+ t.Errorf("args.txt records %d fixtures, want %d", seen, len(built))
+ }
+}
+
+func mapsEqual(a, b map[string]string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for k, v := range a {
+ if b[k] != v {
+ return false
+ }
+ }
+ return true
+}
+
+// TestReadFMP4Refuses: one change at a time to a real file, each one
+// a sequence readFMP4 must refuse.
+func TestReadFMP4Refuses(t *testing.T) {
+ orig := readFixture(t, "video.mp4")
+ be32 := func(v uint32) []byte { return binary.BigEndian.AppendUint32(nil, v) }
+ box := func(typ string, body []byte) []byte {
+ return append(append(be32(uint32(8+len(body))), typ...), body...)
+ }
+ cut := func(b []byte, n int) []byte { return b[:len(b)-n] }
+ boxes := topBoxes(t, orig)
+ moov := boxes[1]
+ moof := boxes[2]
+ setType := func(off int64, typ string) []byte {
+ b := bytes.Clone(orig)
+ copy(b[off+4:], typ)
+ return b
+ }
+ setSize := func(off int64, size uint32) []byte {
+ b := bytes.Clone(orig)
+ binary.BigEndian.PutUint32(b[off:], size)
+ return b
+ }
+ // The first trun's data offset: moof, mfhd (16), traf header (8),
+ // tfhd, tfdt, then the trun's header (8), flags (4) and count (4).
+ firstTraf := moof.off + 8 + 16
+ tfhdSize := int64(binary.BigEndian.Uint32(orig[firstTraf+8:]))
+ tfdtSize := int64(binary.BigEndian.Uint32(orig[firstTraf+8+tfhdSize:]))
+ trun := firstTraf + 8 + tfhdSize + tfdtSize
+ if string(orig[trun+4:trun+8]) != "trun" {
+ t.Fatalf("the fixture's first traf is not tfhd, tfdt, trun")
+ }
+ dataOff := trun + 16
+ setDataOffset := func(v int32) []byte {
+ b := bytes.Clone(orig)
+ binary.BigEndian.PutUint32(b[dataOff:], uint32(v))
+ return b
+ }
+ for name, b := range map[string][]byte{
+ "empty": {},
+ "ftyp only": orig[:boxes[0].size],
+ "header only": orig[:moov.off+moov.size],
+ "a trailer box": append(bytes.Clone(orig), box("mfra", make([]byte, 8))...),
+ "a free box after moov": slices.Concat(orig[:moof.off], box("free", nil), orig[moof.off:]),
+ "a free box at the end": append(bytes.Clone(orig), box("free", nil)...),
+ "cut inside the last mdat": cut(orig, 1),
+ "cut inside a box header": append(bytes.Clone(orig), 0, 0, 0),
+ "moov first": setType(0, "moov"),
+ "two moofs": setType(boxes[3].off, "moof"),
+ "mdat before moof": setType(moof.off, "mdat"),
+ "a size past the file": setSize(boxes[len(boxes)-1].off, uint32(boxes[len(boxes)-1].size+1)),
+ "a size under its header": setSize(moof.off, 7),
+ "a size of 0 (to the end)": setSize(boxes[len(boxes)-1].off, 0),
+ "overlapping moof": setSize(moof.off, uint32(moof.size+8)),
+ "data offset into moof": setDataOffset(int32(moof.size)),
+ "data offset past mdat": setDataOffset(int32(moof.size + boxes[3].size)),
+ "negative data offset": setDataOffset(-8),
+ "tfhd not base-is-moof": func() []byte { b := bytes.Clone(orig); b[firstTraf+8+8+1] = 0; return b }(),
+ } {
+ if _, _, _, err := readFMP4(bytes.NewReader(b), int64(len(b))); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ if _, _, _, err := readFMP4(bytes.NewReader(orig[:moov.off+moov.size]), moov.off+moov.size); err != errNoFragments {
+ t.Errorf("header only: %v, want errNoFragments", err)
+ }
+}
+
+// TestReadFMP4FragmentLimit: a real fragment repeated, each copy's
+// tfdt moved on by one fragment's duration: 1,000,000 are read, the
+// 1,000,001st is refused. The same copies with one tfdt are refused
+// for their order.
+func TestReadFMP4FragmentLimit(t *testing.T) {
+ if testing.Short() {
+ t.Skip("reads a million fragments")
+ }
+ b := readFixture(t, "video-noaudio.mp4")
+ boxes := topBoxes(t, b)
+ moof := boxes[2]
+ // moof header, mfhd (16), traf header: then tfhd, then tfdt (v1).
+ tfhd := moof.off + 8 + 16 + 8
+ tfdt := tfhd + int64(binary.BigEndian.Uint32(b[tfhd:]))
+ if string(b[tfdt+4:tfdt+8]) != "tfdt" || b[tfdt+8] != 1 {
+ t.Fatal("the fixture's first traf is not tfhd then a version 1 tfdt")
+ }
+ r := &repeatReader{
+ head: b[:moof.off], frag: b[moof.off : boxes[3].off+boxes[3].size],
+ tfdtAt: tfdt + 12 - moof.off, step: 1 << 20,
+ }
+ r.n = maxFragments
+ if _, frags, _, err := readFMP4(r, r.size()); err != nil || len(frags) != maxFragments {
+ t.Fatalf("%d fragments: %d, %v", maxFragments, len(frags), err)
+ }
+ r.n = maxFragments + 1
+ if _, _, _, err := readFMP4(r, r.size()); err == nil || !strings.Contains(err.Error(), "over 1000000 fragments") {
+ t.Fatalf("%d fragments: %v", maxFragments+1, err)
+ }
+ r.n, r.step = 3, 0
+ if _, _, _, err := readFMP4(r, r.size()); err == nil || !strings.Contains(err.Error(), "tfdt does not increase") {
+ t.Fatalf("3 copies with one tfdt: %v", err)
+ }
+}
+
+// repeatReader is head followed by n copies of frag, without holding
+// them; copy i's 8-byte tfdt (at tfdtAt in frag) is i*step.
+type repeatReader struct {
+ head, frag []byte
+ n int64
+ tfdtAt int64
+ step uint64
+}
+
+func (r *repeatReader) size() int64 { return int64(len(r.head)) + r.n*int64(len(r.frag)) }
+
+func (r *repeatReader) ReadAt(p []byte, off int64) (int, error) {
+ n := 0
+ for n < len(p) {
+ at := off + int64(n)
+ if at < int64(len(r.head)) {
+ n += copy(p[n:], r.head[at:])
+ continue
+ }
+ i, in := (at-int64(len(r.head)))/int64(len(r.frag)), (at-int64(len(r.head)))%int64(len(r.frag))
+ if i >= r.n {
+ return n, io.EOF
+ }
+ var tfdt [8]byte
+ binary.BigEndian.PutUint64(tfdt[:], uint64(i)*r.step)
+ k := copy(p[n:], r.frag[in:])
+ for j := range k {
+ if x := in + int64(j) - r.tfdtAt; x >= 0 && x < 8 {
+ p[n+j] = tfdt[x]
+ }
+ }
+ n += k
+ }
+ return n, nil
+}
+
+// fragmentsValid reports whether frags are what readFMP4 promises: at
+// least one, contiguous from initLen to size, each with a positive
+// length and a positive, finite duration.
+func fragmentsValid(initLen int64, frags []fragment, size int64) bool {
+ if initLen <= 0 || len(frags) == 0 {
+ return false
+ }
+ at := initLen
+ for _, f := range frags {
+ if f.Offset != at || f.Length <= 0 || f.Length > size-at || !(f.DurationS > 0) || math.IsInf(f.DurationS, 0) {
+ return false
+ }
+ at += f.Length
+ }
+ return at == size
+}
+
+// FuzzReadFMP4: arbitrary bytes never panic, and anything readFMP4
+// accepts is a header and contiguous, in-bounds fragments with a
+// positive duration.
+func FuzzReadFMP4(f *testing.F) {
+ for _, name := range []string{"video.mp4", "video-noaudio.mp4", "audio.mp4"} {
+ b := readFixture(f, name)
+ f.Add(b)
+ f.Add(b[:len(b)/2])
+ }
+ f.Add(goodSynth().bytes())
+ f.Add([]byte{})
+ f.Add([]byte("\x00\x00\x00\x08ftyp\x00\x00\x00\x08moov"))
+ f.Fuzz(func(t *testing.T, b []byte) {
+ initLen, frags, durationMS, err := readFMP4(bytes.NewReader(b), int64(len(b)))
+ if err != nil {
+ return
+ }
+ if !fragmentsValid(initLen, frags, int64(len(b))) || durationMS <= 0 {
+ t.Fatalf("accepted %d, %+v, %d ms", initLen, frags, durationMS)
+ }
+ if err := writePlaylist(&bytes.Buffer{}, "video.mp4", initLen, frags); err != nil {
+ t.Fatalf("accepted fragments the playlist refuses: %v", err)
+ }
+ })
+}
diff --git a/internal/mediahandler/geometry.go b/internal/mediahandler/geometry.go
new file mode 100644
index 000000000..f74a10e90
--- /dev/null
+++ b/internal/mediahandler/geometry.go
@@ -0,0 +1,38 @@
+package mediahandler
+
+// The output box: video-720p is at most 1280x720 in either orientation
+// (spec §5.1).
+const (
+ boxLong = 1280
+ boxShort = 720
+)
+
+// targetSize is the video output's size (and the poster's) for a w x h
+// source with the display rotation rotation (probeFacts.Rotation: one
+// of -90, 0, 90, 180). ffmpeg applies the rotation before the scale
+// filter (autorotate), so a quarter turn swaps the sides first. The box
+// is 1280x720 for a landscape or square picture and 720x1280 for a
+// portrait one. A picture inside the box keeps its size (never
+// upscaled); a larger one is scaled to touch the box on its limiting
+// side, aspect kept, in integer arithmetic only. Each side is then
+// rounded down to even (yuv420p's chroma), and is at least 2.
+func targetSize(w, h, rotation int) (ow, oh int) {
+ if rotation == 90 || rotation == -90 || rotation == 270 || rotation == -270 {
+ w, h = h, w
+ }
+ w, h = max(w, 1), max(h, 1)
+ bw, bh := boxLong, boxShort
+ if w < h {
+ bw, bh = boxShort, boxLong
+ }
+ switch {
+ case w <= bw && h <= bh:
+ ow, oh = w, h
+ case int64(w)*int64(bh) > int64(h)*int64(bw):
+ // Width-limited.
+ ow, oh = bw, int(int64(h)*int64(bw)/int64(w))
+ default:
+ ow, oh = int(int64(w)*int64(bh)/int64(h)), bh
+ }
+ return max(ow&^1, 2), max(oh&^1, 2)
+}
diff --git a/internal/mediahandler/playlist.go b/internal/mediahandler/playlist.go
new file mode 100644
index 000000000..7cfd969a5
--- /dev/null
+++ b/internal/mediahandler/playlist.go
@@ -0,0 +1,131 @@
+package mediahandler
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// writePlaylist writes the HLS version 7 VOD playlist over one
+// fragmented MP4, name, as byte ranges (spec §5.1): its header as the
+// EXT-X-MAP, then one entry per fragment. The target duration is the
+// longest fragment rounded up, so every EXTINF rounds to at most it.
+// It is written here, never by ffmpeg. name must be a plain file name;
+// frags must be what readFMP4 answers (at least one, each with a
+// positive length and a positive, finite duration, none before the
+// header).
+func writePlaylist(w io.Writer, name string, initLen int64, frags []fragment) error {
+ if !plainName(name) {
+ return errors.New("playlist: the media name is not a plain file name")
+ }
+ if initLen <= 0 || len(frags) == 0 {
+ return errors.New("playlist: no header or no fragment")
+ }
+ longest := 0.0
+ for _, f := range frags {
+ if f.Offset < initLen || f.Length <= 0 || !(f.DurationS > 0) || math.IsInf(f.DurationS, 0) {
+ return errors.New("playlist: a fragment has no range or no duration")
+ }
+ longest = max(longest, f.DurationS)
+ }
+ var b strings.Builder
+ fmt.Fprintf(&b, "#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:%d\n", int64(math.Ceil(longest)))
+ b.WriteString("#EXT-X-PLAYLIST-TYPE:VOD\n#EXT-X-INDEPENDENT-SEGMENTS\n")
+ fmt.Fprintf(&b, "#EXT-X-MAP:URI=%q,BYTERANGE=\"%d@0\"\n", name, initLen)
+ for _, f := range frags {
+ fmt.Fprintf(&b, "#EXTINF:%.3f,\n#EXT-X-BYTERANGE:%d@%d\n%s\n", f.DurationS, f.Length, f.Offset, name)
+ }
+ b.WriteString("#EXT-X-ENDLIST\n")
+ _, err := io.WriteString(w, b.String())
+ return err
+}
+
+// plainName is a file name of letters, digits, '.', '_' and '-' only,
+// not starting with '.': nothing a playlist line or URI could be
+// broken by.
+func plainName(s string) bool {
+ if s == "" || s[0] == '.' {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ c := s[i]
+ if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-') {
+ return false
+ }
+ }
+ return true
+}
+
+// packageOutput reads the encode's <scratch>/out/<mediaName> with
+// readFMP4, writes its playlist as <scratch>/out/<playlistName> (a new
+// file, 0600), and answers the converted duration: readFMP4's, but
+// never more than the granted duration (spec A2, preflight F15: -t can
+// let a last video frame or AAC frame, and the encoder's priming, run
+// past it, and the console fails a result over the grant). It runs
+// after every child is dead, so nothing can swap the file between its
+// Lstat and its open. The media file must be a regular file, not a
+// symlink, and is opened inside the output directory (Task 6's collect
+// checks it again, by descriptor, before any upload).
+//
+// A file with no fragment (ffmpeg decoded nothing and still exited 0)
+// is unreadable; anything else readFMP4 or the write refuses is
+// engine_failed, with the reason logged.
+func packageOutput(cfg Config, p media.Payload, mediaName, playlistName string) (durationMS int64, err error) {
+ root, err := os.OpenRoot(filepath.Join(cfg.Scratch, "out"))
+ if err != nil {
+ return 0, packageFailed(cfg, "the output directory", err)
+ }
+ defer root.Close()
+ lfi, err := root.Lstat(mediaName)
+ if err != nil {
+ return 0, packageFailed(cfg, mediaName, err)
+ }
+ if !lfi.Mode().IsRegular() {
+ return 0, packageFailed(cfg, mediaName, errors.New("not a regular file"))
+ }
+ f, err := root.Open(mediaName)
+ if err != nil {
+ return 0, packageFailed(cfg, mediaName, err)
+ }
+ defer f.Close()
+ fi, err := f.Stat()
+ if err != nil {
+ return 0, packageFailed(cfg, mediaName, err)
+ }
+ initLen, frags, durationMS, err := readFMP4(f, fi.Size())
+ if errors.Is(err, errNoFragments) {
+ // engine.encode.empty (pending Luna pass).
+ cfg.Logf("codec: ffmpeg wrote no sample to %s", mediaName)
+ return 0, jobError{media.CodeUnreadable}
+ }
+ if err != nil {
+ return 0, packageFailed(cfg, mediaName, err)
+ }
+ out, err := root.OpenFile(playlistName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return 0, packageFailed(cfg, playlistName, err)
+ }
+ err = writePlaylist(out, mediaName, initLen, frags)
+ if cerr := out.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return 0, packageFailed(cfg, playlistName, err)
+ }
+ return min(durationMS, p.Limits.GrantedMS), nil
+}
+
+// packageFailed logs why an output could not be read or its playlist
+// written and answers engine_failed. what is an output's name; err is
+// the system's or readFMP4's, which quotes no byte of the file.
+func packageFailed(cfg Config, what string, err error) error {
+ // engine.encode.unusable (pending Luna pass).
+ cfg.Logf("codec: %s: %v", what, err)
+ return jobError{media.CodeEngineFailed}
+}
diff --git a/internal/mediahandler/procs.go b/internal/mediahandler/procs.go
index ab3f2af60..32cb7d8f6 100644
--- a/internal/mediahandler/procs.go
+++ b/internal/mediahandler/procs.go
@@ -1,9 +1,13 @@
package mediahandler
import (
+ "errors"
"path/filepath"
"sync"
+ "syscall"
"time"
+
+ "github.com/carlosframework/platform/internal/media"
)
// stderrTailBytes is how much of a child's stderr runChild keeps for
@@ -61,3 +65,19 @@ func (t *tail) Bytes() []byte {
}
return append([]byte(nil), b...)
}
+
+// childSignalled is a child's death by a signal. It is unreadable to
+// every caller that does not ask (errors.As finds jobError{unreadable}
+// through Unwrap); the encodes ask, to tell the OOM killer's SIGKILL
+// apart (encode).
+type childSignalled struct{ sig syscall.Signal }
+
+func (e childSignalled) Error() string { return media.CodeUnreadable }
+
+func (e childSignalled) Unwrap() error { return jobError{media.CodeUnreadable} }
+
+// killedBySIGKILL reports whether err is a child's death by SIGKILL.
+func killedBySIGKILL(err error) bool {
+ var cs childSignalled
+ return errors.As(err, &cs) && cs.sig == syscall.SIGKILL
+}
diff --git a/internal/mediahandler/procs_linux.go b/internal/mediahandler/procs_linux.go
index 4deb4b7c4..b7b44289c 100644
--- a/internal/mediahandler/procs_linux.go
+++ b/internal/mediahandler/procs_linux.go
@@ -54,7 +54,8 @@ func runChild(ctx context.Context, cfg Config, name string, args []string, dir s
// 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
+// unreadable for any other exit (a childSignalled, which is unreadable
+// too, for a death by signal); 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) {
@@ -149,6 +150,9 @@ func runChildTo(ctx context.Context, cfg Config, name string, args []string, dir
case waitErr == nil:
return tail.Bytes(), nil
case errors.As(waitErr, &exitErr):
+ if ws, ok := exitErr.Sys().(syscall.WaitStatus); ok && ws.Signaled() {
+ return tail.Bytes(), childSignalled{ws.Signal()}
+ }
return tail.Bytes(), jobError{media.CodeUnreadable}
}
return tail.Bytes(), childFailed(cfg, "wait failed", waitErr)
diff --git a/internal/mediahandler/realencode_test.go b/internal/mediahandler/realencode_test.go
new file mode 100644
index 000000000..dcb7619e6
--- /dev/null
+++ b/internal/mediahandler/realencode_test.go
@@ -0,0 +1,366 @@
+//go:build linux
+
+package mediahandler
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "maps"
+ "math"
+ "os"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// Encodes against the real ffmpeg (Debian 13's 7.1.5; realffmpeg_test.go
+// says how they skip). They hold Task 4's arguments to what the real
+// binary does: the size, codec, profile, pixel format, frame rate,
+// keyframes and fragments of the output, rotation and tone mapping,
+// no metadata, and readFMP4 and writePlaylist over what it writes.
+
+func init() {
+ // Sources for the encodes, made by the real ffmpeg from lavfi.
+ for name, r := range map[string]recipe{
+ // testdata/fmp4's sources: 10 s, so a 9 s grant cuts them.
+ "fixture-av": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc=size=160x90:rate=30:d=10 -f lavfi -i sine=d=10:sample_rate=44100 -ac 2 " +
+ "-c:v libx264 -preset ultrafast -c:a aac -f mp4 OUT", false},
+ "fixture-video": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc=size=160x90:rate=30:d=10 -c:v libx264 -preset ultrafast -f mp4 OUT", false},
+ "fixture-audio": {"wav", media.PresetAudioAAC,
+ "-f lavfi -i sine=d=10:sample_rate=44100 -ac 2 -c:a pcm_s16le -f wav OUT", false},
+ // 1080p H.264 with audio, 2.5 s.
+ "h264-1080p": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc2=size=1920x1080:rate=30:d=2.5 -f lavfi -i sine=d=2.5 -c:v libx264 -preset ultrafast -c:a aac -f mp4 OUT", false},
+ // PQ (smpte2084) 10-bit HEVC, 1 s.
+ "hevc-pq": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc2=size=1280x720:rate=30:d=1 " +
+ "-c:v libx265 -preset ultrafast -x265-params log-level=error:colorprim=bt2020:transfer=smpte2084:colormatrix=bt2020nc -pix_fmt yuv420p10le -color_primaries bt2020 -color_trc smpte2084 -colorspace bt2020nc -f mp4 OUT", false},
+ // The header's duration (the audio's, 3 s) is longer than the
+ // video (0.5 s): a poster 1 s in finds no frame.
+ "short-video-long-audio": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc=size=160x90:rate=10:d=0.5 -f lavfi -i sine=d=3 -c:v libx264 -preset ultrafast -c:a aac -f mp4 OUT", false},
+ } {
+ recipes[name] = r
+ }
+}
+
+// fmp4Fixture is one testdata/fmp4 file: its source recipe and the
+// grant it was encoded under.
+type fmp4Fixture struct {
+ file, recipe string
+ grantedMS int64
+}
+
+var fmp4Fixtures = []fmp4Fixture{
+ {"video.mp4", "fixture-av", 9000},
+ {"video-noaudio.mp4", "fixture-video", 9000},
+ {"audio.mp4", "fixture-audio", 9000},
+}
+
+// realEncode makes name's source, probes and checks it under preset with
+// grantedMS, and runs the preset's encode (video: video and poster;
+// audio: audio, no gain). It answers the facts and the payload.
+func realEncode(t *testing.T, cfg Config, name, preset string, grantedMS int64) (probeFacts, media.Payload) {
+ t.Helper()
+ r := makeSource(t, cfg, name)
+ for _, n := range append(append([]string{}, videoNames...), audioNames...) {
+ _ = os.Remove(outPath(cfg, n))
+ }
+ l := limitsFor(preset)
+ if grantedMS > 0 {
+ l.GrantedMS = grantedMS
+ }
+ p := media.Payload{Preset: preset, Limits: l}
+ f, err := probe(context.Background(), cfg, r.demuxer, preset)
+ if err != nil {
+ t.Fatalf("%s: probe: %v", name, err)
+ }
+ if grantedMS > 0 {
+ f.DurationMS = min(f.DurationMS, grantedMS) // a longer source, cut by -t
+ }
+ if err := check(f, preset, l); err != nil {
+ t.Fatalf("%s: check: %v", name, err)
+ }
+ if preset == media.PresetVideo720p {
+ err = encodeVideo(context.Background(), cfg, p, r.demuxer, f)
+ } else {
+ err = encodeAudio(context.Background(), cfg, p, r.demuxer, f, 0)
+ }
+ if err != nil {
+ t.Fatalf("%s: encode: %v", name, err)
+ }
+ return f, p
+}
+
+// TestRegenerateFMP4Fixtures rewrites testdata/fmp4 when
+// CARLOS_MEDIA_REGEN_FIXTURES=1: each file is this package's encode of
+// its recipe under a 9 s grant, beside it the real ffprobe's packets
+// and its first stream's duration, and args.txt records the exact arguments and the ffmpeg version.
+func TestRegenerateFMP4Fixtures(t *testing.T) {
+ if os.Getenv(regenEnv) != "1" {
+ t.Skipf("set %s=1 to rewrite testdata/fmp4", regenEnv)
+ }
+ cfg := realConfig(t)
+ var args bytes.Buffer
+ var version bytes.Buffer
+ runFFmpegOut(t, cfg, &version, "-version")
+ fmt.Fprintf(&args, "# %s\n", strings.SplitN(version.String(), "\n", 2)[0])
+ for _, fx := range fmp4Fixtures {
+ preset := recipes[fx.recipe].preset
+ f, p := realEncode(t, cfg, fx.recipe, preset, fx.grantedMS)
+ var a []string
+ name := videoNames[0]
+ if preset == media.PresetVideo720p {
+ a = videoArgs(cfg, f, p, recipes[fx.recipe].demuxer)
+ } else {
+ a = audioArgs(cfg, f, p, recipes[fx.recipe].demuxer, 0)
+ name = audioNames[0]
+ }
+ enc := json.NewEncoder(&args)
+ enc.SetEscapeHTML(false)
+ if err := enc.Encode(argsLine{File: fx.file, Args: scrubScratch(cfg, a)}); err != nil {
+ t.Fatal(err)
+ }
+ b, err := os.ReadFile(outPath(cfg, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join("testdata", "fmp4", fx.file), b, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var pk bytes.Buffer
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFprobe, []string{"-hide_banner", "-loglevel", "error",
+ "-show_entries", "packet=stream_index,dts_time,duration_time,pos,size", "-of", "csv=p=0", outPath(cfg, name)}, "", &pk); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join("testdata", "fmp4", fx.file+".packets.csv"), pk.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ var dur bytes.Buffer
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFprobe, []string{"-hide_banner", "-loglevel", "error",
+ "-select_streams", "0", "-show_entries", "stream=duration", "-of", "csv=p=0", outPath(cfg, name)}, "", &dur); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join("testdata", "fmp4", fx.file+".duration"), dur.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := os.WriteFile(filepath.Join("testdata", "fmp4", "args.txt"), args.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// scrubScratch writes the scratch directory as <scratch>.
+func scrubScratch(cfg Config, args []string) []string {
+ out := make([]string, len(args))
+ for i, a := range args {
+ out[i] = strings.ReplaceAll(a, cfg.Scratch, "<scratch>")
+ }
+ return out
+}
+
+// runFFmpegOut runs the real ffmpeg with args split on spaces, its
+// stdout to out.
+func runFFmpegOut(t *testing.T, cfg Config, out *bytes.Buffer, args string) {
+ t.Helper()
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFmpeg, strings.Fields(args), "", out); err != nil {
+ t.Fatalf("ffmpeg %s: %v", args, err)
+ }
+}
+
+// probedOutput is what the real ffprobe says of an encode's output.
+type probedOutput struct {
+ Streams []struct {
+ CodecType string `json:"codec_type"`
+ CodecName string `json:"codec_name"`
+ Profile string `json:"profile"`
+ Width int `json:"width"`
+ Height int `json:"height"`
+ PixFmt string `json:"pix_fmt"`
+ AvgFrameRate string `json:"avg_frame_rate"`
+ ColorTrc string `json:"color_transfer"`
+ SampleRate string `json:"sample_rate"`
+ Channels int `json:"channels"`
+ SideData []any `json:"side_data_list"`
+ } `json:"streams"`
+ Format struct {
+ Tags map[string]string `json:"tags"`
+ } `json:"format"`
+}
+
+func probeOutput(t *testing.T, cfg Config, path string) probedOutput {
+ t.Helper()
+ var out bytes.Buffer
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFprobe, []string{"-hide_banner", "-loglevel", "error",
+ "-show_entries", "stream=codec_type,codec_name,profile,width,height,pix_fmt,avg_frame_rate,color_transfer,sample_rate,channels:stream_side_data:format_tags",
+ "-of", "json", path}, "", &out); err != nil {
+ t.Fatalf("ffprobe %s: %v", path, err)
+ }
+ var p probedOutput
+ if err := json.Unmarshal(out.Bytes(), &p); err != nil {
+ t.Fatal(err)
+ }
+ return p
+}
+
+// packetsVia counts the packets the real ffprobe reads from path, per
+// stream ("0:270 1:423"), and the video keyframes' times.
+func packetsVia(t *testing.T, cfg Config, path string) (counts string, keyframes []float64) {
+ t.Helper()
+ var out bytes.Buffer
+ if _, err := runChildTo(context.Background(), cfg, cfg.FFprobe, []string{"-hide_banner", "-loglevel", "error",
+ "-protocol_whitelist", "file", "-show_entries", "packet=stream_index,pts_time,flags", "-of", "csv=p=0", path}, "", &out); err != nil {
+ t.Fatalf("ffprobe %s: %v", path, err)
+ }
+ n := map[string]int{}
+ for _, l := range strings.Split(strings.TrimSpace(out.String()), "\n") {
+ f := strings.Split(l, ",")
+ n[f[0]]++
+ if f[0] == "0" && strings.HasPrefix(f[2], "K") {
+ v, _ := strconv.ParseFloat(f[1], 64)
+ keyframes = append(keyframes, v)
+ }
+ }
+ keys := slices.Sorted(maps.Keys(n))
+ for i, k := range keys {
+ keys[i] = fmt.Sprintf("%s:%d", k, n[k])
+ }
+ return strings.Join(keys, " "), keyframes
+}
+
+// TestRealVideoEncodes: each source through encodeVideo and
+// packageOutput. The video is H.264 High yuv420p at targetSize, upright
+// (no display matrix), SDR, at most 30 fps, a keyframe every 2 s, with
+// AAC-LC stereo 48 kHz or no audio, and none of the source's tags; the
+// poster is a JPEG at the same size; the real ffprobe reads every
+// packet of the file through the playlist (Review Focus 1 and 5).
+func TestRealVideoEncodes(t *testing.T) {
+ cfg := realConfig(t)
+ for _, c := range []struct {
+ name string
+ ow, oh int
+ audio bool
+ maxFPS float64
+ hdrInput bool
+ }{
+ {"h264-1080p", 1280, 720, true, 30, false},
+ {"iphone-hevc-hlg-portrait", 720, 1280, true, 30, true},
+ {"hevc-pq", 1280, 720, false, 30, true},
+ {"vfr-screen-recording", 640, 400, false, 30, false},
+ {"fixture-video", 160, 90, false, 30, false},
+ {"short-video-long-audio", 160, 90, true, 30, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f, p := realEncode(t, cfg, c.name, media.PresetVideo720p, 0)
+ if f.HDR != c.hdrInput {
+ t.Fatalf("the source's HDR is %v", f.HDR)
+ }
+ if ow, oh := targetSize(f.Width, f.Height, f.Rotation); ow != c.ow || oh != c.oh {
+ t.Fatalf("targetSize %dx%d, want %dx%d", ow, oh, c.ow, c.oh)
+ }
+ durationMS, err := packageOutput(cfg, p, "video.mp4", "video.m3u8")
+ if err != nil {
+ t.Fatal(err)
+ }
+ out := probeOutput(t, cfg, outPath(cfg, "video.mp4"))
+ v := out.Streams[0]
+ if v.CodecName != "h264" || v.Profile != "High" || v.PixFmt != "yuv420p" || v.Width != c.ow || v.Height != c.oh {
+ t.Errorf("video %+v", v)
+ }
+ if len(v.SideData) != 0 {
+ t.Errorf("side data (a rotation?) %v", v.SideData)
+ }
+ if v.ColorTrc == "smpte2084" || v.ColorTrc == "arib-std-b67" {
+ t.Errorf("still HDR: %s", v.ColorTrc)
+ }
+ if fps, err := parseRate(v.AvgFrameRate); err != nil || fps > c.maxFPS+0.01 {
+ t.Errorf("frame rate %s", v.AvgFrameRate)
+ }
+ if c.audio {
+ if len(out.Streams) != 2 {
+ t.Fatalf("%d streams, want video and audio", len(out.Streams))
+ }
+ a := out.Streams[1]
+ if a.CodecName != "aac" || a.Profile != "LC" || a.SampleRate != "48000" || a.Channels != 2 {
+ t.Errorf("audio %+v", a)
+ }
+ } else if len(out.Streams) != 1 {
+ t.Errorf("%d streams, want the video alone", len(out.Streams))
+ }
+ for k, val := range out.Format.Tags {
+ if k == "location" || strings.Contains(val, "48.8584") {
+ t.Errorf("a source tag in the output: %s=%s", k, val)
+ }
+ }
+ direct, keys := packetsVia(t, cfg, outPath(cfg, "video.mp4"))
+ viaPlaylist, _ := packetsVia(t, cfg, outPath(cfg, "video.m3u8"))
+ if direct != viaPlaylist {
+ t.Errorf("packets: %s in the file, %s through the playlist", direct, viaPlaylist)
+ }
+ for i, k := range keys {
+ // Every 2 s from the first (B-frames shift every pts alike).
+ if want := keys[0] + float64(2*i); math.Abs(k-want) > 0.04 {
+ t.Errorf("keyframes at %v, want every 2 s", keys)
+ break
+ }
+ }
+ if want := (f.DurationMS + 1999) / 2000; int64(len(keys)) != want && !strings.HasPrefix(c.name, "short") {
+ t.Errorf("%d keyframes over %d ms, want %d", len(keys), f.DurationMS, want)
+ }
+ if durationMS <= 0 || durationMS > p.Limits.GrantedMS {
+ t.Errorf("duration %d ms", durationMS)
+ }
+ poster := probeOutput(t, cfg, outPath(cfg, "poster.jpg"))
+ if len(poster.Streams) != 1 || poster.Streams[0].CodecName != "mjpeg" || poster.Streams[0].Width != c.ow || poster.Streams[0].Height != c.oh {
+ t.Errorf("poster %+v", poster.Streams)
+ }
+ })
+ }
+}
+
+// TestRealAudioEncodes: each source through encodeAudio and
+// packageOutput: one AAC-LC track at 48 kHz, mono for a mono source,
+// else stereo (5.1 mixed down), cover art and video ignored, read
+// whole through the playlist; the gain changes the level.
+func TestRealAudioEncodes(t *testing.T) {
+ cfg := realConfig(t)
+ for _, c := range []struct {
+ name string
+ channels int
+ }{
+ {"wav-mono", 1},
+ {"aac-6ch", 2},
+ {"mp3-cover-art", 1},
+ {"chrome-webm-opus", 1},
+ {"av-no-duration", 1},
+ {"h264-1080p", 1},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ _, p := realEncode(t, cfg, c.name, media.PresetAudioAAC, 0)
+ if _, err := packageOutput(cfg, p, "audio.mp4", "audio.m3u8"); err != nil {
+ t.Fatal(err)
+ }
+ out := probeOutput(t, cfg, outPath(cfg, "audio.mp4"))
+ if len(out.Streams) != 1 {
+ t.Fatalf("%d streams, want one", len(out.Streams))
+ }
+ a := out.Streams[0]
+ if a.CodecName != "aac" || a.Profile != "LC" || a.SampleRate != "48000" || a.Channels != c.channels {
+ t.Errorf("audio %+v, want %d channels", a, c.channels)
+ }
+ direct, _ := packetsVia(t, cfg, outPath(cfg, "audio.mp4"))
+ viaPlaylist, _ := packetsVia(t, cfg, outPath(cfg, "audio.m3u8"))
+ if direct != viaPlaylist {
+ t.Errorf("packets: %s in the file, %s through the playlist", direct, viaPlaylist)
+ }
+ })
+ }
+}
diff --git a/internal/mediahandler/testdata/fmp4/args.txt b/internal/mediahandler/testdata/fmp4/args.txt
new file mode 100644
index 000000000..aceecad2a
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/args.txt
@@ -0,0 +1,4 @@
+# ffmpeg version 7.1.5-0+deb13u1 Copyright (c) 2000-2026 the FFmpeg developers
+{"file":"video.mp4","args":["-hide_banner","-nostats","-loglevel","error","-nostdin","-protocol_whitelist","file","-f","mov","-enable_drefs","0","-max_pixels","16777216","-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","-i","<scratch>/in/source","-map","0:0","-map","0:1","-sn","-dn","-map_metadata","-1","-map_chapters","-1","-t","9.000","-vf","scale=160:90:flags=bicubic,format=yuv420p","-c:v","libx264","-profile:v","high","-preset","veryfast","-crf","23","-maxrate","2500k","-bufsize","5000k","-pix_fmt","yuv420p","-fpsmax","30","-force_key_frames","expr:gte(t,n_forced*2)","-sc_threshold","0","-c:a","aac","-b:a","128k","-ac","2","-ar","48000","-f","mp4","-movflags","+frag_keyframe+empty_moov+default_base_moof+skip_trailer","-min_frag_duration","4000000","<scratch>/out/video.mp4"]}
+{"file":"video-noaudio.mp4","args":["-hide_banner","-nostats","-loglevel","error","-nostdin","-protocol_whitelist","file","-f","mov","-enable_drefs","0","-max_pixels","16777216","-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","-i","<scratch>/in/source","-map","0:0","-sn","-dn","-map_metadata","-1","-map_chapters","-1","-t","9.000","-vf","scale=160:90:flags=bicubic,format=yuv420p","-c:v","libx264","-profile:v","high","-preset","veryfast","-crf","23","-maxrate","2500k","-bufsize","5000k","-pix_fmt","yuv420p","-fpsmax","30","-force_key_frames","expr:gte(t,n_forced*2)","-sc_threshold","0","-an","-f","mp4","-movflags","+frag_keyframe+empty_moov+default_base_moof+skip_trailer","-min_frag_duration","4000000","<scratch>/out/video.mp4"]}
+{"file":"audio.mp4","args":["-hide_banner","-nostats","-loglevel","error","-nostdin","-protocol_whitelist","file","-f","wav","-max_pixels","16777216","-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","-i","<scratch>/in/source","-map","0:0","-vn","-sn","-dn","-map_metadata","-1","-map_chapters","-1","-t","9.000","-af","aformat=channel_layouts=stereo:sample_rates=48000,volume=0.00dB","-c:a","aac","-b:a","128k","-f","mp4","-movflags","+empty_moov+default_base_moof+skip_trailer","-frag_duration","4000000","<scratch>/out/audio.mp4"]}
diff --git a/internal/mediahandler/testdata/fmp4/audio.mp4 b/internal/mediahandler/testdata/fmp4/audio.mp4
new file mode 100644
index 000000000..a91870ea9
Binary files /dev/null and b/internal/mediahandler/testdata/fmp4/audio.mp4 differ
diff --git a/internal/mediahandler/testdata/fmp4/audio.mp4.duration b/internal/mediahandler/testdata/fmp4/audio.mp4.duration
new file mode 100644
index 000000000..944af80c6
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/audio.mp4.duration
@@ -0,0 +1 @@
+9.021333
diff --git a/internal/mediahandler/testdata/fmp4/audio.mp4.packets.csv b/internal/mediahandler/testdata/fmp4/audio.mp4.packets.csv
new file mode 100644
index 000000000..989438485
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/audio.mp4.packets.csv
@@ -0,0 +1,423 @@
+0,0.000000,N/A,300,1588
+0,0.021333,0.021333,393,1888
+0,0.042667,0.021333,312,2281
+0,0.064000,0.021333,335,2593
+0,0.085333,0.021333,311,2928
+0,0.106667,0.021333,335,3239
+0,0.128000,0.021333,333,3574
+0,0.149333,0.021333,342,3907
+0,0.170667,0.021333,313,4249
+0,0.192000,0.021333,344,4562
+0,0.213333,0.021333,337,4906
+0,0.234667,0.021333,339,5243
+0,0.256000,0.021333,347,5582
+0,0.277333,0.021333,351,5929
+0,0.298667,0.021333,333,6280
+0,0.320000,0.021333,346,6613
+0,0.341333,0.021333,342,6959
+0,0.362667,0.021333,333,7301
+0,0.384000,0.021333,332,7634
+0,0.405333,0.021333,356,7966
+0,0.426667,0.021333,353,8322
+0,0.448000,0.021333,339,8675
+0,0.469333,0.021333,337,9014
+0,0.490667,0.021333,336,9351
+0,0.512000,0.021333,356,9687
+0,0.533333,0.021333,338,10043
+0,0.554667,0.021333,339,10381
+0,0.576000,0.021333,342,10720
+0,0.597333,0.021333,352,11062
+0,0.618667,0.021333,343,11414
+0,0.640000,0.021333,340,11757
+0,0.661333,0.021333,332,12097
+0,0.682667,0.021333,330,12429
+0,0.704000,0.021333,351,12759
+0,0.725333,0.021333,344,13110
+0,0.746667,0.021333,354,13454
+0,0.768000,0.021333,344,13808
+0,0.789333,0.021333,337,14152
+0,0.810667,0.021333,343,14489
+0,0.832000,0.021333,354,14832
+0,0.853333,0.021333,383,15186
+0,0.874667,0.021333,323,15569
+0,0.896000,0.021333,320,15892
+0,0.917333,0.021333,343,16212
+0,0.938667,0.021333,316,16555
+0,0.960000,0.021333,364,16871
+0,0.981333,0.021333,336,17235
+0,1.002667,0.021333,339,17571
+0,1.024000,0.021333,325,17910
+0,1.045333,0.021333,351,18235
+0,1.066667,0.021333,364,18586
+0,1.088000,0.021333,335,18950
+0,1.109333,0.021333,329,19285
+0,1.130667,0.021333,348,19614
+0,1.152000,0.021333,326,19962
+0,1.173333,0.021333,343,20288
+0,1.194667,0.021333,340,20631
+0,1.216000,0.021333,366,20971
+0,1.237333,0.021333,354,21337
+0,1.258667,0.021333,329,21691
+0,1.280000,0.021333,323,22020
+0,1.301333,0.021333,361,22343
+0,1.322667,0.021333,353,22704
+0,1.344000,0.021333,319,23057
+0,1.365333,0.021333,337,23376
+0,1.386667,0.021333,315,23713
+0,1.408000,0.021333,363,24028
+0,1.429333,0.021333,350,24391
+0,1.450667,0.021333,323,24741
+0,1.472000,0.021333,342,25064
+0,1.493333,0.021333,362,25406
+0,1.514667,0.021333,349,25768
+0,1.536000,0.021333,345,26117
+0,1.557333,0.021333,334,26462
+0,1.578667,0.021333,333,26796
+0,1.600000,0.021333,344,27129
+0,1.621333,0.021333,341,27473
+0,1.642667,0.021333,340,27814
+0,1.664000,0.021333,331,28154
+0,1.685333,0.021333,343,28485
+0,1.706667,0.021333,351,28828
+0,1.728000,0.021333,342,29179
+0,1.749333,0.021333,342,29521
+0,1.770667,0.021333,328,29863
+0,1.792000,0.021333,378,30191
+0,1.813333,0.021333,345,30569
+0,1.834667,0.021333,325,30914
+0,1.856000,0.021333,337,31239
+0,1.877333,0.021333,334,31576
+0,1.898667,0.021333,342,31910
+0,1.920000,0.021333,342,32252
+0,1.941333,0.021333,343,32594
+0,1.962667,0.021333,333,32937
+0,1.984000,0.021333,358,33270
+0,2.005333,0.021333,343,33628
+0,2.026667,0.021333,341,33971
+0,2.048000,0.021333,324,34312
+0,2.069333,0.021333,343,34636
+0,2.090667,0.021333,360,34979
+0,2.112000,0.021333,357,35339
+0,2.133333,0.021333,342,35696
+0,2.154667,0.021333,303,36038
+0,2.176000,0.021333,375,36341
+0,2.197333,0.021333,347,36716
+0,2.218667,0.021333,343,37063
+0,2.240000,0.021333,338,37406
+0,2.261333,0.021333,337,37744
+0,2.282667,0.021333,346,38081
+0,2.304000,0.021333,314,38427
+0,2.325333,0.021333,360,38741
+0,2.346667,0.021333,352,39101
+0,2.368000,0.021333,348,39453
+0,2.389333,0.021333,330,39801
+0,2.410667,0.021333,336,40131
+0,2.432000,0.021333,353,40467
+0,2.453333,0.021333,337,40820
+0,2.474667,0.021333,340,41157
+0,2.496000,0.021333,331,41497
+0,2.517333,0.021333,354,41828
+0,2.538667,0.021333,369,42182
+0,2.560000,0.021333,322,42551
+0,2.581333,0.021333,317,42873
+0,2.602667,0.021333,357,43190
+0,2.624000,0.021333,354,43547
+0,2.645333,0.021333,345,43901
+0,2.666667,0.021333,335,44246
+0,2.688000,0.021333,345,44581
+0,2.709333,0.021333,333,44926
+0,2.730667,0.021333,356,45259
+0,2.752000,0.021333,340,45615
+0,2.773333,0.021333,324,45955
+0,2.794667,0.021333,337,46279
+0,2.816000,0.021333,383,46616
+0,2.837333,0.021333,354,46999
+0,2.858667,0.021333,327,47353
+0,2.880000,0.021333,328,47680
+0,2.901333,0.021333,326,48008
+0,2.922667,0.021333,369,48334
+0,2.944000,0.021333,324,48703
+0,2.965333,0.021333,357,49027
+0,2.986667,0.021333,338,49384
+0,3.008000,0.021333,317,49722
+0,3.029333,0.021333,334,50039
+0,3.050667,0.021333,360,50373
+0,3.072000,0.021333,345,50733
+0,3.093333,0.021333,329,51078
+0,3.114667,0.021333,357,51407
+0,3.136000,0.021333,346,51764
+0,3.157333,0.021333,341,52110
+0,3.178667,0.021333,317,52451
+0,3.200000,0.021333,351,52768
+0,3.221333,0.021333,353,53119
+0,3.242667,0.021333,350,53472
+0,3.264000,0.021333,350,53822
+0,3.285333,0.021333,326,54172
+0,3.306667,0.021333,340,54498
+0,3.328000,0.021333,333,54838
+0,3.349333,0.021333,345,55171
+0,3.370667,0.021333,340,55516
+0,3.392000,0.021333,350,55856
+0,3.413333,0.021333,327,56206
+0,3.434667,0.021333,358,56533
+0,3.456000,0.021333,348,56891
+0,3.477333,0.021333,313,57239
+0,3.498667,0.021333,351,57552
+0,3.520000,0.021333,337,57903
+0,3.541333,0.021333,346,58240
+0,3.562667,0.021333,337,58586
+0,3.584000,0.021333,348,58923
+0,3.605333,0.021333,331,59271
+0,3.626667,0.021333,365,59602
+0,3.648000,0.021333,353,59967
+0,3.669333,0.021333,338,60320
+0,3.690667,0.021333,341,60658
+0,3.712000,0.021333,335,60999
+0,3.733333,0.021333,340,61334
+0,3.754667,0.021333,331,61674
+0,3.776000,0.021333,365,62005
+0,3.797333,0.021333,336,62370
+0,3.818667,0.021333,335,62706
+0,3.840000,0.021333,337,63041
+0,3.861333,0.021333,345,63378
+0,3.882667,0.021333,345,63723
+0,3.904000,0.021333,333,64068
+0,3.925333,0.021333,342,64401
+0,3.946667,0.021333,353,64743
+0,3.968000,0.021333,338,65096
+0,3.989333,0.021333,351,65434
+0,4.010667,0.021333,328,66645
+0,4.032000,0.021333,345,66973
+0,4.053333,0.021333,341,67318
+0,4.074667,0.021333,323,67659
+0,4.096000,0.021333,359,67982
+0,4.117333,0.021333,339,68341
+0,4.138667,0.021333,333,68680
+0,4.160000,0.021333,327,69013
+0,4.181333,0.021333,347,69340
+0,4.202667,0.021333,339,69687
+0,4.224000,0.021333,363,70026
+0,4.245333,0.021333,346,70389
+0,4.266667,0.021333,322,70735
+0,4.288000,0.021333,348,71057
+0,4.309333,0.021333,354,71405
+0,4.330667,0.021333,344,71759
+0,4.352000,0.021333,334,72103
+0,4.373333,0.021333,334,72437
+0,4.394667,0.021333,336,72771
+0,4.416000,0.021333,367,73107
+0,4.437333,0.021333,342,73474
+0,4.458667,0.021333,337,73816
+0,4.480000,0.021333,346,74153
+0,4.501333,0.021333,325,74499
+0,4.522667,0.021333,352,74824
+0,4.544000,0.021333,321,75176
+0,4.565333,0.021333,370,75497
+0,4.586667,0.021333,338,75867
+0,4.608000,0.021333,349,76205
+0,4.629333,0.021333,331,76554
+0,4.650667,0.021333,335,76885
+0,4.672000,0.021333,332,77220
+0,4.693333,0.021333,330,77552
+0,4.714667,0.021333,369,77882
+0,4.736000,0.021333,339,78251
+0,4.757333,0.021333,327,78590
+0,4.778667,0.021333,344,78917
+0,4.800000,0.021333,355,79261
+0,4.821333,0.021333,354,79616
+0,4.842667,0.021333,330,79970
+0,4.864000,0.021333,339,80300
+0,4.885333,0.021333,332,80639
+0,4.906667,0.021333,347,80971
+0,4.928000,0.021333,356,81318
+0,4.949333,0.021333,325,81674
+0,4.970667,0.021333,353,81999
+0,4.992000,0.021333,338,82352
+0,5.013333,0.021333,337,82690
+0,5.034667,0.021333,353,83027
+0,5.056000,0.021333,337,83380
+0,5.077333,0.021333,345,83717
+0,5.098667,0.021333,344,84062
+0,5.120000,0.021333,324,84406
+0,5.141333,0.021333,352,84730
+0,5.162667,0.021333,333,85082
+0,5.184000,0.021333,353,85415
+0,5.205333,0.021333,329,85768
+0,5.226667,0.021333,356,86097
+0,5.248000,0.021333,344,86453
+0,5.269333,0.021333,337,86797
+0,5.290667,0.021333,345,87134
+0,5.312000,0.021333,332,87479
+0,5.333333,0.021333,346,87811
+0,5.354667,0.021333,337,88157
+0,5.376000,0.021333,342,88494
+0,5.397333,0.021333,341,88836
+0,5.418667,0.021333,340,89177
+0,5.440000,0.021333,347,89517
+0,5.461333,0.021333,350,89864
+0,5.482667,0.021333,337,90214
+0,5.504000,0.021333,331,90551
+0,5.525333,0.021333,338,90882
+0,5.546667,0.021333,346,91220
+0,5.568000,0.021333,337,91566
+0,5.589333,0.021333,349,91903
+0,5.610667,0.021333,346,92252
+0,5.632000,0.021333,341,92598
+0,5.653333,0.021333,333,92939
+0,5.674667,0.021333,343,93272
+0,5.696000,0.021333,338,93615
+0,5.717333,0.021333,341,93953
+0,5.738667,0.021333,349,94294
+0,5.760000,0.021333,340,94643
+0,5.781333,0.021333,348,94983
+0,5.802667,0.021333,338,95331
+0,5.824000,0.021333,340,95669
+0,5.845333,0.021333,346,96009
+0,5.866667,0.021333,332,96355
+0,5.888000,0.021333,341,96687
+0,5.909333,0.021333,350,97028
+0,5.930667,0.021333,348,97378
+0,5.952000,0.021333,336,97726
+0,5.973333,0.021333,332,98062
+0,5.994667,0.021333,338,98394
+0,6.016000,0.021333,351,98732
+0,6.037333,0.021333,331,99083
+0,6.058667,0.021333,355,99414
+0,6.080000,0.021333,344,99769
+0,6.101333,0.021333,344,100113
+0,6.122667,0.021333,334,100457
+0,6.144000,0.021333,346,100791
+0,6.165333,0.021333,335,101137
+0,6.186667,0.021333,351,101472
+0,6.208000,0.021333,335,101823
+0,6.229333,0.021333,338,102158
+0,6.250667,0.021333,349,102496
+0,6.272000,0.021333,340,102845
+0,6.293333,0.021333,339,103185
+0,6.314667,0.021333,339,103524
+0,6.336000,0.021333,347,103863
+0,6.357333,0.021333,335,104210
+0,6.378667,0.021333,336,104545
+0,6.400000,0.021333,353,104881
+0,6.421333,0.021333,338,105234
+0,6.442667,0.021333,341,105572
+0,6.464000,0.021333,345,105913
+0,6.485333,0.021333,338,106258
+0,6.506667,0.021333,343,106596
+0,6.528000,0.021333,351,106939
+0,6.549333,0.021333,338,107290
+0,6.570667,0.021333,335,107628
+0,6.592000,0.021333,341,107963
+0,6.613333,0.021333,347,108304
+0,6.634667,0.021333,342,108651
+0,6.656000,0.021333,344,108993
+0,6.677333,0.021333,337,109337
+0,6.698667,0.021333,337,109674
+0,6.720000,0.021333,345,110011
+0,6.741333,0.021333,344,110356
+0,6.762667,0.021333,327,110700
+0,6.784000,0.021333,360,111027
+0,6.805333,0.021333,332,111387
+0,6.826667,0.021333,350,111719
+0,6.848000,0.021333,350,112069
+0,6.869333,0.021333,325,112419
+0,6.890667,0.021333,350,112744
+0,6.912000,0.021333,336,113094
+0,6.933333,0.021333,350,113430
+0,6.954667,0.021333,324,113780
+0,6.976000,0.021333,360,114104
+0,6.997333,0.021333,334,114464
+0,7.018667,0.021333,341,114798
+0,7.040000,0.021333,342,115139
+0,7.061333,0.021333,339,115481
+0,7.082667,0.021333,350,115820
+0,7.104000,0.021333,326,116170
+0,7.125333,0.021333,360,116496
+0,7.146667,0.021333,325,116856
+0,7.168000,0.021333,355,117181
+0,7.189333,0.021333,332,117536
+0,7.210667,0.021333,350,117868
+0,7.232000,0.021333,332,118218
+0,7.253333,0.021333,340,118550
+0,7.274667,0.021333,347,118890
+0,7.296000,0.021333,332,119237
+0,7.317333,0.021333,353,119569
+0,7.338667,0.021333,330,119922
+0,7.360000,0.021333,355,120252
+0,7.381333,0.021333,330,120607
+0,7.402667,0.021333,351,120937
+0,7.424000,0.021333,330,121288
+0,7.445333,0.021333,347,121618
+0,7.466667,0.021333,332,121965
+0,7.488000,0.021333,358,122297
+0,7.509333,0.021333,330,122655
+0,7.530667,0.021333,350,122985
+0,7.552000,0.021333,339,123335
+0,7.573333,0.021333,339,123674
+0,7.594667,0.021333,346,124013
+0,7.616000,0.021333,327,124359
+0,7.637333,0.021333,355,124686
+0,7.658667,0.021333,334,125041
+0,7.680000,0.021333,341,125375
+0,7.701333,0.021333,343,125716
+0,7.722667,0.021333,331,126059
+0,7.744000,0.021333,367,126390
+0,7.765333,0.021333,320,126757
+0,7.786667,0.021333,365,127077
+0,7.808000,0.021333,321,127442
+0,7.829333,0.021333,367,127763
+0,7.850667,0.021333,312,128130
+0,7.872000,0.021333,371,128442
+0,7.893333,0.021333,309,128813
+0,7.914667,0.021333,370,129122
+0,7.936000,0.021333,319,129492
+0,7.957333,0.021333,351,129811
+0,7.978667,0.021333,340,130162
+0,8.000000,0.021333,341,130502
+0,8.021333,0.021333,336,131327
+0,8.042667,0.021333,344,131663
+0,8.064000,0.021333,342,132007
+0,8.085333,0.021333,327,132349
+0,8.106667,0.021333,357,132676
+0,8.128000,0.021333,336,133033
+0,8.149333,0.021333,342,133369
+0,8.170667,0.021333,336,133711
+0,8.192000,0.021333,343,134047
+0,8.213333,0.021333,338,134390
+0,8.234667,0.021333,338,134728
+0,8.256000,0.021333,355,135066
+0,8.277333,0.021333,332,135421
+0,8.298667,0.021333,341,135753
+0,8.320000,0.021333,340,136094
+0,8.341333,0.021333,336,136434
+0,8.362667,0.021333,349,136770
+0,8.384000,0.021333,339,137119
+0,8.405333,0.021333,341,137458
+0,8.426667,0.021333,344,137799
+0,8.448000,0.021333,348,138143
+0,8.469333,0.021333,324,138491
+0,8.490667,0.021333,362,138815
+0,8.512000,0.021333,328,139177
+0,8.533333,0.021333,359,139505
+0,8.554667,0.021333,322,139864
+0,8.576000,0.021333,356,140186
+0,8.597333,0.021333,329,140542
+0,8.618667,0.021333,350,140871
+0,8.640000,0.021333,332,141221
+0,8.661333,0.021333,349,141553
+0,8.682667,0.021333,348,141902
+0,8.704000,0.021333,329,142250
+0,8.725333,0.021333,349,142579
+0,8.746667,0.021333,328,142928
+0,8.768000,0.021333,358,143256
+0,8.789333,0.021333,333,143614
+0,8.810667,0.021333,334,143947
+0,8.832000,0.021333,341,144281
+0,8.853333,0.021333,347,144622
+0,8.874667,0.021333,339,144969
+0,8.896000,0.021333,339,145308
+0,8.917333,0.021333,344,145647
+0,8.938667,0.021333,337,145991
+0,8.960000,0.021333,353,146328
+0,8.981333,0.021333,314,146681
+0,9.002667,0.021333,381,146995
diff --git a/internal/mediahandler/testdata/fmp4/provenance.txt b/internal/mediahandler/testdata/fmp4/provenance.txt
new file mode 100644
index 000000000..25a2b66c9
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/provenance.txt
@@ -0,0 +1,39 @@
+Where each fixture comes from (plan 3 Task 4).
+
+Made by Debian 13's ffmpeg 7.1.5 (7:7.1.5-0+deb13u1, amd64, unpacked
+without root on docs-t1) with this package's own videoArgs and
+audioArgs: TestRegenerateFMP4Fixtures in realencode_test.go encodes each
+recipe under a 9 s grant through runChild, exactly as the handler does,
+and writes args.txt (the version line, then each file's exact
+arguments, the scratch path written <scratch>). Rewrite them with:
+
+ . <ffmpeg dir>/env.sh
+ CARLOS_MEDIA_REGEN_FIXTURES=1 go test ./internal/mediahandler/ -run TestRegenerateFMP4Fixtures
+
+video.mp4 recipe fixture-av: lavfi testsrc 160x90 30 fps
+ + 44.1 kHz stereo sine, 10 s, H.264 + AAC in
+ MP4; encoded with audio, cut to 9 s
+video-noaudio.mp4 recipe fixture-video: the same video alone
+audio.mp4 recipe fixture-audio: 10 s 44.1 kHz stereo
+ sine, PCM WAV; encoded with no gain, cut to
+ 9 s (it ends at 9.021 s: the AAC priming and
+ the last frame, trimmed to 896 samples)
+<file>.packets.csv ffprobe -show_entries
+ packet=stream_index,dts_time,duration_time,size,pos
+ -of csv=p=0 (ffprobe's column order)
+<file>.duration ffprobe -select_streams 0
+ -show_entries stream=duration -of csv=p=0
+args.txt the exact ffmpeg arguments of each
+
+Each file is ftyp, moov, then three moof/mdat pairs (4 s, 4 s, 1 s), no
+free and no mfra box.
+
+Provisional: plan 1's spike makes the same files with the same arguments
+on arm64 (docs/superpowers/reviews/media-spike-fixtures/fmp4/); when its
+report lands, these are replaced by its files and args.txt by its
+recorded muxer flags, and TestReadFMP4Fixtures and
+TestMuxerArgsMatchTheFixtures rerun against them. The box sequence and
+the muxer flags are not expected to depend on the architecture (the mov
+muxer is the same C code), but the encoded bytes, and so the offsets,
+may differ: x264's and the AAC encoder's output is not promised to be
+identical across CPU feature sets.
diff --git a/internal/mediahandler/testdata/fmp4/video-noaudio.mp4 b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4
new file mode 100644
index 000000000..8b09d0bfc
Binary files /dev/null and b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4 differ
diff --git a/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.duration b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.duration
new file mode 100644
index 000000000..a2041e9ee
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.duration
@@ -0,0 +1 @@
+9.000000
diff --git a/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.packets.csv b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.packets.csv
new file mode 100644
index 000000000..bd08b0fb6
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/video-noaudio.mp4.packets.csv
@@ -0,0 +1,270 @@
+0,0.000000,0.033333,2151,2344
+0,0.033333,0.033333,110,4495
+0,0.066667,0.033333,88,4605
+0,0.100000,0.033333,79,4693
+0,0.133333,0.033333,87,4772
+0,0.166667,0.033333,114,4859
+0,0.200000,0.033333,74,4973
+0,0.233333,0.033333,93,5047
+0,0.266667,0.033333,93,5140
+0,0.300000,0.033333,99,5233
+0,0.333333,0.033333,117,5332
+0,0.366667,0.033333,87,5449
+0,0.400000,0.033333,101,5536
+0,0.433333,0.033333,80,5637
+0,0.466667,0.033333,97,5717
+0,0.500000,0.033333,79,5814
+0,0.533333,0.033333,98,5893
+0,0.566667,0.033333,81,5991
+0,0.600000,0.033333,82,6072
+0,0.633333,0.033333,97,6154
+0,0.666667,0.033333,70,6251
+0,0.700000,0.033333,117,6321
+0,0.733333,0.033333,88,6438
+0,0.766667,0.033333,84,6526
+0,0.800000,0.033333,82,6610
+0,0.833333,0.033333,100,6692
+0,0.866667,0.033333,89,6792
+0,0.900000,0.033333,98,6881
+0,0.933333,0.033333,79,6979
+0,0.966667,0.033333,93,7058
+0,1.000000,0.033333,138,7151
+0,1.033333,0.033333,114,7289
+0,1.066667,0.033333,106,7403
+0,1.100000,0.033333,80,7509
+0,1.133333,0.033333,104,7589
+0,1.166667,0.033333,90,7693
+0,1.200000,0.033333,121,7783
+0,1.233333,0.033333,90,7904
+0,1.266667,0.033333,90,7994
+0,1.300000,0.033333,90,8084
+0,1.333333,0.033333,109,8174
+0,1.366667,0.033333,89,8283
+0,1.400000,0.033333,97,8372
+0,1.433333,0.033333,92,8469
+0,1.466667,0.033333,101,8561
+0,1.500000,0.033333,98,8662
+0,1.533333,0.033333,103,8760
+0,1.566667,0.033333,112,8863
+0,1.600000,0.033333,89,8975
+0,1.633333,0.033333,134,9064
+0,1.666667,0.033333,99,9198
+0,1.700000,0.033333,104,9297
+0,1.733333,0.033333,94,9401
+0,1.766667,0.033333,126,9495
+0,1.800000,0.033333,114,9621
+0,1.833333,0.033333,116,9735
+0,1.866667,0.033333,88,9851
+0,1.900000,0.033333,115,9939
+0,1.933333,0.033333,118,10054
+0,1.966667,0.033333,124,10172
+0,2.000000,0.033333,1614,10296
+0,2.033333,0.033333,114,11910
+0,2.066667,0.033333,83,12024
+0,2.100000,0.033333,108,12107
+0,2.133333,0.033333,106,12215
+0,2.166667,0.033333,95,12321
+0,2.200000,0.033333,114,12416
+0,2.233333,0.033333,97,12530
+0,2.266667,0.033333,131,12627
+0,2.300000,0.033333,91,12758
+0,2.333333,0.033333,119,12849
+0,2.366667,0.033333,81,12968
+0,2.400000,0.033333,84,13049
+0,2.433333,0.033333,118,13133
+0,2.466667,0.033333,113,13251
+0,2.500000,0.033333,131,13364
+0,2.533333,0.033333,93,13495
+0,2.566667,0.033333,113,13588
+0,2.600000,0.033333,128,13701
+0,2.633333,0.033333,102,13829
+0,2.666667,0.033333,100,13931
+0,2.700000,0.033333,126,14031
+0,2.733333,0.033333,119,14157
+0,2.766667,0.033333,127,14276
+0,2.800000,0.033333,120,14403
+0,2.833333,0.033333,103,14523
+0,2.866667,0.033333,108,14626
+0,2.900000,0.033333,133,14734
+0,2.933333,0.033333,88,14867
+0,2.966667,0.033333,130,14955
+0,3.000000,0.033333,147,15085
+0,3.033333,0.033333,112,15232
+0,3.066667,0.033333,96,15344
+0,3.100000,0.033333,89,15440
+0,3.133333,0.033333,96,15529
+0,3.166667,0.033333,96,15625
+0,3.200000,0.033333,99,15721
+0,3.233333,0.033333,93,15820
+0,3.266667,0.033333,109,15913
+0,3.300000,0.033333,110,16022
+0,3.333333,0.033333,96,16132
+0,3.366667,0.033333,94,16228
+0,3.400000,0.033333,90,16322
+0,3.433333,0.033333,77,16412
+0,3.466667,0.033333,112,16489
+0,3.500000,0.033333,72,16601
+0,3.533333,0.033333,91,16673
+0,3.566667,0.033333,93,16764
+0,3.600000,0.033333,90,16857
+0,3.633333,0.033333,110,16947
+0,3.666667,0.033333,84,17057
+0,3.700000,0.033333,94,17141
+0,3.733333,0.033333,97,17235
+0,3.766667,0.033333,99,17332
+0,3.800000,0.033333,90,17431
+0,3.833333,0.033333,85,17521
+0,3.866667,0.033333,95,17606
+0,3.900000,0.033333,107,17701
+0,3.933333,0.033333,95,17808
+0,3.966667,0.033333,101,17903
+0,4.000000,0.033333,1602,19552
+0,4.033333,0.033333,104,21154
+0,4.066667,0.033333,86,21258
+0,4.100000,0.033333,104,21344
+0,4.133333,0.033333,106,21448
+0,4.166667,0.033333,98,21554
+0,4.200000,0.033333,96,21652
+0,4.233333,0.033333,97,21748
+0,4.266667,0.033333,98,21845
+0,4.300000,0.033333,100,21943
+0,4.333333,0.033333,121,22043
+0,4.366667,0.033333,79,22164
+0,4.400000,0.033333,113,22243
+0,4.433333,0.033333,99,22356
+0,4.466667,0.033333,94,22455
+0,4.500000,0.033333,102,22549
+0,4.533333,0.033333,79,22651
+0,4.566667,0.033333,94,22730
+0,4.600000,0.033333,88,22824
+0,4.633333,0.033333,114,22912
+0,4.666667,0.033333,97,23026
+0,4.700000,0.033333,95,23123
+0,4.733333,0.033333,86,23218
+0,4.766667,0.033333,105,23304
+0,4.800000,0.033333,96,23409
+0,4.833333,0.033333,97,23505
+0,4.866667,0.033333,88,23602
+0,4.900000,0.033333,113,23690
+0,4.933333,0.033333,110,23803
+0,4.966667,0.033333,108,23913
+0,5.000000,0.033333,146,24021
+0,5.033333,0.033333,120,24167
+0,5.066667,0.033333,101,24287
+0,5.100000,0.033333,121,24388
+0,5.133333,0.033333,96,24509
+0,5.166667,0.033333,108,24605
+0,5.200000,0.033333,106,24713
+0,5.233333,0.033333,103,24819
+0,5.266667,0.033333,118,24922
+0,5.300000,0.033333,89,25040
+0,5.333333,0.033333,110,25129
+0,5.366667,0.033333,92,25239
+0,5.400000,0.033333,108,25331
+0,5.433333,0.033333,109,25439
+0,5.466667,0.033333,126,25548
+0,5.500000,0.033333,126,25674
+0,5.533333,0.033333,114,25800
+0,5.566667,0.033333,117,25914
+0,5.600000,0.033333,130,26031
+0,5.633333,0.033333,116,26161
+0,5.666667,0.033333,82,26277
+0,5.700000,0.033333,150,26359
+0,5.733333,0.033333,139,26509
+0,5.766667,0.033333,143,26648
+0,5.800000,0.033333,111,26791
+0,5.833333,0.033333,110,26902
+0,5.866667,0.033333,126,27012
+0,5.900000,0.033333,121,27138
+0,5.933333,0.033333,106,27259
+0,5.966667,0.033333,98,27365
+0,6.000000,0.033333,1591,27463
+0,6.033333,0.033333,121,29054
+0,6.066667,0.033333,100,29175
+0,6.100000,0.033333,78,29275
+0,6.133333,0.033333,90,29353
+0,6.166667,0.033333,88,29443
+0,6.200000,0.033333,91,29531
+0,6.233333,0.033333,87,29622
+0,6.266667,0.033333,107,29709
+0,6.300000,0.033333,87,29816
+0,6.333333,0.033333,85,29903
+0,6.366667,0.033333,78,29988
+0,6.400000,0.033333,123,30066
+0,6.433333,0.033333,95,30189
+0,6.466667,0.033333,81,30284
+0,6.500000,0.033333,75,30365
+0,6.533333,0.033333,94,30440
+0,6.566667,0.033333,99,30534
+0,6.600000,0.033333,81,30633
+0,6.633333,0.033333,99,30714
+0,6.666667,0.033333,75,30813
+0,6.700000,0.033333,84,30888
+0,6.733333,0.033333,90,30972
+0,6.766667,0.033333,88,31062
+0,6.800000,0.033333,89,31150
+0,6.833333,0.033333,93,31239
+0,6.866667,0.033333,88,31332
+0,6.900000,0.033333,88,31420
+0,6.933333,0.033333,96,31508
+0,6.966667,0.033333,103,31604
+0,7.000000,0.033333,150,31707
+0,7.033333,0.033333,115,31857
+0,7.066667,0.033333,108,31972
+0,7.100000,0.033333,86,32080
+0,7.133333,0.033333,125,32166
+0,7.166667,0.033333,81,32291
+0,7.200000,0.033333,140,32372
+0,7.233333,0.033333,81,32512
+0,7.266667,0.033333,95,32593
+0,7.300000,0.033333,89,32688
+0,7.333333,0.033333,100,32777
+0,7.366667,0.033333,109,32877
+0,7.400000,0.033333,87,32986
+0,7.433333,0.033333,102,33073
+0,7.466667,0.033333,92,33175
+0,7.500000,0.033333,93,33267
+0,7.533333,0.033333,97,33360
+0,7.566667,0.033333,110,33457
+0,7.600000,0.033333,117,33567
+0,7.633333,0.033333,112,33684
+0,7.666667,0.033333,90,33796
+0,7.700000,0.033333,109,33886
+0,7.733333,0.033333,104,33995
+0,7.766667,0.033333,103,34099
+0,7.800000,0.033333,110,34202
+0,7.833333,0.033333,102,34312
+0,7.866667,0.033333,120,34414
+0,7.900000,0.033333,106,34534
+0,7.933333,0.033333,95,34640
+0,7.966667,0.033333,129,34735
+0,8.000000,0.033333,1605,35216
+0,8.033333,0.033333,127,36821
+0,8.066667,0.033333,88,36948
+0,8.100000,0.033333,107,37036
+0,8.133333,0.033333,99,37143
+0,8.166667,0.033333,99,37242
+0,8.200000,0.033333,125,37341
+0,8.233333,0.033333,92,37466
+0,8.266667,0.033333,113,37558
+0,8.300000,0.033333,91,37671
+0,8.333333,0.033333,109,37762
+0,8.366667,0.033333,84,37871
+0,8.400000,0.033333,116,37955
+0,8.433333,0.033333,89,38071
+0,8.466667,0.033333,107,38160
+0,8.500000,0.033333,124,38267
+0,8.533333,0.033333,117,38391
+0,8.566667,0.033333,120,38508
+0,8.600000,0.033333,89,38628
+0,8.633333,0.033333,116,38717
+0,8.666667,0.033333,110,38833
+0,8.700000,0.033333,122,38943
+0,8.733333,0.033333,109,39065
+0,8.766667,0.033333,99,39174
+0,8.800000,0.033333,89,39273
+0,8.833333,0.033333,114,39362
+0,8.866667,0.033333,110,39476
+0,8.900000,0.033333,80,39586
+0,8.933333,0.033333,79,39666
+0,8.966667,0.033333,52,39745
diff --git a/internal/mediahandler/testdata/fmp4/video.mp4 b/internal/mediahandler/testdata/fmp4/video.mp4
new file mode 100644
index 000000000..b473dc11c
Binary files /dev/null and b/internal/mediahandler/testdata/fmp4/video.mp4 differ
diff --git a/internal/mediahandler/testdata/fmp4/video.mp4.duration b/internal/mediahandler/testdata/fmp4/video.mp4.duration
new file mode 100644
index 000000000..a2041e9ee
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/video.mp4.duration
@@ -0,0 +1 @@
+9.000000
diff --git a/internal/mediahandler/testdata/fmp4/video.mp4.packets.csv b/internal/mediahandler/testdata/fmp4/video.mp4.packets.csv
new file mode 100644
index 000000000..5206cc1e0
--- /dev/null
+++ b/internal/mediahandler/testdata/fmp4/video.mp4.packets.csv
@@ -0,0 +1,693 @@
+0,0.000000,0.033333,2151,4387
+0,0.033333,0.033333,110,6538
+0,0.066667,0.033333,88,6648
+0,0.100000,0.033333,79,6736
+0,0.133333,0.033333,87,6815
+0,0.166667,0.033333,114,6902
+0,0.200000,0.033333,74,7016
+0,0.233333,0.033333,93,7090
+0,0.266667,0.033333,93,7183
+0,0.300000,0.033333,99,7276
+0,0.333333,0.033333,117,7375
+0,0.366667,0.033333,87,7492
+0,0.400000,0.033333,101,7579
+0,0.433333,0.033333,80,7680
+0,0.466667,0.033333,97,7760
+0,0.500000,0.033333,79,7857
+0,0.533333,0.033333,98,7936
+0,0.566667,0.033333,81,8034
+0,0.600000,0.033333,82,8115
+0,0.633333,0.033333,97,8197
+0,0.666667,0.033333,70,8294
+0,0.700000,0.033333,117,8364
+0,0.733333,0.033333,88,8481
+0,0.766667,0.033333,84,8569
+0,0.800000,0.033333,82,8653
+0,0.833333,0.033333,100,8735
+0,0.866667,0.033333,89,8835
+0,0.900000,0.033333,98,8924
+0,0.933333,0.033333,79,9022
+0,0.966667,0.033333,93,9101
+0,1.000000,0.033333,138,9194
+1,0.000000,N/A,284,20047
+0,1.033333,0.033333,114,9332
+0,1.066667,0.033333,106,9446
+1,0.066667,0.021333,378,20331
+1,0.088000,0.021333,289,20709
+0,1.100000,0.033333,80,9552
+1,0.109333,0.021333,358,20998
+1,0.130667,0.021333,323,21356
+0,1.133333,0.033333,104,9632
+1,0.152000,0.021333,335,21679
+0,1.166667,0.033333,90,9736
+1,0.173333,0.021333,381,22014
+1,0.194667,0.021333,319,22395
+0,1.200000,0.033333,121,9826
+1,0.216000,0.021333,331,22714
+0,1.233333,0.033333,90,9947
+1,0.237333,0.021333,318,23045
+1,0.258667,0.021333,353,23363
+0,1.266667,0.033333,90,10037
+1,0.280000,0.021333,352,23716
+0,1.300000,0.033333,90,10127
+1,0.301333,0.021333,349,24068
+1,0.322667,0.021333,368,24417
+0,1.333333,0.033333,109,10217
+1,0.344000,0.021333,319,24785
+1,0.365333,0.021333,337,25104
+0,1.366667,0.033333,89,10326
+1,0.386667,0.021333,339,25441
+0,1.400000,0.033333,97,10415
+1,0.408000,0.021333,353,25780
+1,0.429333,0.021333,326,26133
+0,1.433333,0.033333,92,10512
+1,0.450667,0.021333,341,26459
+0,1.466667,0.033333,101,10604
+1,0.472000,0.021333,350,26800
+1,0.493333,0.021333,354,27150
+0,1.500000,0.033333,98,10705
+1,0.514667,0.021333,329,27504
+0,1.533333,0.033333,103,10803
+1,0.536000,0.021333,326,27833
+1,0.557333,0.021333,350,28159
+0,1.566667,0.033333,112,10906
+1,0.578667,0.021333,374,28509
+0,1.600000,0.033333,89,11018
+1,0.600000,0.021333,305,28883
+1,0.621333,0.021333,359,29188
+0,1.633333,0.033333,134,11107
+1,0.642667,0.021333,352,29547
+1,0.664000,0.021333,348,29899
+0,1.666667,0.033333,99,11241
+1,0.685333,0.021333,327,30247
+0,1.700000,0.033333,104,11340
+1,0.706667,0.021333,351,30574
+1,0.728000,0.021333,318,30925
+0,1.733333,0.033333,94,11444
+1,0.749333,0.021333,346,31243
+0,1.766667,0.033333,126,11538
+1,0.770667,0.021333,375,31589
+1,0.792000,0.021333,333,31964
+0,1.800000,0.033333,114,11664
+1,0.813333,0.021333,359,32297
+0,1.833333,0.033333,116,11778
+1,0.834667,0.021333,332,32656
+1,0.856000,0.021333,352,32988
+0,1.866667,0.033333,88,11894
+1,0.877333,0.021333,327,33340
+1,0.898667,0.021333,328,33667
+0,1.900000,0.033333,115,11982
+1,0.920000,0.021333,348,33995
+0,1.933333,0.033333,118,12097
+1,0.941333,0.021333,351,34343
+1,0.962667,0.021333,326,34694
+0,1.966667,0.033333,124,12215
+1,0.984000,0.021333,359,35020
+0,2.000000,0.033333,1614,12339
+1,1.005333,0.021333,348,35379
+1,1.026667,0.021333,329,35727
+0,2.033333,0.033333,114,13953
+1,1.048000,0.021333,328,36056
+0,2.066667,0.033333,83,14067
+1,1.069333,0.021333,346,36384
+1,1.090667,0.021333,377,36730
+0,2.100000,0.033333,108,14150
+1,1.112000,0.021333,308,37107
+0,2.133333,0.033333,106,14258
+1,1.133333,0.021333,326,37415
+1,1.154667,0.021333,360,37741
+0,2.166667,0.033333,95,14364
+1,1.176000,0.021333,349,38101
+1,1.197333,0.021333,340,38450
+0,2.200000,0.033333,114,14459
+1,1.218667,0.021333,326,38790
+0,2.233333,0.033333,97,14573
+1,1.240000,0.021333,359,39116
+1,1.261333,0.021333,345,39475
+0,2.266667,0.033333,131,14670
+1,1.282667,0.021333,327,39820
+0,2.300000,0.033333,91,14801
+1,1.304000,0.021333,350,40147
+1,1.325333,0.021333,350,40497
+0,2.333333,0.033333,119,14892
+1,1.346667,0.021333,339,40847
+0,2.366667,0.033333,81,15011
+1,1.368000,0.021333,322,41186
+1,1.389333,0.021333,329,41508
+0,2.400000,0.033333,84,15092
+1,1.410667,0.021333,347,41837
+1,1.432000,0.021333,331,42184
+0,2.433333,0.033333,118,15176
+1,1.453333,0.021333,346,42515
+0,2.466667,0.033333,113,15294
+1,1.474667,0.021333,349,42861
+1,1.496000,0.021333,338,43210
+0,2.500000,0.033333,131,15407
+1,1.517333,0.021333,342,43548
+0,2.533333,0.033333,93,15538
+1,1.538667,0.021333,340,43890
+1,1.560000,0.021333,350,44230
+0,2.566667,0.033333,113,15631
+1,1.581333,0.021333,336,44580
+0,2.600000,0.033333,128,15744
+1,1.602667,0.021333,351,44916
+1,1.624000,0.021333,338,45267
+0,2.633333,0.033333,102,15872
+1,1.645333,0.021333,352,45605
+0,2.666667,0.033333,100,15974
+1,1.666667,0.021333,339,45957
+1,1.688000,0.021333,347,46296
+0,2.700000,0.033333,126,16074
+1,1.709333,0.021333,373,46643
+1,1.730667,0.021333,333,47016
+0,2.733333,0.033333,119,16200
+1,1.752000,0.021333,328,47349
+0,2.766667,0.033333,127,16319
+1,1.773333,0.021333,335,47677
+1,1.794667,0.021333,328,48012
+0,2.800000,0.033333,120,16446
+1,1.816000,0.021333,334,48340
+0,2.833333,0.033333,103,16566
+1,1.837333,0.021333,347,48674
+1,1.858667,0.021333,334,49021
+0,2.866667,0.033333,108,16669
+1,1.880000,0.021333,337,49355
+0,2.900000,0.033333,133,16777
+1,1.901333,0.021333,342,49692
+1,1.922667,0.021333,356,50034
+0,2.933333,0.033333,88,16910
+1,1.944000,0.021333,347,50390
+1,1.965333,0.021333,338,50737
+0,2.966667,0.033333,130,16998
+1,1.986667,0.021333,341,51075
+0,3.000000,0.033333,147,17128
+1,2.008000,0.021333,335,51416
+1,2.029333,0.021333,364,51751
+0,3.033333,0.033333,112,17275
+1,2.050667,0.021333,350,52115
+0,3.066667,0.033333,96,17387
+1,2.072000,0.021333,308,52465
+1,2.093333,0.021333,352,52773
+0,3.100000,0.033333,89,17483
+1,2.114667,0.021333,355,53125
+0,3.133333,0.033333,96,17572
+1,2.136000,0.021333,334,53480
+1,2.157333,0.021333,329,53814
+0,3.166667,0.033333,96,17668
+1,2.178667,0.021333,356,54143
+0,3.200000,0.033333,99,17764
+1,2.200000,0.021333,352,54499
+1,2.221333,0.021333,331,54851
+0,3.233333,0.033333,93,17863
+1,2.242667,0.021333,336,55182
+1,2.264000,0.021333,324,55518
+0,3.266667,0.033333,109,17956
+1,2.285333,0.021333,343,55842
+0,3.300000,0.033333,110,18065
+1,2.306667,0.021333,368,56185
+1,2.328000,0.021333,351,56553
+0,3.333333,0.033333,96,18175
+1,2.349333,0.021333,299,56904
+0,3.366667,0.033333,94,18271
+1,2.370667,0.021333,364,57203
+1,2.392000,0.021333,348,57567
+0,3.400000,0.033333,90,18365
+1,2.413333,0.021333,349,57915
+0,3.433333,0.033333,77,18455
+1,2.434667,0.021333,328,58264
+1,2.456000,0.021333,366,58592
+0,3.466667,0.033333,112,18532
+1,2.477333,0.021333,329,58958
+1,2.498667,0.021333,334,59287
+0,3.500000,0.033333,72,18644
+1,2.520000,0.021333,346,59621
+0,3.533333,0.033333,91,18716
+1,2.541333,0.021333,344,59967
+1,2.562667,0.021333,334,60311
+0,3.566667,0.033333,93,18807
+1,2.584000,0.021333,349,60645
+0,3.600000,0.033333,90,18900
+1,2.605333,0.021333,342,60994
+1,2.626667,0.021333,340,61336
+0,3.633333,0.033333,110,18990
+1,2.648000,0.021333,351,61676
+0,3.666667,0.033333,84,19100
+1,2.669333,0.021333,344,62027
+1,2.690667,0.021333,315,62371
+0,3.700000,0.033333,94,19184
+1,2.712000,0.021333,351,62686
+0,3.733333,0.033333,97,19278
+1,2.733333,0.021333,344,63037
+1,2.754667,0.021333,355,63381
+0,3.766667,0.033333,99,19375
+1,2.776000,0.021333,343,63736
+1,2.797333,0.021333,334,64079
+0,3.800000,0.033333,90,19474
+1,2.818667,0.021333,323,64413
+0,3.833333,0.033333,85,19564
+1,2.840000,0.021333,351,64736
+1,2.861333,0.021333,352,65087
+0,3.866667,0.033333,95,19649
+1,2.882667,0.021333,333,65439
+0,3.900000,0.033333,107,19744
+1,2.904000,0.021333,344,65772
+1,2.925333,0.021333,346,66116
+0,3.933333,0.033333,95,19851
+1,2.946667,0.021333,332,66462
+0,3.966667,0.033333,101,19946
+1,2.968000,0.021333,329,66794
+1,2.989333,0.021333,355,67123
+1,3.010667,0.021333,342,67478
+1,3.032000,0.021333,372,67820
+1,3.053333,0.021333,332,68192
+1,3.074667,0.021333,319,68524
+1,3.096000,0.021333,347,68843
+1,3.117333,0.021333,345,69190
+1,3.138667,0.021333,341,69535
+1,3.160000,0.021333,341,69876
+1,3.181333,0.021333,341,70217
+1,3.202667,0.021333,345,70558
+1,3.224000,0.021333,347,70903
+1,3.245333,0.021333,339,71250
+1,3.266667,0.021333,348,71589
+1,3.288000,0.021333,316,71937
+1,3.309333,0.021333,352,72253
+1,3.330667,0.021333,330,72605
+1,3.352000,0.021333,360,72935
+1,3.373333,0.021333,345,73295
+1,3.394667,0.021333,351,73640
+1,3.416000,0.021333,323,73991
+1,3.437333,0.021333,337,74314
+1,3.458667,0.021333,355,74651
+1,3.480000,0.021333,345,75006
+1,3.501333,0.021333,349,75351
+1,3.522667,0.021333,324,75700
+1,3.544000,0.021333,330,76024
+1,3.565333,0.021333,347,76354
+1,3.586667,0.021333,359,76701
+1,3.608000,0.021333,338,77060
+1,3.629333,0.021333,333,77398
+1,3.650667,0.021333,353,77731
+1,3.672000,0.021333,324,78084
+1,3.693333,0.021333,363,78408
+1,3.714667,0.021333,333,78771
+1,3.736000,0.021333,353,79104
+1,3.757333,0.021333,339,79457
+1,3.778667,0.021333,354,79796
+1,3.800000,0.021333,322,80150
+1,3.821333,0.021333,318,80472
+1,3.842667,0.021333,378,80790
+1,3.864000,0.021333,330,81168
+1,3.885333,0.021333,342,81498
+1,3.906667,0.021333,346,81840
+1,3.928000,0.021333,340,82186
+1,3.949333,0.021333,346,82526
+1,3.970667,0.021333,328,82872
+1,3.992000,0.021333,353,83200
+0,4.000000,0.033333,1602,85925
+0,4.033333,0.033333,104,87527
+0,4.066667,0.033333,86,87631
+0,4.100000,0.033333,104,87717
+0,4.133333,0.033333,106,87821
+0,4.166667,0.033333,98,87927
+0,4.200000,0.033333,96,88025
+0,4.233333,0.033333,97,88121
+0,4.266667,0.033333,98,88218
+0,4.300000,0.033333,100,88316
+0,4.333333,0.033333,121,88416
+0,4.366667,0.033333,79,88537
+0,4.400000,0.033333,113,88616
+0,4.433333,0.033333,99,88729
+0,4.466667,0.033333,94,88828
+0,4.500000,0.033333,102,88922
+0,4.533333,0.033333,79,89024
+0,4.566667,0.033333,94,89103
+0,4.600000,0.033333,88,89197
+0,4.633333,0.033333,114,89285
+0,4.666667,0.033333,97,89399
+0,4.700000,0.033333,95,89496
+0,4.733333,0.033333,86,89591
+0,4.766667,0.033333,105,89677
+0,4.800000,0.033333,96,89782
+0,4.833333,0.033333,97,89878
+0,4.866667,0.033333,88,89975
+0,4.900000,0.033333,113,90063
+0,4.933333,0.033333,110,90176
+0,4.966667,0.033333,108,90286
+0,5.000000,0.033333,146,90394
+1,4.013333,0.021333,348,101237
+0,5.033333,0.033333,120,90540
+1,4.034667,0.021333,323,101585
+1,4.056000,0.021333,345,101908
+0,5.066667,0.033333,101,90660
+1,4.077333,0.021333,338,102253
+1,4.098667,0.021333,349,102591
+0,5.100000,0.033333,121,90761
+1,4.120000,0.021333,355,102940
+0,5.133333,0.033333,96,90882
+1,4.141333,0.021333,338,103295
+1,4.162667,0.021333,346,103633
+0,5.166667,0.033333,108,90978
+1,4.184000,0.021333,337,103979
+0,5.200000,0.033333,106,91086
+1,4.205333,0.021333,327,104316
+1,4.226667,0.021333,352,104643
+0,5.233333,0.033333,103,91192
+1,4.248000,0.021333,348,104995
+0,5.266667,0.033333,118,91295
+1,4.269333,0.021333,340,105343
+1,4.290667,0.021333,344,105683
+0,5.300000,0.033333,89,91413
+1,4.312000,0.021333,323,106027
+0,5.333333,0.033333,110,91502
+1,4.333333,0.021333,344,106350
+1,4.354667,0.021333,354,106694
+0,5.366667,0.033333,92,91612
+1,4.376000,0.021333,347,107048
+1,4.397333,0.021333,323,107395
+0,5.400000,0.033333,108,91704
+1,4.418667,0.021333,347,107718
+0,5.433333,0.033333,109,91812
+1,4.440000,0.021333,344,108065
+1,4.461333,0.021333,344,108409
+0,5.466667,0.033333,126,91921
+1,4.482667,0.021333,346,108753
+0,5.500000,0.033333,126,92047
+1,4.504000,0.021333,335,109099
+1,4.525333,0.021333,331,109434
+0,5.533333,0.033333,114,92173
+1,4.546667,0.021333,358,109765
+0,5.566667,0.033333,117,92287
+1,4.568000,0.021333,334,110123
+1,4.589333,0.021333,345,110457
+0,5.600000,0.033333,130,92404
+1,4.610667,0.021333,341,110802
+1,4.632000,0.021333,346,111143
+0,5.633333,0.033333,116,92534
+1,4.653333,0.021333,329,111489
+0,5.666667,0.033333,82,92650
+1,4.674667,0.021333,340,111818
+1,4.696000,0.021333,352,112158
+0,5.700000,0.033333,150,92732
+1,4.717333,0.021333,342,112510
+0,5.733333,0.033333,139,92882
+1,4.738667,0.021333,341,112852
+1,4.760000,0.021333,340,113193
+0,5.766667,0.033333,143,93021
+1,4.781333,0.021333,340,113533
+0,5.800000,0.033333,111,93164
+1,4.802667,0.021333,344,113873
+1,4.824000,0.021333,349,114217
+0,5.833333,0.033333,110,93275
+1,4.845333,0.021333,333,114566
+0,5.866667,0.033333,126,93385
+1,4.866667,0.021333,345,114899
+1,4.888000,0.021333,346,115244
+0,5.900000,0.033333,121,93511
+1,4.909333,0.021333,340,115590
+1,4.930667,0.021333,339,115930
+0,5.933333,0.033333,106,93632
+1,4.952000,0.021333,344,116269
+0,5.966667,0.033333,98,93738
+1,4.973333,0.021333,345,116613
+1,4.994667,0.021333,334,116958
+0,6.000000,0.033333,1591,93836
+1,5.016000,0.021333,346,117292
+0,6.033333,0.033333,121,95427
+1,5.037333,0.021333,332,117638
+1,5.058667,0.021333,347,117970
+0,6.066667,0.033333,100,95548
+1,5.080000,0.021333,336,118317
+0,6.100000,0.033333,78,95648
+1,5.101333,0.021333,344,118653
+1,5.122667,0.021333,334,118997
+0,6.133333,0.033333,90,95726
+1,5.144000,0.021333,345,119331
+1,5.165333,0.021333,335,119676
+0,6.166667,0.033333,88,95816
+1,5.186667,0.021333,348,120011
+0,6.200000,0.033333,91,95904
+1,5.208000,0.021333,337,120359
+1,5.229333,0.021333,345,120696
+0,6.233333,0.033333,87,95995
+1,5.250667,0.021333,344,121041
+0,6.266667,0.033333,107,96082
+1,5.272000,0.021333,334,121385
+1,5.293333,0.021333,336,121719
+0,6.300000,0.033333,87,96189
+1,5.314667,0.021333,351,122055
+0,6.333333,0.033333,85,96276
+1,5.336000,0.021333,350,122406
+1,5.357333,0.021333,344,122756
+0,6.366667,0.033333,78,96361
+1,5.378667,0.021333,341,123100
+0,6.400000,0.033333,123,96439
+1,5.400000,0.021333,333,123441
+1,5.421333,0.021333,345,123774
+0,6.433333,0.033333,95,96562
+1,5.442667,0.021333,346,124119
+1,5.464000,0.021333,339,124465
+0,6.466667,0.033333,81,96657
+1,5.485333,0.021333,343,124804
+0,6.500000,0.033333,75,96738
+1,5.506667,0.021333,356,125147
+1,5.528000,0.021333,337,125503
+0,6.533333,0.033333,94,96813
+1,5.549333,0.021333,317,125840
+0,6.566667,0.033333,99,96907
+1,5.570667,0.021333,360,126157
+1,5.592000,0.021333,341,126517
+0,6.600000,0.033333,81,97006
+1,5.613333,0.021333,339,126858
+0,6.633333,0.033333,99,97087
+1,5.634667,0.021333,347,127197
+1,5.656000,0.021333,341,127544
+0,6.666667,0.033333,75,97186
+1,5.677333,0.021333,337,127885
+1,5.698667,0.021333,336,128222
+0,6.700000,0.033333,84,97261
+1,5.720000,0.021333,337,128558
+0,6.733333,0.033333,90,97345
+1,5.741333,0.021333,344,128895
+1,5.762667,0.021333,346,129239
+0,6.766667,0.033333,88,97435
+1,5.784000,0.021333,342,129585
+0,6.800000,0.033333,89,97523
+1,5.805333,0.021333,342,129927
+1,5.826667,0.021333,341,130269
+0,6.833333,0.033333,93,97612
+1,5.848000,0.021333,339,130610
+0,6.866667,0.033333,88,97705
+1,5.869333,0.021333,350,130949
+1,5.890667,0.021333,334,131299
+0,6.900000,0.033333,88,97793
+1,5.912000,0.021333,333,131633
+0,6.933333,0.033333,96,97881
+1,5.933333,0.021333,353,131966
+1,5.954667,0.021333,342,132319
+0,6.966667,0.033333,103,97977
+1,5.976000,0.021333,341,132661
+1,5.997333,0.021333,337,133002
+0,7.000000,0.033333,150,98080
+1,6.018667,0.021333,345,133339
+0,7.033333,0.033333,115,98230
+1,6.040000,0.021333,329,133684
+1,6.061333,0.021333,350,134013
+0,7.066667,0.033333,108,98345
+1,6.082667,0.021333,340,134363
+0,7.100000,0.033333,86,98453
+1,6.104000,0.021333,352,134703
+1,6.125333,0.021333,335,135055
+0,7.133333,0.033333,125,98539
+1,6.146667,0.021333,351,135390
+0,7.166667,0.033333,81,98664
+1,6.168000,0.021333,345,135741
+1,6.189333,0.021333,337,136086
+0,7.200000,0.033333,140,98745
+1,6.210667,0.021333,344,136423
+1,6.232000,0.021333,341,136767
+0,7.233333,0.033333,81,98885
+1,6.253333,0.021333,339,137108
+0,7.266667,0.033333,95,98966
+1,6.274667,0.021333,335,137447
+1,6.296000,0.021333,332,137782
+0,7.300000,0.033333,89,99061
+1,6.317333,0.021333,358,138114
+0,7.333333,0.033333,100,99150
+1,6.338667,0.021333,335,138472
+1,6.360000,0.021333,344,138807
+0,7.366667,0.033333,109,99250
+1,6.381333,0.021333,335,139151
+0,7.400000,0.033333,87,99359
+1,6.402667,0.021333,345,139486
+1,6.424000,0.021333,344,139831
+0,7.433333,0.033333,102,99446
+1,6.445333,0.021333,335,140175
+0,7.466667,0.033333,92,99548
+1,6.466667,0.021333,351,140510
+1,6.488000,0.021333,329,140861
+0,7.500000,0.033333,93,99640
+1,6.509333,0.021333,348,141190
+1,6.530667,0.021333,335,141538
+0,7.533333,0.033333,97,99733
+1,6.552000,0.021333,344,141873
+0,7.566667,0.033333,110,99830
+1,6.573333,0.021333,352,142217
+1,6.594667,0.021333,340,142569
+0,7.600000,0.033333,117,99940
+1,6.616000,0.021333,343,142909
+0,7.633333,0.033333,112,100057
+1,6.637333,0.021333,329,143252
+1,6.658667,0.021333,346,143581
+0,7.666667,0.033333,90,100169
+1,6.680000,0.021333,348,143927
+0,7.700000,0.033333,109,100259
+1,6.701333,0.021333,342,144275
+1,6.722667,0.021333,338,144617
+0,7.733333,0.033333,104,100368
+1,6.744000,0.021333,337,144955
+1,6.765333,0.021333,336,145292
+0,7.766667,0.033333,103,100472
+1,6.786667,0.021333,343,145628
+0,7.800000,0.033333,110,100575
+1,6.808000,0.021333,348,145971
+1,6.829333,0.021333,338,146319
+0,7.833333,0.033333,102,100685
+1,6.850667,0.021333,349,146657
+0,7.866667,0.033333,120,100787
+1,6.872000,0.021333,338,147006
+1,6.893333,0.021333,350,147344
+0,7.900000,0.033333,106,100907
+1,6.914667,0.021333,329,147694
+0,7.933333,0.033333,95,101013
+1,6.936000,0.021333,354,148023
+1,6.957333,0.021333,324,148377
+0,7.966667,0.033333,129,101108
+1,6.978667,0.021333,348,148701
+1,7.000000,0.021333,340,149049
+1,7.021333,0.021333,336,149389
+1,7.042667,0.021333,339,149725
+1,7.064000,0.021333,353,150064
+1,7.085333,0.021333,333,150417
+1,7.106667,0.021333,356,150750
+1,7.128000,0.021333,333,151106
+1,7.149333,0.021333,349,151439
+1,7.170667,0.021333,336,151788
+1,7.192000,0.021333,350,152124
+1,7.213333,0.021333,326,152474
+1,7.234667,0.021333,355,152800
+1,7.256000,0.021333,331,153155
+1,7.277333,0.021333,359,153486
+1,7.298667,0.021333,322,153845
+1,7.320000,0.021333,351,154167
+1,7.341333,0.021333,332,154518
+1,7.362667,0.021333,358,154850
+1,7.384000,0.021333,317,155208
+1,7.405333,0.021333,368,155525
+1,7.426667,0.021333,313,155893
+1,7.448000,0.021333,369,156206
+1,7.469333,0.021333,328,156575
+1,7.490667,0.021333,352,156903
+1,7.512000,0.021333,329,157255
+1,7.533333,0.021333,352,157584
+1,7.554667,0.021333,333,157936
+1,7.576000,0.021333,337,158269
+1,7.597333,0.021333,348,158606
+1,7.618667,0.021333,329,158954
+1,7.640000,0.021333,359,159283
+1,7.661333,0.021333,322,159642
+1,7.682667,0.021333,357,159964
+1,7.704000,0.021333,337,160321
+1,7.725333,0.021333,336,160658
+1,7.746667,0.021333,345,160994
+1,7.768000,0.021333,336,161339
+1,7.789333,0.021333,357,161675
+1,7.810667,0.021333,332,162032
+1,7.832000,0.021333,359,162364
+1,7.853333,0.021333,325,162723
+1,7.874667,0.021333,364,163048
+1,7.896000,0.021333,316,163412
+1,7.917333,0.021333,365,163728
+1,7.938667,0.021333,309,164093
+1,7.960000,0.021333,385,164402
+1,7.981333,0.021333,298,164787
+0,8.000000,0.033333,1605,165913
+0,8.033333,0.033333,127,167518
+0,8.066667,0.033333,88,167645
+0,8.100000,0.033333,107,167733
+0,8.133333,0.033333,99,167840
+0,8.166667,0.033333,99,167939
+0,8.200000,0.033333,125,168038
+0,8.233333,0.033333,92,168163
+0,8.266667,0.033333,113,168255
+0,8.300000,0.033333,91,168368
+0,8.333333,0.033333,109,168459
+0,8.366667,0.033333,84,168568
+0,8.400000,0.033333,116,168652
+0,8.433333,0.033333,89,168768
+0,8.466667,0.033333,107,168857
+0,8.500000,0.033333,124,168964
+0,8.533333,0.033333,117,169088
+0,8.566667,0.033333,120,169205
+0,8.600000,0.033333,89,169325
+0,8.633333,0.033333,116,169414
+0,8.666667,0.033333,110,169530
+0,8.700000,0.033333,122,169640
+0,8.733333,0.033333,109,169762
+0,8.766667,0.033333,99,169871
+0,8.800000,0.033333,89,169970
+0,8.833333,0.033333,114,170059
+0,8.866667,0.033333,110,170173
+0,8.900000,0.033333,80,170283
+0,8.933333,0.033333,79,170363
+0,8.966667,0.033333,52,170442
+1,8.002667,0.021333,379,170494
+1,8.024000,0.021333,314,170873
+1,8.045333,0.021333,353,171187
+1,8.066667,0.021333,341,171540
+1,8.088000,0.021333,327,171881
+1,8.109333,0.021333,350,172208
+1,8.130667,0.021333,334,172558
+1,8.152000,0.021333,350,172892
+1,8.173333,0.021333,329,173242
+1,8.194667,0.021333,348,173571
+1,8.216000,0.021333,335,173919
+1,8.237333,0.021333,343,174254
+1,8.258667,0.021333,348,174597
+1,8.280000,0.021333,336,174945
+1,8.301333,0.021333,352,175281
+1,8.322667,0.021333,340,175633
+1,8.344000,0.021333,338,175973
+1,8.365333,0.021333,342,176311
+1,8.386667,0.021333,335,176653
+1,8.408000,0.021333,337,176988
+1,8.429333,0.021333,347,177325
+1,8.450667,0.021333,348,177672
+1,8.472000,0.021333,330,178020
+1,8.493333,0.021333,354,178350
+1,8.514667,0.021333,322,178704
+1,8.536000,0.021333,365,179026
+1,8.557333,0.021333,329,179391
+1,8.578667,0.021333,343,179720
+1,8.600000,0.021333,336,180063
+1,8.621333,0.021333,339,180399
+1,8.642667,0.021333,345,180738
+1,8.664000,0.021333,336,181083
+1,8.685333,0.021333,350,181419
+1,8.706667,0.021333,326,181769
+1,8.728000,0.021333,366,182095
+1,8.749333,0.021333,325,182461
+1,8.770667,0.021333,359,182786
+1,8.792000,0.021333,314,183145
+1,8.813333,0.021333,366,183459
+1,8.834667,0.021333,318,183825
+1,8.856000,0.021333,365,184143
+1,8.877333,0.021333,321,184508
+1,8.898667,0.021333,356,184829
+1,8.920000,0.021333,339,185185
+1,8.941333,0.021333,332,185524
+1,8.962667,0.021333,352,185856
+1,8.984000,0.021333,317,186208
+1,9.005333,0.021333,375,186525
+1,9.026667,0.021333,334,186900
+1,9.048000,0.021333,344,187234