carlos / platform Public

media: pad video to its audio, count every track, apply the SAR

Plan 3 Task 4 fix round 1. With audio, the video's last frame is
repeated and cut at the probed duration (tpad, trim) and the audio
padded with silence to it (apad whole_dur), so a short video under
long audio no longer ends the timeline early, and a longer video is not
cut. -shortest is not used: on Debian's 7.1.5 it cut a longer video to
its audio, and with apad ran it to 5 s, 15 s or 50 s as unrelated
options changed.

readFMP4 still cuts at the timeline's tfdt, but the last fragment and
the total run to the latest end of any traf, each in its own timescale.

The probe reads the sample aspect ratio; the video and poster are sized
from the display size (outputSize) and get setsar=1. Fixtures, args.txt
and the probe fixtures are regenerated with Debian's ffmpeg 7.1.5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7484a986e7c4b6489a6d600762b506516014036d parent 8fb8fa9
20 files changed, +412 −145
  • internal/mediahandler/ffmpeg.go +63 −11
  • internal/mediahandler/ffmpeg_test.go +72 −12
  • internal/mediahandler/fmp4.go +74 −59
  • internal/mediahandler/fmp4_synth_test.go +42 −9
  • internal/mediahandler/fmp4_test.go +16 −14
  • internal/mediahandler/probe.go +31 −2
  • internal/mediahandler/probe_test.go +8 −7
  • internal/mediahandler/realencode_test.go +86 −24
  • internal/mediahandler/testdata/fmp4/args.txt +2 −2
  • internal/mediahandler/testdata/fmp4/provenance.txt +8 −4
  • internal/mediahandler/testdata/fmp4/video.mp4.duration +1 −1
  • internal/mediahandler/testdata/probe/av-no-duration.json +1 −0
  • internal/mediahandler/testdata/probe/h264-120fps.json +1 −0
  • internal/mediahandler/testdata/probe/h264-4k60.json +1 −0
  • internal/mediahandler/testdata/probe/h264-subtitle.json +1 −0
  • internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json +1 −0
  • internal/mediahandler/testdata/probe/m4a-cover-art.json +1 −0
  • internal/mediahandler/testdata/probe/mka-cover-art.json +1 −0
  • internal/mediahandler/testdata/probe/mp3-cover-art.json +1 −0
  • internal/mediahandler/testdata/probe/vfr-screen-recording.json +1 −0
diff --git a/internal/mediahandler/ffmpeg.go b/internal/mediahandler/ffmpeg.go
index 13a9ea5d0..bef02baa9 100644
--- a/internal/mediahandler/ffmpeg.go
+++ b/internal/mediahandler/ffmpeg.go
@@ -24,7 +24,14 @@ const (
// 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
+// accepts. With no edit list in a fragmented file, the muxer delays
+// every track by the video's B-frame decoder delay (two frames with
+// these x264 settings), so the file runs that much past its content;
+// negative_cts_offsets would avoid it, but on Debian's 7.1.5 it does so
+// only for some inputs (a 10 fps source, or 1 s of video under 9 s of
+// audio, still starts the video two frames late) and then shifts the
+// video alone, putting the audio two frames ahead of it (plan 3 Task 4
+// fix 1). 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.
@@ -34,13 +41,19 @@ const (
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.
+// sdrFilter scales to the output size with square pixels; hdrFilter
+// does the same, then tone-maps PQ or HLG to BT.709 SDR (spike: the
+// chain and operator plan 1 confirms). %d:%d is the output size.
+// padFilter ends the video encode's chain when the job has audio: the
+// last frame is repeated, then the video cut at %s, the probed
+// duration; padAudio pads the audio with silence to it, and never cuts
+// it. Both tracks then last as long as the source (fix 1).
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," +
+ sdrFilter = "scale=%d:%d:flags=bicubic,setsar=1,format=yuv420p"
+ hdrFilter = "scale=%d:%d:flags=bicubic,setsar=1,zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709," +
"tonemap=tonemap=hable:desat=0,zscale=t=bt709:m=bt709:r=tv,format=yuv420p"
+ padFilter = ",tpad=stop_mode=clone:stop=-1,trim=duration=%s"
+ padAudio = "apad=whole_dur=%s"
)
// The outputs' names, in media.OutputNames order.
@@ -67,10 +80,27 @@ 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.
+// displayWidth is the source's width with its sample aspect ratio
+// applied, rounded to the nearest pixel: what a player shows, which
+// ffmpeg's convention keeps the height of.
+func displayWidth(f probeFacts) int {
+ if f.SARNum <= 0 || f.SARDen <= 0 || f.SARNum == f.SARDen {
+ return f.Width
+ }
+ return int((int64(f.Width)*int64(f.SARNum) + int64(f.SARDen)/2) / int64(f.SARDen))
+}
+
+// outputSize is the video's and the poster's size: targetSize of the
+// source's display size (preflight F16 fills OutputFact from it).
+func outputSize(f probeFacts) (w, h int) {
+ return targetSize(displayWidth(f), f.Height, f.Rotation)
+}
+
+// videoFilter is the -vf of the poster, and of the video encode without
+// the pad: the scale to outputSize with square pixels, with the tone
+// map for an HDR source.
func videoFilter(f probeFacts) string {
- w, h := targetSize(f.Width, f.Height, f.Rotation)
+ w, h := outputSize(f)
if f.HDR {
return fmt.Sprintf(hdrFilter, w, h)
}
@@ -82,6 +112,22 @@ func videoFilter(f probeFacts) string {
// 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.
+//
+// With audio, both streams last exactly the probed duration, which is
+// the longer of the source's streams (its header's, or the longest
+// taken stream's; plan 3 Task 4 fix 1): the video's last frame is
+// repeated (tpad) and cut there (trim), and the audio is padded with
+// silence to it (apad whole_dur), never cut. Audio longer than that
+// (a Matroska with no header duration, where the probe timed the
+// video's packets) is kept whole, past the video's end, and readFMP4
+// counts it; an atrim would drop it. So a short video under long audio
+// does not end the video track early, which would leave the rest of
+// the audio in one last fragment past the playlist's timeline, and a
+// video longer than its audio is not cut to the audio. -shortest is not
+// used: on Debian's 7.1.5, with an endless tpad, it cut a 6 s video
+// with 2 s of audio at 5 s, or ran it to 15 s or 50 s, as unrelated
+// options changed, and let the audio run 0.2 s past the video. -t
+// caps everything at the grant.
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))
@@ -89,12 +135,18 @@ func videoArgs(cfg Config, f probeFacts, p media.Payload, demuxer string) []stri
args = append(args, "-map", "0:"+strconv.Itoa(f.AudioIndex))
}
args = append(args, stripArgs(p)...)
- args = append(args, "-vf", videoFilter(f),
+ vf := videoFilter(f)
+ length := msSeconds(f.DurationMS)
+ if f.AudioIndex >= 0 {
+ vf += fmt.Sprintf(padFilter, length)
+ }
+ args = append(args, "-vf", vf,
"-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")
+ args = append(args, "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-ar", "48000",
+ "-af", fmt.Sprintf(padAudio, length))
} else {
args = append(args, "-an")
}
diff --git a/internal/mediahandler/ffmpeg_test.go b/internal/mediahandler/ffmpeg_test.go
index 6cd6ecba2..ede813de6 100644
--- a/internal/mediahandler/ffmpeg_test.go
+++ b/internal/mediahandler/ffmpeg_test.go
@@ -2,6 +2,7 @@ package mediahandler
import (
"bytes"
+ "fmt"
"math"
"os"
"slices"
@@ -98,7 +99,9 @@ func inputPrefix(demuxer string) []string {
}
// TestVideoArgsSDRLandscape: the exact arguments for a 1080p H.264 with
-// audio granted 61.5 s.
+// audio, 60 s long, granted 61.5 s: the video padded with its last
+// frame and cut at the probed 60 s, the audio padded with silence to
+// it (fix 1).
func TestVideoArgsSDRLandscape(t *testing.T) {
cfg := Config{Scratch: "/scratch"}
f := goodVideo() // 1920x1080 h264, audio at 1
@@ -106,11 +109,11 @@ func TestVideoArgsSDRLandscape(t *testing.T) {
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",
+ "-vf", "scale=1280:720:flags=bicubic,setsar=1,format=yuv420p,tpad=stop_mode=clone:stop=-1,trim=duration=60.000",
"-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",
+ "-c:a", "aac", "-b:a", "128k", "-ac", "2", "-ar", "48000", "-af", "apad=whole_dur=60.000",
"-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) {
@@ -128,7 +131,7 @@ func TestVideoArgsSDRLandscape(t *testing.T) {
// 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," +
+ hdr := "scale=720:1280:flags=bicubic,setsar=1,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)
@@ -138,19 +141,25 @@ func TestVideoArgsPortraitHDR(t *testing.T) {
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 f.AudioIndex < 0 {
+ t.Fatalf("%s: the fixture has no audio", name)
+ }
+ for what, c := range map[string]struct {
+ args []string
+ want string
+ }{
+ "video": {videoArgs(cfg, f, videoPayload(60000), "mov"), hdr + ",tpad=stop_mode=clone:stop=-1,trim=duration=" + msSeconds(f.DurationMS)},
+ "poster": {posterArgs(cfg, f, videoPayload(60000), "mov"), hdr},
} {
- if vf := argAfter(args, "-vf"); vf != hdr {
- t.Errorf("%s %s: -vf %q, want %q", name, what, vf, hdr)
+ if vf := argAfter(c.args, "-vf"); vf != c.want {
+ t.Errorf("%s %s: -vf %q, want %q", name, what, vf, c.want)
}
}
}
// 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" {
+ if vf := argAfter(posterArgs(cfg, f, videoPayload(60000), "mov"), "-vf"); vf != "scale=720:1280:flags=bicubic,setsar=1,format=yuv420p" {
t.Errorf("SDR portrait: -vf %q", vf)
}
}
@@ -178,9 +187,13 @@ func TestVideoWithoutAudio(t *testing.T) {
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") {
+ if !slices.Contains(args, "-an") || slices.Contains(args, "-c:a") || slices.Contains(args, "-af") || slices.Contains(args, "-shortest") {
t.Errorf("audio options: %q", args)
}
+ // Nothing to cover: the video is not padded.
+ if vf := argAfter(args, "-vf"); vf != "scale=1280:720:flags=bicubic,setsar=1,format=yuv420p" {
+ t.Errorf("-vf %q", vf)
+ }
b := readFixture(t, "video-noaudio.mp4")
initLen, frags, durationMS, err := readFMP4(bytes.NewReader(b), int64(len(b)))
if err != nil {
@@ -224,7 +237,7 @@ func TestPosterArgs(t *testing.T) {
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",
+ "-vf", "scale=1280:720:flags=bicubic,setsar=1,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)
@@ -464,6 +477,53 @@ func TestPackageOutput(t *testing.T) {
}
}
+// TestOutputSizeAppliesSAR (fix 1): the output is sized from the
+// display size, the sample aspect ratio applied to the width, then
+// rotated; the filter scales to it with square pixels.
+func TestOutputSizeAppliesSAR(t *testing.T) {
+ for _, c := range []struct {
+ w, h, num, den, rot int
+ ow, oh int
+ }{
+ {720, 480, 0, 0, 0, 720, 480}, // none: square
+ {720, 480, 1, 1, 0, 720, 480}, // square
+ {720, 480, 4, 3, 0, 960, 480}, // anamorphic, inside the box
+ {720, 576, 64, 45, 0, 1024, 576}, // PAL 16:9
+ {1440, 1080, 4, 3, 0, 1280, 720}, // HDV: 1920x1080 shown
+ {720, 480, 4, 3, -90, 480, 960}, // then rotated
+ {720, 480, 8, 9, 0, 640, 480}, // narrow pixels
+ {1920, 1080, 65536, 1, 0, 1280, 2}, // the largest ratio taken
+ } {
+ f := probeFacts{Width: c.w, Height: c.h, SARNum: c.num, SARDen: c.den, Rotation: c.rot}
+ if ow, oh := outputSize(f); ow != c.ow || oh != c.oh {
+ t.Errorf("%dx%d SAR %d:%d rotation %d: %dx%d, want %dx%d", c.w, c.h, c.num, c.den, c.rot, ow, oh, c.ow, c.oh)
+ }
+ want := fmt.Sprintf("scale=%d:%d:flags=bicubic,setsar=1,format=yuv420p", c.ow, c.oh)
+ if vf := videoFilter(f); vf != want {
+ t.Errorf("%dx%d SAR %d:%d: %q, want %q", c.w, c.h, c.num, c.den, vf, want)
+ }
+ }
+}
+
+// TestParseSAR: a ratio of positive terms up to 2^16; none, zero or
+// larger terms are square; anything else is an error.
+func TestParseSAR(t *testing.T) {
+ for _, c := range []struct {
+ s string
+ num, den int
+ err bool
+ }{
+ {"", 0, 0, false}, {"N/A", 0, 0, false}, {"0:1", 0, 0, false}, {"1:0", 0, 0, false},
+ {"1:1", 1, 1, false}, {"4:3", 4, 3, false}, {"65536:1", 65536, 1, false}, {"65537:1", 0, 0, false},
+ {"1:65537", 0, 0, false}, {"4/3", 0, 0, true}, {"-4:3", 0, 0, true}, {"a:b", 0, 0, true},
+ } {
+ num, den, err := parseSAR(c.s)
+ if num != c.num || den != c.den || (err != nil) != c.err {
+ t.Errorf("%q: %d:%d %v", c.s, num, den, err)
+ }
+ }
+}
+
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
func atoi(t *testing.T, s string) int64 {
diff --git a/internal/mediahandler/fmp4.go b/internal/mediahandler/fmp4.go
index 9e7e2fbeb..8c842c03d 100644
--- a/internal/mediahandler/fmp4.go
+++ b/internal/mediahandler/fmp4.go
@@ -36,9 +36,14 @@ var errNoFragments = errors.New("no fragment")
// 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
+// timescale: fragments are cut at its tfdt, so each fragment's
+// duration but the last is the next fragment's tfdt less its own,
+// strictly increasing. The file ends at the latest end of any traf (its
+// tfdt plus its trun sample durations, in its own track's timescale,
+// to the microsecond), so a track that outlasts the timeline's (audio
+// past the video) is counted: the last fragment runs from its timeline
+// tfdt to that end, and the duration from the first fragment's
+// timeline tfdt to it (plan 3 Task 4 fix 1). 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
@@ -67,7 +72,7 @@ func readFMP4(r io.ReaderAt, size int64) (initLen int64, frags []fragment, durat
}
initLen = moov.end()
var starts []uint64 // each fragment's tfdt on the timeline
- var lastDur uint64 // the last fragment's trun durations
+ var endUS int64 // the latest end of any traf, in microseconds
for off := initLen; off < size; {
if len(frags) == maxFragments {
return 0, nil, 0, fmt.Errorf("over %d fragments", maxFragments)
@@ -84,54 +89,51 @@ func readFMP4(r io.ReaderAt, size int64) (initLen int64, frags []fragment, durat
if err != nil {
return 0, nil, 0, err
}
- start, dur, err := parseMoof(body, moof, mdat, tl)
+ start, end, 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
+ starts, endUS = append(starts, start), max(endUS, end)
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 {
+ // The timeline's starts are under the ends (ticksToMicros bounds
+ // both), so neither conversion fails here.
+ firstUS, _ := ticksToMicros(starts[0], tl.timescale, false)
+ lastUS, _ := ticksToMicros(starts[len(starts)-1], tl.timescale, false)
+ if endUS <= lastUS {
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
+ for i := range frags[:len(frags)-1] {
+ frags[i].DurationS = float64(starts[i+1]-starts[i]) / ts
}
- return initLen, frags, durationMS, nil
+ frags[len(frags)-1].DurationS = float64(endUS-lastUS) / 1e6
+ return initLen, frags, (endUS - firstUS + 999) / 1000, nil
}
-// ticksToMS is ticks/timescale seconds in milliseconds, rounded up; an
-// error past maxDurationMS.
-func ticksToMS(ticks uint64, timescale uint32) (int64, error) {
+// ticksToMicros is ticks/timescale seconds in microseconds, rounded up
+// (or down), in 128-bit arithmetic; an error past maxDurationMS.
+func ticksToMicros(ticks uint64, timescale uint32, up bool) (int64, error) {
ts := uint64(timescale)
- secs, rem := ticks/ts, ticks%ts
- if secs > uint64(maxDurationMS/1000) {
+ hi, lo := bits.Mul64(ticks, 1_000_000)
+ if hi >= ts {
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
+ q, r := bits.Div64(hi, lo, ts)
+ if up && r > 0 {
+ q++
+ }
+ if q > uint64(maxDurationMS)*1000 {
+ return 0, errors.New("the duration is implausible")
+ }
+ return int64(q), nil
}
// fileBox is one top-level box: its offset, header length and size.
@@ -227,11 +229,12 @@ func children(b []byte) ([]child, error) {
}
// timeline is what readFMP4 needs from the moov: the chosen track, its
-// timescale, and each track's trex defaults.
+// timescale, every track's timescale, and each track's trex defaults.
type timeline struct {
- track uint32
- timescale uint32
- trex map[uint32]trexDefaults
+ track uint32
+ timescale uint32
+ timescales map[uint32]uint32
+ trex map[uint32]trexDefaults
}
type trexDefaults struct{ duration, size uint32 }
@@ -249,7 +252,7 @@ func parseMoov(b []byte) (timeline, error) {
if err != nil {
return timeline{}, fmt.Errorf("moov: %w", err)
}
- tl := timeline{trex: map[uint32]trexDefaults{}}
+ tl := timeline{trex: map[uint32]trexDefaults{}, timescales: map[uint32]uint32{}}
var tracks []track
for _, c := range boxes {
switch c.typ {
@@ -258,6 +261,13 @@ func parseMoov(b []byte) (timeline, error) {
if err != nil {
return timeline{}, err
}
+ if t.timescale == 0 {
+ return timeline{}, errors.New("a track's timescale is 0")
+ }
+ if _, dup := tl.timescales[t.id]; dup {
+ return timeline{}, errors.New("two tracks with one track_ID")
+ }
+ tl.timescales[t.id] = t.timescale
tracks = append(tracks, t)
case "mvex":
if err := parseMvex(c.body, tl.trex); err != nil {
@@ -275,9 +285,6 @@ func parseMoov(b []byte) (timeline, error) {
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
}
@@ -382,10 +389,10 @@ const (
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) {
+// parseMoof reads one moof: the timeline track's tfdt, and the latest
+// end of any of its trafs in microseconds (rounded up); and, for every
+// traf, that its samples lie inside mdat's body.
+func parseMoof(b []byte, moof, mdat fileBox, tl timeline) (start uint64, endUS int64, err error) {
boxes, err := children(b)
if err != nil {
return 0, 0, fmt.Errorf("moof: %w", err)
@@ -399,25 +406,34 @@ func parseMoof(b []byte, moof, mdat fileBox, tl timeline) (start, dur uint64, er
if err != nil {
return 0, 0, err
}
+ if !hasTfdt {
+ return 0, 0, errors.New("a traf has no tfdt")
+ }
+ end, carry := bits.Add64(tfdt, d, 0)
+ if carry != 0 {
+ return 0, 0, errors.New("a traf's end overflows")
+ }
+ us, err := ticksToMicros(end, tl.timescales[id], true)
+ if err != nil {
+ return 0, 0, err
+ }
+ endUS = max(endUS, us)
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
+ found, start = true, tfdt
}
if !found {
return 0, 0, errors.New("no traf for the timeline's track")
}
- return start, dur, nil
+ return start, endUS, 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
+// parseTraf reads one traf of a track the moov declares: its track,
+// tfdt, and the sum of its sample durations, 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)
@@ -431,7 +447,9 @@ func parseTraf(b []byte, moof, mdat fileBox, tl timeline) (id uint32, tfdt uint6
if err != nil {
return 0, 0, false, 0, err
}
- timed := h.id == tl.track
+ if _, ok := tl.timescales[h.id]; !ok {
+ return 0, 0, false, 0, errors.New("a traf for a track the moov does not declare")
+ }
for _, c := range boxes[1:] {
switch c.typ {
case "tfdt":
@@ -443,7 +461,7 @@ func parseTraf(b []byte, moof, mdat fileBox, tl timeline) (id uint32, tfdt uint6
}
hasTfdt = true
case "trun":
- d, err := parseTrun(c.body, h, timed, moof, mdat)
+ d, err := parseTrun(c.body, h, moof, mdat)
if err != nil {
return 0, 0, false, 0, err
}
@@ -521,10 +539,10 @@ func parseTfdt(b []byte) (uint64, error) {
return 0, errors.New("tfdt is cut short or of an unknown version")
}
-// parseTrun sums one trun's sample durations (when timed) and checks
+// parseTrun sums one trun's sample durations 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) {
+func parseTrun(b []byte, h tfhd, moof, mdat fileBox) (uint64, error) {
if len(b) < 8 {
return 0, errors.New("trun is cut short")
}
@@ -551,8 +569,8 @@ func parseTrun(b []byte, h tfhd, timed bool, moof, mdat fileBox) (uint64, error)
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&trunSampleDuration == 0 && !h.hasDuration {
+ return 0, errors.New("no sample duration")
}
if flags&trunSampleSize == 0 && !h.hasSize {
return 0, errors.New("no sample size")
@@ -584,8 +602,5 @@ func parseTrun(b []byte, h tfhd, timed bool, moof, mdat fileBox) (uint64, error)
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
index dbe2e7f44..f9787e270 100644
--- a/internal/mediahandler/fmp4_synth_test.go
+++ b/internal/mediahandler/fmp4_synth_test.go
@@ -227,12 +227,25 @@ func TestReadFMP4Synthetic(t *testing.T) {
"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.
+ // Fragments are cut at the video's tfdt, whichever track comes
+ // first; the file ends where the last track ends (fix 1): the
+ // audio here runs 4 s a fragment, 4.5 s in the last, to 12.5 s,
+ // past the video's 9 s.
"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]...)
+ d := uint32(4 * 48000)
+ if i == 2 {
+ d = 216000
+ }
+ f.frags[i] = append([]sTraf{{track: 2, tfdt: uint64(i) * 4 * 48000, truns: []sTrun{{flags: trunSampleDuration | trunSampleSize, durs: []uint32{d}, sizes: []uint32{4}}}}}, f.frags[i]...)
+ }
+ }, []float64{4, 4, 4.5}, 12500},
+ // An audio track that ends before the video changes nothing.
+ "audio shorter": {func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 2, handler: "soun", timescale: 48000})
+ for i := range f.frags {
+ f.frags[i] = append(f.frags[i], sTraf{track: 2, tfdt: uint64(i) * 48000, truns: []sTrun{{flags: trunSampleDuration | trunSampleSize, durs: []uint32{48000}, sizes: []uint32{4}}}})
}
}, []float64{4, 4, 1}, 9000},
// No video track: the first track's timeline.
@@ -260,7 +273,7 @@ func TestReadFMP4Synthetic(t *testing.T) {
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))) {
+ if !slices.EqualFunc(got, c.durs, func(a, b float64) bool { return math.Abs(a-b) < 1e-6 }) || 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)
}
}
@@ -281,9 +294,29 @@ func TestReadFMP4SyntheticRefusals(t *testing.T) {
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"},
+ "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"},
+ "another track's timescale 0": {edit: func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 2, handler: "soun"})
+ }, want: "timescale is 0"},
+ "two tracks with one id": {edit: func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 1, handler: "soun", timescale: 48000})
+ }, want: "one track_ID"},
+ "a traf for no track": {edit: func(f *sFile) { f.frags[1][0].track = 9 }, want: "does not declare"},
+ "no traf for the track": {edit: func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 2, handler: "soun", timescale: 48000})
+ f.frags[1][0].track = 2
+ }, want: "no traf for the timeline's track"},
+ "another traf with no tfdt": {edit: func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 2, handler: "soun", timescale: 48000})
+ f.frags[1] = append(f.frags[1], sTraf{track: 2, noTfdt: true, truns: []sTrun{{flags: trunSampleDuration | trunSampleSize, durs: []uint32{1}, sizes: []uint32{1}}}})
+ }, want: "a traf has no tfdt"},
+ "another traf with no durations": {edit: func(f *sFile) {
+ f.tracks = append(f.tracks, sTrack{id: 2, handler: "soun", timescale: 48000, noTrex: true})
+ f.frags[1] = append(f.frags[1], sTraf{track: 2, tfdt: 48000, truns: []sTrun{{flags: trunSampleSize, sizes: []uint32{1}}}})
+ }, want: "no sample duration"},
+ // 2e15 ticks of 1,000 is 2e18 µs: under 2^64, over the bound.
+ "a tfdt past the bound": {edit: func(f *sFile) { f.frags[2][0].tfdt = 2e15 }, want: "implausible"},
"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) {
@@ -310,10 +343,10 @@ func TestReadFMP4SyntheticRefusals(t *testing.T) {
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) {
+ "a traf's end overflows": {edit: func(f *sFile) {
huge(f)
f.frags[2][0].tfdt = math.MaxUint64 - 1<<31
- }, want: "duration overflows"},
+ }, want: "end overflows"},
"a moov over the bound": {raw: func(b []byte) []byte {
moov := topBoxesOf(b)[1]
pad := mkbox("free", make([]byte, maxHeaderBox))
diff --git a/internal/mediahandler/fmp4_test.go b/internal/mediahandler/fmp4_test.go
index 974867544..a77cb7e58 100644
--- a/internal/mediahandler/fmp4_test.go
+++ b/internal/mediahandler/fmp4_test.go
@@ -100,10 +100,10 @@ func readPackets(t *testing.T, name string) []packet {
// 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.
+// stream's packet times, and the last one runs to the latest end of any
+// stream's packets (fix 1); 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 file, within 1 ms.
func TestReadFMP4Fixtures(t *testing.T) {
const aacFrame = 1024.0 / 48000
for _, c := range []struct {
@@ -113,7 +113,10 @@ func TestReadFMP4Fixtures(t *testing.T) {
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},
+ // The file's end is its latest track's (fix 1): the audio, which
+ // the muxer delays with the video by the video's two-frame
+ // decoder delay, ends at 9.0667 s.
+ {"video.mp4", 3, 9067, 0.0005, aacFrame},
{"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:
@@ -167,19 +170,18 @@ func TestReadFMP4Fixtures(t *testing.T) {
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
- }
+ // The file's end is any stream's (fix 1); the cut points
+ // are the timeline's (stream 0).
if !math.IsNaN(p.dur) {
end = max(end, p.dts+p.dur)
}
+ if p.stream == 0 && first[i] < 0 {
+ first[i] = p.dts
+ }
}
// 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
+ // last: its timeline packets start before its end, and every
+ // stream's 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
@@ -203,7 +205,7 @@ func TestReadFMP4Fixtures(t *testing.T) {
f.DurationS, lastStart-first[i], end-first[i])
}
}
- // The whole: ffprobe's own duration of the stream.
+ // The whole: ffprobe's own duration of the file.
probed, err := strconv.ParseFloat(strings.TrimSpace(string(readFixture(t, c.file+".duration"))), 64)
if err != nil {
t.Fatal(err)
diff --git a/internal/mediahandler/probe.go b/internal/mediahandler/probe.go
index d861a4614..3c3fa7fcb 100644
--- a/internal/mediahandler/probe.go
+++ b/internal/mediahandler/probe.go
@@ -66,7 +66,7 @@ const maxDecodePixels = media.MaxSide * media.MaxSide
// nothing else, so the source's tags (a title, a location), but for a
// stream's rotate tag, never reach the handler's memory.
const probeEntries = "format=duration" +
- ":stream=index,codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate,color_transfer,channels,duration" +
+ ":stream=index,codec_type,codec_name,width,height,sample_aspect_ratio,avg_frame_rate,r_frame_rate,color_transfer,channels,duration" +
":stream_disposition=attached_pic:stream_tags=rotate" +
":stream_side_data=side_data_type,rotation,dv_profile"
@@ -89,10 +89,12 @@ const maxDurationMS = int64(1) << 50
// probeFacts are what the checks and the encodes need from ffprobe.
// An absent stream's index is -1. Rotation is the display matrix's, in
// ffprobe's sense (degrees counter-clockwise: an iPhone portrait clip
-// is -90), one of -90, 0, 90, 180.
+// is -90), one of -90, 0, 90, 180. SARNum:SARDen is the video's
+// sample (pixel) aspect ratio, 0:0 when ffprobe gives none (square).
type probeFacts struct {
VideoIndex, AudioIndex int
Width, Height, Rotation int
+ SARNum, SARDen int
FPS float64
HDR bool
DolbyVisionProfile int
@@ -242,6 +244,7 @@ type ffStream struct {
CodecName string `json:"codec_name"`
Width int `json:"width"`
Height int `json:"height"`
+ SAR string `json:"sample_aspect_ratio"`
AvgFrameRate string `json:"avg_frame_rate"`
RFrameRate string `json:"r_frame_rate"`
ColorTransfer string `json:"color_transfer"`
@@ -361,6 +364,9 @@ func videoFacts(f *probeFacts, s *ffStream) error {
}
}
f.FPS = max(fps, 0)
+ if f.SARNum, f.SARDen, err = parseSAR(s.SAR); err != nil {
+ return fmt.Errorf("stream %d sample_aspect_ratio: %w", s.Index, err)
+ }
f.HDR = s.ColorTransfer == "smpte2084" || s.ColorTransfer == "arib-std-b67"
matrix := false
for _, sd := range s.SideData {
@@ -399,6 +405,29 @@ func quarterTurns(deg float64) int {
return q
}
+// maxSARTerm bounds a sample aspect ratio's terms (the codecs' fields
+// are 16 bits); a larger one is no ratio.
+const maxSARTerm = 1 << 16
+
+// parseSAR reads an ffprobe sample aspect ratio "num:den" of positive
+// integers up to maxSARTerm. "", "N/A", "0:1" and anything with a zero
+// term are none (0, 0): square pixels.
+func parseSAR(s string) (num, den int, err error) {
+ if s == "" || s == "N/A" {
+ return 0, 0, nil
+ }
+ n, d, ok := strings.Cut(s, ":")
+ num64, err1 := strconv.ParseUint(n, 10, 63)
+ den64, err2 := strconv.ParseUint(d, 10, 63)
+ if !ok || err1 != nil || err2 != nil {
+ return 0, 0, errors.New("not a ratio of non-negative integers")
+ }
+ if num64 == 0 || den64 == 0 || num64 > maxSARTerm || den64 > maxSARTerm {
+ return 0, 0, nil
+ }
+ return int(num64), int(den64), nil
+}
+
// parseRate reads an ffprobe rational "num/den" of non-negative
// integers. "0/0" and "" are no rate, answered as -1.
func parseRate(s string) (float64, error) {
diff --git a/internal/mediahandler/probe_test.go b/internal/mediahandler/probe_test.go
index d567ce8d7..7aa92d1cc 100644
--- a/internal/mediahandler/probe_test.go
+++ b/internal/mediahandler/probe_test.go
@@ -26,7 +26,8 @@ func fixture(t testing.TB, name string) []byte {
}
// TestParseProbeFixtures: the facts each fixture yields under its
-// preset. Most are the real ffprobe's answers (TestRealProbeMatchesFixtures
+// preset (a sample aspect ratio only where ffprobe 7.1.5 printed one:
+// the generated video fixtures, plan 3 Task 4 fix 1). Most are the real ffprobe's answers (TestRealProbeMatchesFixtures
// keeps them so); the Chrome WebM and av-no-duration have no duration in
// their header, so parseProbe answers 0 and probe runs the packet pass.
func TestParseProbeFixtures(t *testing.T) {
@@ -35,18 +36,18 @@ func TestParseProbeFixtures(t *testing.T) {
preset string
want probeFacts
}{
- "iphone-hevc-hlg-portrait": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 1920, Height: 1080, Rotation: -90, FPS: 30, HDR: true, VideoCodec: "hevc", AudioCodec: "aac", Channels: 2, DurationMS: 1000}},
+ "iphone-hevc-hlg-portrait": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 1920, Height: 1080, Rotation: -90, SARNum: 1, SARDen: 1, FPS: 30, HDR: true, VideoCodec: "hevc", AudioCodec: "aac", Channels: 2, DurationMS: 1000}},
"dolby-vision-8-4": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 3840, Height: 2160, Rotation: -90, FPS: 60, HDR: true, DolbyVisionProfile: 8, VideoCodec: "hevc", AudioCodec: "aac", Channels: 2, DurationMS: 8000}},
- "vfr-screen-recording": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 640, Height: 400, FPS: 1800.0 / 59, VideoCodec: "h264", DurationMS: 1967}},
+ "vfr-screen-recording": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 640, Height: 400, SARNum: 1, SARDen: 1, FPS: 1800.0 / 59, VideoCodec: "h264", DurationMS: 1967}},
"chrome-webm-opus": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "opus", Channels: 1}},
"av-no-duration": {a, probeFacts{VideoIndex: -1, AudioIndex: 1, AudioCodec: "opus", Channels: 1}},
"dolby-vision-5": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 1920, Height: 1080, FPS: 24000.0 / 1001, HDR: true, DolbyVisionProfile: 5, VideoCodec: "hevc", DurationMS: 20020}},
"mp3-cover-art": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "mp3", Channels: 1, DurationMS: 3031}},
"m4a-cover-art": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "aac", Channels: 1, DurationMS: 3000}},
"mka-cover-art": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "flac", Channels: 1, DurationMS: 2000}},
- "h264-subtitle": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 160, Height: 90, FPS: 10, VideoCodec: "h264", AudioCodec: "aac", Channels: 1, DurationMS: 2000}},
- "h264-4k60": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 3840, Height: 2160, FPS: 60, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 50}},
- "h264-120fps": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 320, Height: 180, FPS: 120, VideoCodec: "h264", DurationMS: 1000}},
+ "h264-subtitle": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 160, Height: 90, SARNum: 1, SARDen: 1, FPS: 10, VideoCodec: "h264", AudioCodec: "aac", Channels: 1, DurationMS: 2000}},
+ "h264-4k60": {v, probeFacts{VideoIndex: 0, AudioIndex: 1, Width: 3840, Height: 2160, SARNum: 1, SARDen: 1, FPS: 60, VideoCodec: "h264", AudioCodec: "aac", Channels: 2, DurationMS: 50}},
+ "h264-120fps": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 320, Height: 180, SARNum: 1, SARDen: 1, FPS: 120, VideoCodec: "h264", DurationMS: 1000}},
"bomb-30000": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 30000, Height: 30000, FPS: 1, VideoCodec: "h264", DurationMS: 1000}},
"lying-10h": {v, probeFacts{VideoIndex: 0, AudioIndex: -1, Width: 1280, Height: 720, FPS: 30, VideoCodec: "h264", DurationMS: 36000000}},
"wav-mono": {a, probeFacts{VideoIndex: -1, AudioIndex: 0, AudioCodec: "pcm_s16le", Channels: 1, DurationMS: 2500}},
@@ -506,7 +507,7 @@ func TestProbeArgs(t *testing.T) {
a = append(a, extra...)
return append(a, "-i", filepath.Join(cfg.Scratch, "in", "source"))
}
- entries := "format=duration:stream=index,codec_type,codec_name,width,height,avg_frame_rate,r_frame_rate,color_transfer,channels,duration:stream_disposition=attached_pic:stream_tags=rotate:stream_side_data=side_data_type,rotation,dv_profile"
+ entries := "format=duration:stream=index,codec_type,codec_name,width,height,sample_aspect_ratio,avg_frame_rate,r_frame_rate,color_transfer,channels,duration:stream_disposition=attached_pic:stream_tags=rotate:stream_side_data=side_data_type,rotation,dv_profile"
for i, w := range [][]string{
want("mov", cfg, "-show_entries", entries, "-of", "json"),
want("matroska", cfg2, "-show_entries", entries, "-of", "json"),
diff --git a/internal/mediahandler/realencode_test.go b/internal/mediahandler/realencode_test.go
index dcb7619e6..2178f27f8 100644
--- a/internal/mediahandler/realencode_test.go
+++ b/internal/mediahandler/realencode_test.go
@@ -43,10 +43,17 @@ func init() {
"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.
+ // The header's duration (the audio's, 9 s) is longer than the
+ // video (1 s): a poster 1 s in finds no frame, and the video must
+ // be padded to cover the audio (fix 1).
"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},
+ "-f lavfi -i testsrc=size=160x90:rate=10:d=1 -f lavfi -i sine=d=9 -c:v libx264 -preset ultrafast -c:a aac -f mp4 OUT", false},
+ // A video (6 s) longer than its audio (2 s): not cut to the audio.
+ "long-video-short-audio": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc=size=160x90:rate=10:d=6 -f lavfi -i sine=d=2 -c:v libx264 -preset ultrafast -c:a aac -f mp4 OUT", false},
+ // Anamorphic: 720x480 stored, 4:3 pixels, shown 960x480 (fix 1).
+ "anamorphic-4-3": {"mov", media.PresetVideo720p,
+ "-f lavfi -i testsrc=size=720x480:rate=10:d=1 -vf setsar=4/3 -c:v libx264 -preset ultrafast -f mp4 OUT", false},
} {
recipes[name] = r
}
@@ -103,7 +110,7 @@ func realEncode(t *testing.T, cfg Config, name, preset string, grantedMS int64)
// 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.
+// and the file'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)
@@ -146,7 +153,7 @@ func TestRegenerateFMP4Fixtures(t *testing.T) {
}
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 {
+ "-show_entries", "format=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 {
@@ -185,6 +192,9 @@ type probedOutput struct {
Width int `json:"width"`
Height int `json:"height"`
PixFmt string `json:"pix_fmt"`
+ SAR string `json:"sample_aspect_ratio"`
+ StartTime string `json:"start_time"`
+ Duration string `json:"duration"`
AvgFrameRate string `json:"avg_frame_rate"`
ColorTrc string `json:"color_transfer"`
SampleRate string `json:"sample_rate"`
@@ -200,7 +210,7 @@ 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",
+ "-show_entries", "stream=codec_type,codec_name,profile,width,height,pix_fmt,sample_aspect_ratio,start_time,duration,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)
}
@@ -237,34 +247,50 @@ func packetsVia(t *testing.T, cfg Config, path string) (counts string, 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).
+// packageOutput. The video is H.264 High yuv420p at outputSize with
+// square pixels, 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). With audio, the two tracks end within a
+// video frame of each other, at the longer of the source's streams
+// (fix 1): the duration is within a video frame of the audio track's
+// end, the source's length plus at most the muxer's start delay (two
+// video frames) and the AAC encoder's priming, and the playlist's
+// EXTINF values sum to it.
func TestRealVideoEncodes(t *testing.T) {
cfg := realConfig(t)
for _, c := range []struct {
name string
ow, oh int
audio bool
- maxFPS float64
hdrInput bool
+ // lengthMS is the longer of the source's streams; frame its
+ // video frame, in seconds. videoMS, when set, is where the video
+ // ends instead: the audio outlasts it.
+ lengthMS int64
+ frame float64
+ videoMS int64
}{
- {"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},
+ {"h264-1080p", 1280, 720, true, false, 2500, 1.0 / 30, 0},
+ {"iphone-hevc-hlg-portrait", 720, 1280, true, true, 1000, 1.0 / 30, 0},
+ {"hevc-pq", 1280, 720, false, true, 1000, 1.0 / 30, 0},
+ {"vfr-screen-recording", 640, 400, false, false, 2000, 1.0 / 15, 0},
+ {"fixture-video", 160, 90, false, false, 10000, 1.0 / 30, 0},
+ {"short-video-long-audio", 160, 90, true, false, 9000, 1.0 / 10, 0},
+ {"long-video-short-audio", 160, 90, true, false, 6000, 1.0 / 10, 0},
+ {"anamorphic-4-3", 960, 480, false, false, 1000, 1.0 / 10, 0},
+ // No header duration: the probe times the video's packets (1 s),
+ // and the audio (3 s) is kept whole past it, not cut (fix 1).
+ {"av-no-duration", 160, 90, true, false, 3000, 1.0 / 10, 1000},
} {
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)
+ if ow, oh := outputSize(f); ow != c.ow || oh != c.oh {
+ t.Fatalf("outputSize %dx%d, want %dx%d", ow, oh, c.ow, c.oh)
}
durationMS, err := packageOutput(cfg, p, "video.mp4", "video.m3u8")
if err != nil {
@@ -275,15 +301,20 @@ func TestRealVideoEncodes(t *testing.T) {
if v.CodecName != "h264" || v.Profile != "High" || v.PixFmt != "yuv420p" || v.Width != c.ow || v.Height != c.oh {
t.Errorf("video %+v", v)
}
+ if v.SAR != "" && v.SAR != "1:1" {
+ t.Errorf("video sample aspect ratio %s, want square", v.SAR)
+ }
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 {
+ if fps, err := parseRate(v.AvgFrameRate); err != nil || fps > 30.01 {
t.Errorf("frame rate %s", v.AvgFrameRate)
}
+ vdur := parseFloat(t, v.Duration)
+ vend := parseFloat(t, v.StartTime) + vdur
if c.audio {
if len(out.Streams) != 2 {
t.Fatalf("%d streams, want video and audio", len(out.Streams))
@@ -292,9 +323,39 @@ func TestRealVideoEncodes(t *testing.T) {
if a.CodecName != "aac" || a.Profile != "LC" || a.SampleRate != "48000" || a.Channels != 2 {
t.Errorf("audio %+v", a)
}
+ aend := parseFloat(t, a.StartTime) + parseFloat(t, a.Duration)
+ if c.videoMS > 0 {
+ // Less at most a frame, plus at most the muxer's
+ // two-frame start delay.
+ if d := vend - float64(c.videoMS)/1000; d < -c.frame || d > 2*c.frame+0.001 {
+ t.Errorf("video ends at %.3f s, want %d ms", vend, c.videoMS)
+ }
+ } else if math.Abs(vend-aend) > c.frame {
+ t.Errorf("video ends at %.3f s, audio at %.3f s: more than a frame apart", vend, aend)
+ }
+ if got := float64(durationMS) / 1000; math.Abs(got-aend) > c.frame {
+ t.Errorf("duration %d ms, the audio ends at %.3f s", durationMS, aend)
+ }
} else if len(out.Streams) != 1 {
t.Errorf("%d streams, want the video alone", len(out.Streams))
}
+ // The length: the longer stream's, less at most a frame, plus
+ // at most the muxer's two-frame start delay and the AAC
+ // encoder's 1,024 priming samples.
+ const priming = 1024.0 / 48000
+ if got := float64(durationMS) / 1000; got < float64(c.lengthMS)/1000-c.frame || got > float64(c.lengthMS)/1000+2*c.frame+priming+0.001 {
+ t.Errorf("duration %d ms, want %d ms within a frame", durationMS, c.lengthMS)
+ }
+ pl, err := os.ReadFile(outPath(cfg, "video.m3u8"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ fi, err := os.Stat(outPath(cfg, "video.mp4"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ initLen := atoi(t, strings.SplitN(strings.SplitN(string(pl), `BYTERANGE="`, 2)[1], "@", 2)[0])
+ checkPlaylist(t, string(pl), "video.mp4", initLen, fi.Size(), durationMS)
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)
@@ -312,14 +373,15 @@ func TestRealVideoEncodes(t *testing.T) {
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 want := int(math.Ceil(vdur/2 - 0.01)); len(keys) != want {
+ t.Errorf("%d keyframes over %.3f s of video, want %d", len(keys), vdur, 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 {
+ if len(poster.Streams) != 1 || poster.Streams[0].CodecName != "mjpeg" || poster.Streams[0].Width != c.ow || poster.Streams[0].Height != c.oh ||
+ (poster.Streams[0].SAR != "" && poster.Streams[0].SAR != "1:1") {
t.Errorf("poster %+v", poster.Streams)
}
})
diff --git a/internal/mediahandler/testdata/fmp4/args.txt b/internal/mediahandler/testdata/fmp4/args.txt
index aceecad2a..6c7cfc6d8 100644
--- a/internal/mediahandler/testdata/fmp4/args.txt
+++ b/internal/mediahandler/testdata/fmp4/args.txt
@@ -1,4 +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":"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,setsar=1,format=yuv420p,tpad=stop_mode=clone:stop=-1,trim=duration=9.000","-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","-af","apad=whole_dur=9.000","-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,setsar=1,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/provenance.txt b/internal/mediahandler/testdata/fmp4/provenance.txt
index 25a2b66c9..e48af990b 100644
--- a/internal/mediahandler/testdata/fmp4/provenance.txt
+++ b/internal/mediahandler/testdata/fmp4/provenance.txt
@@ -1,4 +1,6 @@
-Where each fixture comes from (plan 3 Task 4).
+Where each fixture comes from (plan 3 Task 4; remade in fix round 1,
+when the video encode gained setsar=1 and, with audio, the tpad/trim
+and apad padding).
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
@@ -12,7 +14,9 @@ arguments, the scratch path written <scratch>). Rewrite them with:
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
+ MP4; encoded with audio, cut to 9 s (it ends
+ at 9.0667 s: the muxer delays both tracks by
+ the video's two-frame decoder delay)
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
@@ -21,8 +25,8 @@ audio.mp4 recipe fixture-audio: 10 s 44.1 kHz stereo
<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
+<file>.duration ffprobe -show_entries format=duration
+ -of csv=p=0 (the file's end, its latest track's)
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
diff --git a/internal/mediahandler/testdata/fmp4/video.mp4.duration b/internal/mediahandler/testdata/fmp4/video.mp4.duration
index a2041e9ee..34e0c9f2b 100644
--- a/internal/mediahandler/testdata/fmp4/video.mp4.duration
+++ b/internal/mediahandler/testdata/fmp4/video.mp4.duration
@@ -1 +1 @@
-9.000000
+9.066667
diff --git a/internal/mediahandler/testdata/probe/av-no-duration.json b/internal/mediahandler/testdata/probe/av-no-duration.json
index 2c7a3436a..f3a2f9e1b 100644
--- a/internal/mediahandler/testdata/probe/av-no-duration.json
+++ b/internal/mediahandler/testdata/probe/av-no-duration.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 160,
"height": 90,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "10/1",
"avg_frame_rate": "10/1",
"disposition": {
diff --git a/internal/mediahandler/testdata/probe/h264-120fps.json b/internal/mediahandler/testdata/probe/h264-120fps.json
index 3c90926e6..241138c73 100644
--- a/internal/mediahandler/testdata/probe/h264-120fps.json
+++ b/internal/mediahandler/testdata/probe/h264-120fps.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 320,
"height": 180,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "120/1",
"avg_frame_rate": "120/1",
"duration": "1.000000",
diff --git a/internal/mediahandler/testdata/probe/h264-4k60.json b/internal/mediahandler/testdata/probe/h264-4k60.json
index 220cb54d2..1c1fa4592 100644
--- a/internal/mediahandler/testdata/probe/h264-4k60.json
+++ b/internal/mediahandler/testdata/probe/h264-4k60.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 3840,
"height": 2160,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "60/1",
"avg_frame_rate": "60/1",
"duration": "0.050000",
diff --git a/internal/mediahandler/testdata/probe/h264-subtitle.json b/internal/mediahandler/testdata/probe/h264-subtitle.json
index b029f575c..d29f9f5e9 100644
--- a/internal/mediahandler/testdata/probe/h264-subtitle.json
+++ b/internal/mediahandler/testdata/probe/h264-subtitle.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 160,
"height": 90,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "10/1",
"avg_frame_rate": "10/1",
"duration": "2.000000",
diff --git a/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json b/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json
index 6c4eb2a8a..009ed76af 100644
--- a/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json
+++ b/internal/mediahandler/testdata/probe/iphone-hevc-hlg-portrait.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 1920,
"height": 1080,
+ "sample_aspect_ratio": "1:1",
"color_transfer": "arib-std-b67",
"r_frame_rate": "30/1",
"avg_frame_rate": "30/1",
diff --git a/internal/mediahandler/testdata/probe/m4a-cover-art.json b/internal/mediahandler/testdata/probe/m4a-cover-art.json
index 3fca37aa7..01a99db0d 100644
--- a/internal/mediahandler/testdata/probe/m4a-cover-art.json
+++ b/internal/mediahandler/testdata/probe/m4a-cover-art.json
@@ -27,6 +27,7 @@
"codec_type": "video",
"width": 64,
"height": 64,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "90000/1",
"avg_frame_rate": "0/0",
"duration": "3.000000",
diff --git a/internal/mediahandler/testdata/probe/mka-cover-art.json b/internal/mediahandler/testdata/probe/mka-cover-art.json
index 67e287301..e9b651520 100644
--- a/internal/mediahandler/testdata/probe/mka-cover-art.json
+++ b/internal/mediahandler/testdata/probe/mka-cover-art.json
@@ -26,6 +26,7 @@
"codec_type": "video",
"width": 64,
"height": 64,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "90000/1",
"avg_frame_rate": "0/0",
"duration": "2.000000",
diff --git a/internal/mediahandler/testdata/probe/mp3-cover-art.json b/internal/mediahandler/testdata/probe/mp3-cover-art.json
index 5598ff8dd..f13a392f3 100644
--- a/internal/mediahandler/testdata/probe/mp3-cover-art.json
+++ b/internal/mediahandler/testdata/probe/mp3-cover-art.json
@@ -24,6 +24,7 @@
"codec_type": "video",
"width": 64,
"height": 64,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "90000/1",
"avg_frame_rate": "0/0",
"duration": "3.030200",
diff --git a/internal/mediahandler/testdata/probe/vfr-screen-recording.json b/internal/mediahandler/testdata/probe/vfr-screen-recording.json
index 75e990c21..bc0b76038 100644
--- a/internal/mediahandler/testdata/probe/vfr-screen-recording.json
+++ b/internal/mediahandler/testdata/probe/vfr-screen-recording.json
@@ -12,6 +12,7 @@
"codec_type": "video",
"width": 640,
"height": 400,
+ "sample_aspect_ratio": "1:1",
"r_frame_rate": "120/1",
"avg_frame_rate": "1800/59",
"duration": "1.966667",