Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(video): bound splice parsing, compare whole sample entries, cancel splices

Lincoln Stein9a607ccf05b4
diff --git a/invokeai/app/invocations/video_concat.py b/invokeai/app/invocations/video_concat.py
index 8ddeff8ba0..0701a488b0 100644
--- a/invokeai/app/invocations/video_concat.py
+++ b/invokeai/app/invocations/video_concat.py
@@ -63,6 +63,7 @@ from invokeai.app.util.h264_splice import (
SpliceError,
concat_stream_copy,
copy_frames,
+ probes_as,
read_h264_layout,
)
from invokeai.app.util.video_audio import (
@@ -71,7 +72,7 @@ from invokeai.app.util.video_audio import (
mux_audio_into_video,
resample_linear,
)
-from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_decoder_config
+from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_sample_entry
from invokeai.app.util.video_thumbnails import iter_video_frames, probe_video
TransitionMode = Literal["cut", "crossfade", "fade_through_black"]
@@ -235,7 +236,9 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
keyframe, layout = splice
rest_path = work_dir / "rest.mp4"
rest = self._encode_joined(context, paths, (width, height), output_fps, rest_path, skip=keyframe)
- if self._splice(context, paths[0], keyframe, layout, rest_path, rest[0][0], work_dir, tmp_path):
+ if self._splice(
+ context, paths[0], keyframe, layout, rest_path, rest[0][0], output_fps, work_dir, tmp_path
+ ):
joined = rest
if joined is None:
joined = self._encode_joined(context, paths, (width, height), output_fps, tmp_path, skip=0)
@@ -287,6 +290,9 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
f"Encoded concatenated MP4: {num_frames} frames @ {output_fps:.2f} fps "
f"({duration:.2f}s) at {width}x{height}" + (", with AAC audio" if audio is not None else ", silent")
)
+ # Splice stages run uninterrupted; a cancellation that arrived meanwhile must not be saved.
+ if context.util.is_canceled():
+ raise CanceledException
video_dto = context.videos.save(
source_path=source_path,
width=width,
@@ -324,7 +330,7 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
if (
layout is None
or layout.frame_duration is None
- or layout.decoder_config != writer_decoder_config(*canvas, output_fps)
+ or layout.sample_entry != writer_sample_entry(*canvas, output_fps)
):
return None
tail_need, _ = self._transition_windows()
@@ -383,6 +389,7 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
layout: H264Layout,
rest_path: Path,
first_clip_frames: int,
+ output_fps: float,
work_dir: Path,
out_path: Path,
) -> bool:
@@ -397,24 +404,28 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
rest = read_h264_layout(rest_path)
if first_clip_frames != layout.sample_count:
reason = f"it decoded to {first_clip_frames} frames but lists {layout.sample_count}"
- elif rest is None or rest.decoder_config != layout.decoder_config or rest.sync_samples[:1] != (0,):
+ elif rest is None or rest.sample_entry != layout.sample_entry or rest.sync_samples[:1] != (0,):
reason = "its encoding differs from this node's"
else:
reason = None
if reason is None:
head_path = work_dir / "head.mp4"
try:
- copy_frames(first_path, 0, keyframe, layout.sample_count, head_path)
+ copy_frames(first_path, 0, keyframe, layout.sample_count, head_path, context.util.is_canceled)
head = read_h264_layout(head_path)
- if head is None or head.sample_count != keyframe:
+ # ffmpeg can derive presentation boxes (e.g. a pasp from a tkhd display size) while
+ # copying, so the copied head must keep the source's own sample entry.
+ if head is None or head.sample_count != keyframe or head.sample_entry != layout.sample_entry:
reason = "copying its head did not yield the expected frames"
else:
- concat_stream_copy([head_path, rest_path], out_path)
+ concat_stream_copy([head_path, rest_path], out_path, context.util.is_canceled)
joined = read_h264_layout(out_path)
if (
joined is None
+ or joined.sample_entry != layout.sample_entry
or joined.sample_count != keyframe + rest.sample_count
or joined.frame_duration != layout.frame_duration
+ or not probes_as(out_path, output_fps, joined.sample_count)
):
reason = "the joined file does not hold the expected frames on one timeline"
except SpliceError as e:
@@ -480,6 +491,7 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
rate,
pcm.shape[1],
out_path,
+ context.util.is_canceled,
)
muxed = extract_audio_pcm(out_path)
except (SpliceError, AudioExtractionError) as e:
diff --git a/invokeai/app/invocations/video_frame_extract_range.py b/invokeai/app/invocations/video_frame_extract_range.py
index eb67c19ddd..fd798478c8 100644
--- a/invokeai/app/invocations/video_frame_extract_range.py
+++ b/invokeai/app/invocations/video_frame_extract_range.py
@@ -54,11 +54,12 @@ from invokeai.app.util.h264_splice import (
SpliceError,
concat_stream_copy,
copy_frames,
+ probes_as,
read_h264_layout,
)
from invokeai.app.util.mp4_metadata import write_mp4_tags
from invokeai.app.util.video_audio import extract_audio_pcm, mux_audio_into_video, resample_linear
-from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_decoder_config
+from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_sample_entry
from invokeai.app.util.video_thumbnails import decoder_frame_count, iter_video_frames, probe_video
@@ -295,6 +296,9 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
f"Encoded trimmed MP4: {num_frames} frames @ {output_fps:.2f} fps "
f"({out_duration:.2f}s) at {width}x{height}" + (", with AAC audio" if audio is not None else ", silent")
)
+ # A cancellation that arrived during an uninterruptible stage must not be saved.
+ if context.util.is_canceled():
+ raise CanceledException
video_dto = context.videos.save(
source_path=source_path,
width=width,
@@ -338,7 +342,7 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
node's encoder writes and a constant frame duration, or the re-encoded ends could not
share its track.
"""
- if layout.frame_duration is None or layout.decoder_config != writer_decoder_config(width, height, fps):
+ if layout.frame_duration is None or layout.sample_entry != writer_sample_entry(width, height, fps):
return None
boundaries = [*layout.sync_samples, layout.sample_count]
inner_starts = [k for k in layout.sync_samples if k >= start and not 0 < k - start < MIN_ENCODED_FRAMES]
@@ -392,25 +396,27 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
middle_path = work_dir / "middle.mp4"
reason: Optional[str] = None
if any(
- (part := read_h264_layout(path)) is None or part.decoder_config != layout.decoder_config
+ (part := read_h264_layout(path)) is None or part.sample_entry != layout.sample_entry
for _, _, path in encoded
):
reason = "its encoding differs from this node's"
else:
try:
- copy_frames(video_path, k1, k2, layout.sample_count, middle_path)
+ copy_frames(video_path, k1, k2, layout.sample_count, middle_path, context.util.is_canceled)
middle = read_h264_layout(middle_path)
- if middle is None or middle.sample_count != k2 - k1:
+ if middle is None or middle.sample_count != k2 - k1 or middle.sample_entry != layout.sample_entry:
reason = "copying its frames did not yield the expected count"
else:
parts = [head[2]] if head in encoded else []
parts += [middle_path] + ([tail[2]] if tail in encoded else [])
- concat_stream_copy(parts, out_path)
+ concat_stream_copy(parts, out_path, context.util.is_canceled)
joined = read_h264_layout(out_path)
if (
joined is None
+ or joined.sample_entry != layout.sample_entry
or joined.sample_count != written + (k2 - k1)
or joined.frame_duration != layout.frame_duration
+ or not probes_as(out_path, output_fps, joined.sample_count)
):
reason = "the joined file does not hold the expected frames on one timeline"
except SpliceError as e:
@@ -436,6 +442,9 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
# A stream-copy remux that drops the source's keyed metadata: save() writes this
# node's record, and if that rewrite fails the source's must not be read back as it.
write_mp4_tags(video_path, copy_path, {})
+ # A cancellation that arrived during an uninterruptible stage must not be saved.
+ if context.util.is_canceled():
+ raise CanceledException
video_dto = context.videos.save(
source_path=copy_path,
width=width,
diff --git a/invokeai/app/util/aac_splice.py b/invokeai/app/util/aac_splice.py
index e145863580..ddb8b41221 100644
--- a/invokeai/app/util/aac_splice.py
+++ b/invokeai/app/util/aac_splice.py
@@ -28,7 +28,7 @@ the copied head decodes bit-exact before trusting the result.
import struct
import tempfile
from pathlib import Path
-from typing import BinaryIO, NamedTuple, Optional
+from typing import BinaryIO, Callable, NamedTuple, Optional
import numpy as np
@@ -151,7 +151,17 @@ def _read_audio_track(fh: BinaryIO, trak: tuple[int, int], mdia: tuple[int, int]
fh.seek(entry_start + 8)
if fh.read(2) != b"\x00\x00": # QuickTime v1/v2 sound entries lay their fields out differently
return None
- esds = find_box(fh, entry_start + _AUDIO_SAMPLE_ENTRY_HEADER, entry_end, b"esds")
+ # Anything beyond the decoder config (and a per-file bitrate) — a channel layout, say —
+ # would describe the copied packets differently from the ones encoded beside them. Read
+ # lazily and bounded: the entry is the uploader's.
+ # Each allowed box at most once, so a third box of any kind is refused and no more are read.
+ esds, seen = None, set()
+ for child, start, end in iter_boxes(fh, entry_start + _AUDIO_SAMPLE_ENTRY_HEADER, entry_end, max_boxes=3):
+ if child not in (b"esds", b"btrt") or child in seen:
+ return None
+ seen.add(child)
+ if child == b"esds":
+ esds = (start, end)
if esds is None:
return None
fh.seek(esds[0])
@@ -295,6 +305,7 @@ def mux_spliced_aac(
sample_rate: int,
total_samples: int,
out_path: Path,
+ is_canceled: Optional[Callable[[], bool]] = None,
) -> np.ndarray:
"""Write ``out_path`` = ``video_path``'s video plus a soundtrack spliced from ``source``.
@@ -316,9 +327,12 @@ def mux_spliced_aac(
run_ffmpeg(
["-i", str(source), "-map", "0:a:0", "-c", "copy", "-frames:a", str(head_packets), "-f", "adts", str(head)],
f"copying the first {head_packets} audio packets of {source.name}",
+ is_canceled,
)
write_stereo_wav(tail_wav, tail_pcm, sample_rate)
- run_ffmpeg(["-i", str(tail_wav), *AAC_ENCODE_ARGS, "-f", "adts", str(tail)], "encoding the new audio")
+ run_ffmpeg(
+ ["-i", str(tail_wav), *AAC_ENCODE_ARGS, "-f", "adts", str(tail)], "encoding the new audio", is_canceled
+ )
head_frames = _adts_frames(head.read_bytes())
if len(head_frames) != head_packets:
raise SpliceError(f"copied {len(head_frames)} audio packets, expected {head_packets}")
@@ -354,6 +368,7 @@ def mux_spliced_aac(
str(out_path),
],
"muxing the spliced audio",
+ is_canceled,
)
_set_track_duration(out_path, b"soun", total_samples, sample_rate)
return seam_reference
diff --git a/invokeai/app/util/h264_splice.py b/invokeai/app/util/h264_splice.py
index 83af5c7459..33712d45dc 100644
--- a/invokeai/app/util/h264_splice.py
+++ b/invokeai/app/util/h264_splice.py
@@ -6,10 +6,11 @@ segment through N generations of artifacts. When the head of a clip can be reuse
:func:`copy_frames` cuts out a keyframe-aligned run of frames without decoding, and
:func:`concat_stream_copy` joins it to freshly encoded neighbours.
-That join is only valid when every part carries the *same* decoder configuration: an MP4
-stores one ``avcC`` (profile, level, SPS and PPS) per track, so a part encoded with
-different parameters would be decoded against the wrong headers. :func:`read_h264_layout`
-exposes the ``avcC`` bytes so callers can require an exact match. Parts written by this
+That join is only valid when every part carries the *same* sample entry: an MP4 stores
+one per track — the ``avcC`` (profile, level, SPS and PPS) a decoder needs, and boxes such
+as ``colr`` and ``pasp`` that say how to present the frames — so a part encoded or tagged
+differently would be decoded or displayed against the wrong ones.
+:func:`read_h264_layout` exposes those bytes so callers can require an exact match. Parts written by this
app's own encoder (``make_mp4_writer``) at the same canvas and frame rate match; anything
else is reported as not spliceable rather than guessed at.
@@ -32,30 +33,42 @@ rotation applied as metadata, which decoding applies to the frames this app re-e
a stream copy carries into the joined file for all of them).
"""
+import math
import shutil
import struct
import subprocess
import tempfile
+import time
from pathlib import Path
-from typing import BinaryIO, NamedTuple, Optional
+from typing import BinaryIO, Callable, NamedTuple, Optional
import imageio_ffmpeg
+import numpy as np
+from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.util.mp4_metadata import find_box, iter_boxes
# A stream copy is disk-bound; this only stops a wedged child from holding the node forever.
SPLICE_TIMEOUT_SECONDS = 600
+# How often a running ffmpeg child is checked for cancellation.
+_CANCEL_POLL_SECONDS = 0.1
# ``moov`` precedes or follows ``mdat`` in a real file; a dozen top-level boxes at most.
_MAX_TOP_LEVEL_BOXES = 1024
-# A sync-sample table for even an hour of 120 fps all-intra video is ~430k entries.
-_MAX_SYNC_ENTRIES = 1 << 20
-# VisualSampleEntry fields before its child boxes (SampleEntry 8 + visual header 70).
+# Keyframes examined per track: at the 2 s interval this app writes, nine hours of video.
+_MAX_SYNC_ENTRIES = 1 << 14
+# VisualSampleEntry fields before its child boxes (SampleEntry 8 + visual header 70), and where
+# among them the 32-byte compressor name sits.
_VISUAL_SAMPLE_ENTRY_HEADER = 78
+_COMPRESSOR_NAME = slice(42, 74)
+# A real sample entry holds a handful of boxes (avcC, btrt, colr, pasp...); more is hostile.
+_MAX_ENTRY_CHILDREN = 32
+# NAL units examined per keyframe before its first slice (AUD, SEI, SPS, PPS precede it).
+_MAX_NALS_BEFORE_SLICE = 64
# Shortest part x264 (bframes=3, as make_mp4_writer leaves it) encodes with its full B-frame
# reorder delay; a shorter part joined to full-delay parts distorts the joined timestamps.
MIN_ENCODED_FRAMES = 3
-# A sample table for an hour of 120 fps video is ~430k entries.
-_MAX_SAMPLES = 1 << 22
+# Samples per track: over four hours at 60 fps. Bounds every table read before it is allocated.
+_MAX_SAMPLES = 1 << 20
# NAL unit types: 1-5 are coded slices, 5 an IDR picture's.
_NAL_IDR = 5
_NAL_VCL = range(1, 6)
@@ -72,6 +85,11 @@ class H264Layout(NamedTuple):
"""0-based decode-order indices of the IDR pictures — the only clean cut points — ascending."""
decoder_config: bytes
"""The raw ``avcC`` payload: profile, level, SPS and PPS."""
+ sample_entry: bytes
+ """What a joined track inherits from this one's sample entry: its fixed fields and every
+ child box — ``avcC``, and any ``colr``, ``pasp``, ``clap`` and the like, which change how
+ frames are presented without changing ``avcC`` — except ``btrt``, a per-file bitrate.
+ Two tracks can share a joined track only if these bytes match."""
frame_duration: Optional[int]
"""Every sample's duration in media ticks, or None if they are not all equal."""
@@ -216,58 +234,82 @@ def _read_stts(fh: BinaryIO, stbl: tuple[int, int]) -> Optional[list[tuple[int,
return list(zip(flat[::2], flat[1::2], strict=True))
-def _sample_locations(fh: BinaryIO, stbl: tuple[int, int], sample_count: int) -> Optional[list[tuple[int, int]]]:
- """``(file_offset, size)`` of every sample, from the size, chunk and chunk-offset tables."""
- stsz, stsc = find_box(fh, *stbl, b"stsz"), find_box(fh, *stbl, b"stsc")
- stco, co64 = find_box(fh, *stbl, b"stco"), find_box(fh, *stbl, b"co64")
- offsets_box, offset_format = (stco, "I") if stco is not None else (co64, "Q")
- if stsz is None or stsc is None or offsets_box is None or sample_count > _MAX_SAMPLES:
- return None
- # Each table opens with version/flags and a 4-byte count (stsz: a size and a count).
- if any(box[0] + 8 > box[1] for box in (stsz, stsc, offsets_box)):
+def _sample_sizes(fh: BinaryIO, stsz: tuple[int, int], sample_count: int, file_size: int) -> Optional[np.ndarray]:
+ """Every sample's size, or None unless the table is plausible for a file of ``file_size``.
+
+ The count comes from the file, so it is bounded before anything is allocated by it: by
+ ``_MAX_SAMPLES``, by the table actually holding that many entries, and by the samples
+ fitting in the file.
+ """
+ if not 0 < sample_count <= _MAX_SAMPLES or stsz[0] + 12 > stsz[1]:
return None
fh.seek(stsz[0] + 4)
(uniform_size,) = struct.unpack(">I", fh.read(4))
if uniform_size:
- sizes: tuple[int, ...] = (uniform_size,) * sample_count
- else:
- if stsz[0] + 12 + 4 * sample_count > stsz[1]:
+ if uniform_size * sample_count > file_size:
return None
- fh.seek(stsz[0] + 12)
- sizes = struct.unpack(f">{sample_count}I", fh.read(4 * sample_count))
+ return np.full(sample_count, uniform_size, dtype=np.int64)
+ if stsz[0] + 12 + 4 * sample_count > stsz[1]:
+ return None
+ fh.seek(stsz[0] + 12)
+ sizes = np.frombuffer(fh.read(4 * sample_count), dtype=">u4").astype(np.int64)
+ return sizes if int(sizes.sum()) <= file_size else None
+
+
+def _sample_locations(
+ fh: BinaryIO, stbl: tuple[int, int], sizes: np.ndarray, wanted: tuple[int, ...], file_size: int
+) -> Optional[list[tuple[int, int]]]:
+ """``(file_offset, size)`` of each sample in ``wanted`` (ascending), from the chunk tables."""
+ stsc = find_box(fh, *stbl, b"stsc")
+ stco, co64 = find_box(fh, *stbl, b"stco"), find_box(fh, *stbl, b"co64")
+ offsets_box, offset_format = (stco, "I") if stco is not None else (co64, "Q")
+ # Each table opens with version/flags and a 4-byte count.
+ if stsc is None or offsets_box is None or any(box[0] + 8 > box[1] for box in (stsc, offsets_box)):
+ return None
+ sample_count = len(sizes)
fh.seek(stsc[0] + 4)
(run_count,) = struct.unpack(">I", fh.read(4))
- if run_count == 0 or stsc[0] + 8 + 12 * run_count > stsc[1]:
+ if not 0 < run_count <= _MAX_SAMPLES or stsc[0] + 8 + 12 * run_count > stsc[1]:
return None
flat = struct.unpack(f">{3 * run_count}I", fh.read(12 * run_count))
runs = [(flat[i], flat[i + 1]) for i in range(0, len(flat), 3)]
fh.seek(offsets_box[0] + 4)
(chunk_count,) = struct.unpack(">I", fh.read(4))
entry = struct.calcsize(offset_format)
- if chunk_count > _MAX_SAMPLES or offsets_box[0] + 8 + entry * chunk_count > offsets_box[1]:
+ if chunk_count > sample_count or offsets_box[0] + 8 + entry * chunk_count > offsets_box[1]:
return None
chunk_offsets = struct.unpack(f">{chunk_count}{offset_format}", fh.read(entry * chunk_count))
+ # Byte position of each sample relative to the start of the sample table's data.
+ starts = np.concatenate([[0], np.cumsum(sizes)])
locations: list[tuple[int, int]] = []
+ pending = iter(wanted)
+ target = next(pending, None)
+ first_sample = 0
for run, (first_chunk, per_chunk) in enumerate(runs):
last_chunk = runs[run + 1][0] - 1 if run + 1 < len(runs) else chunk_count
- if not 1 <= first_chunk <= last_chunk + 1 or last_chunk > chunk_count:
+ if not 1 <= first_chunk <= last_chunk + 1 or last_chunk > chunk_count or per_chunk > sample_count:
return None
for chunk in range(first_chunk - 1, last_chunk):
- position = chunk_offsets[chunk]
- for _ in range(per_chunk):
- if len(locations) == sample_count:
+ end_sample = first_sample + per_chunk
+ if end_sample > sample_count:
+ return None
+ while target is not None and target < end_sample:
+ offset = chunk_offsets[chunk] + int(starts[target] - starts[first_sample])
+ if offset + int(sizes[target]) > file_size:
return None
- size = sizes[len(locations)]
- locations.append((position, size))
- position += size
- return locations if len(locations) == sample_count else None
+ locations.append((offset, int(sizes[target])))
+ target = next(pending, None)
+ first_sample = end_sample
+ return locations if first_sample == sample_count and target is None else None
def _is_idr(fh: BinaryIO, offset: int, size: int, length_size: int) -> bool:
"""True if the sample's first coded slice is an IDR slice (AUD, SEI, SPS and PPS may precede it)."""
position, end = offset, offset + size
- while position + length_size + 1 <= end:
+ for _ in range(_MAX_NALS_BEFORE_SLICE):
+ if position + length_size + 1 > end:
+ return False
fh.seek(position)
header = fh.read(length_size + 1)
if len(header) < length_size + 1:
@@ -303,17 +345,39 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
return None
fh.seek(avcc[0])
decoder_config = fh.read(avcc[1] - avcc[0])
-
- sizes = _read_full_box_table(fh, *stsz, ">II")
- if sizes is None:
+ fh.seek(entry_start)
+ header_fields = bytearray(fh.read(_VISUAL_SAMPLE_ENTRY_HEADER))
+ # The compressor name records the encoder's version: masked, so files this app wrote before
+ # an ffmpeg upgrade still match what it writes after one.
+ header_fields[_COMPRESSOR_NAME] = bytes(_COMPRESSOR_NAME.stop - _COMPRESSOR_NAME.start)
+ parts = [bytes(header_fields)]
+ children = list(
+ iter_boxes(fh, entry_start + _VISUAL_SAMPLE_ENTRY_HEADER, entry_end, max_boxes=_MAX_ENTRY_CHILDREN + 1)
+ )
+ if len(children) > _MAX_ENTRY_CHILDREN:
return None
- sample_count = sizes[1]
- if sample_count == 0:
+ for child, child_start, child_end in children:
+ if child != b"btrt":
+ fh.seek(child_start)
+ parts.append(struct.pack(">I", child_end - child_start) + child + fh.read(child_end - child_start))
+ sample_entry = b"".join(parts)
+
+ header = _read_full_box_table(fh, *stsz, ">II")
+ if header is None:
+ return None
+ fh.seek(0, 2)
+ file_size = fh.tell()
+ sizes = _sample_sizes(fh, stsz, header[1], file_size)
+ if sizes is None:
return None
+ sample_count = len(sizes)
stss = find_box(fh, *stbl, b"stss")
if stss is None:
- # No sync-sample table means every sample is a sync sample.
+ # No sync-sample table means every sample is a sync sample (an all-intra stream), each
+ # of which would be examined below: only a short one is worth splicing.
+ if sample_count > _MAX_SYNC_ENTRIES:
+ return None
sync_samples = tuple(range(sample_count))
else:
count = _read_full_box_table(fh, *stss, ">I")
@@ -328,10 +392,12 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
if len(decoder_config) < 5:
return None
length_size = (decoder_config[4] & 0x03) + 1
- locations = _sample_locations(fh, stbl, sample_count)
+ locations = _sample_locations(fh, stbl, sizes, sync_samples, file_size)
if locations is None:
return None
- idr_samples = tuple(k for k in sync_samples if _is_idr(fh, *locations[k], length_size))
+ idr_samples = tuple(
+ k for k, location in zip(sync_samples, locations, strict=True) if _is_idr(fh, *location, length_size)
+ )
runs = _read_stts(fh, stbl)
if runs is None:
@@ -342,25 +408,56 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
sample_count=sample_count,
sync_samples=idr_samples,
decoder_config=decoder_config,
+ sample_entry=sample_entry,
frame_duration=frame_duration,
)
-def run_ffmpeg(args: list[str], description: str) -> None:
- try:
- proc = subprocess.run(
+def run_ffmpeg(args: list[str], description: str, is_canceled: Optional[Callable[[], bool]] = None) -> None:
+ """Run the bundled ffmpeg, raising SpliceError if it fails or outlasts the timeout.
+
+ ``is_canceled`` is polled while the child runs; a cancellation kills and reaps it and
+ raises CanceledException, so a canceled node never waits on a long copy.
+ """
+ if is_canceled is not None and is_canceled():
+ raise CanceledException
+ with tempfile.TemporaryFile() as stderr:
+ proc = subprocess.Popen(
[imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-loglevel", "error", *args],
- capture_output=True,
- timeout=SPLICE_TIMEOUT_SECONDS,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=stderr,
)
- except subprocess.TimeoutExpired as e:
- raise SpliceError(f"ffmpeg timed out {description}") from e
- if proc.returncode != 0:
- stderr = proc.stderr.decode("utf-8", errors="replace").strip()
- raise SpliceError(f"ffmpeg failed {description}: {stderr[-500:]}")
-
-
-def copy_frames(src: Path, start: int, end: int, sample_count: int, dst: Path) -> None:
+ deadline = time.monotonic() + SPLICE_TIMEOUT_SECONDS
+ try:
+ while True:
+ try:
+ proc.wait(timeout=_CANCEL_POLL_SECONDS)
+ break
+ except subprocess.TimeoutExpired:
+ pass
+ if is_canceled is not None and is_canceled():
+ raise CanceledException
+ if time.monotonic() > deadline:
+ raise SpliceError(f"ffmpeg timed out {description}")
+ finally:
+ if proc.returncode is None:
+ proc.kill()
+ proc.wait()
+ if proc.returncode != 0:
+ stderr.seek(0)
+ message = stderr.read().decode("utf-8", errors="replace").strip()
+ raise SpliceError(f"ffmpeg failed {description}: {message[-500:]}")
+
+
+def copy_frames(
+ src: Path,
+ start: int,
+ end: int,
+ sample_count: int,
+ dst: Path,
+ is_canceled: Optional[Callable[[], bool]] = None,
+) -> None:
"""Write ``dst`` = frames ``[start, end)`` of ``src``'s video, stream-copied.
``start`` and ``end`` are decode-order sample indices that must each be a keyframe (or
@@ -373,6 +470,7 @@ def copy_frames(src: Path, start: int, end: int, sample_count: int, dst: Path) -
run_ffmpeg(
["-i", str(src), "-map", "0:v:0", "-c", "copy", "-frames:v", str(end), "-f", "mp4", str(dst)],
description,
+ is_canceled,
)
return
# The segment muxer splits at exact packet counts; the wanted range is the second segment.
@@ -398,6 +496,7 @@ def copy_frames(src: Path, start: int, end: int, sample_count: int, dst: Path) -
str(pattern),
],
description,
+ is_canceled,
)
segment = Path(work) / "segment1.mp4"
if not segment.exists():
@@ -405,13 +504,28 @@ def copy_frames(src: Path, start: int, end: int, sample_count: int, dst: Path) -
shutil.move(str(segment), str(dst))
+def probes_as(path: Path, fps: float, frames: int) -> bool:
+ """Whether a player's probe of ``path`` agrees with the timeline it should hold: ``frames``
+ at ``fps``. A last check on a joined file, independent of the sample tables it was built
+ from — a squeezed or stretched timestamp shows up as a wrong rate or duration."""
+ from invokeai.app.util.video_thumbnails import probe_video
+
+ _, _, duration, probed_fps = probe_video(path)
+ # The probe reports duration to the hundredth of a second.
+ return (
+ probed_fps is not None
+ and math.isclose(probed_fps, fps, rel_tol=1e-3)
+ and abs(duration - frames / fps) <= 0.5 / fps + 0.01
+ )
+
+
def _concat_list_entry(path: Path) -> str:
# The concat demuxer's quoting: close the quote, emit an escaped quote, reopen.
escaped = str(path.resolve()).replace("'", "'\\''")
return f"file '{escaped}'\n"
-def concat_stream_copy(parts: list[Path], dst: Path) -> None:
+def concat_stream_copy(parts: list[Path], dst: Path, is_canceled: Optional[Callable[[], bool]] = None) -> None:
"""Write ``dst`` = ``parts``' video streams joined end to end, stream-copied.
Every part must share one decoder configuration (see :func:`read_h264_layout`) and
@@ -439,6 +553,7 @@ def concat_stream_copy(parts: list[Path], dst: Path) -> None:
str(dst),
],
f"joining {len(parts)} stream-copied parts",
+ is_canceled,
)
finally:
list_path.unlink(missing_ok=True)
diff --git a/invokeai/app/util/video_encoding.py b/invokeai/app/util/video_encoding.py
index 0ae247fe74..91fcb1e80e 100644
--- a/invokeai/app/util/video_encoding.py
+++ b/invokeai/app/util/video_encoding.py
@@ -71,11 +71,12 @@ def make_mp4_writer(path: Path | str, fps: float, audio_path: Path | str | None
)
-_writer_decoder_configs: dict[tuple[int, int, float], bytes] = {}
+_writer_sample_entrys: dict[tuple[int, int, float], bytes] = {}
-def writer_decoder_config(width: int, height: int, fps: float) -> bytes | None:
- """The ``avcC`` bytes ``make_mp4_writer`` writes for this canvas and rate.
+def writer_sample_entry(width: int, height: int, fps: float) -> bytes | None:
+ """The sample entry ``make_mp4_writer`` writes for this canvas and rate (see
+ ``H264Layout.sample_entry``).
They depend only on the encoder settings, canvas and rate, never on the content, so one
encoded frame tells a splice up front whether a file can share a track with new output
@@ -83,15 +84,15 @@ def writer_decoder_config(width: int, height: int, fps: float) -> bytes | None:
successful probe is remembered.
"""
key = (width, height, fps)
- if key not in _writer_decoder_configs:
- config = _probe_decoder_config(width, height, fps)
+ if key not in _writer_sample_entrys:
+ config = _probe_sample_entry(width, height, fps)
if config is None:
return None
- _writer_decoder_configs[key] = config
- return _writer_decoder_configs[key]
+ _writer_sample_entrys[key] = config
+ return _writer_sample_entrys[key]
-def _probe_decoder_config(width: int, height: int, fps: float) -> bytes | None:
+def _probe_sample_entry(width: int, height: int, fps: float) -> bytes | None:
from invokeai.app.util.h264_splice import read_h264_layout
with tempfile.TemporaryDirectory(prefix="invokeai_encoder_probe_") as work:
@@ -102,7 +103,7 @@ def _probe_decoder_config(width: int, height: int, fps: float) -> bytes | None:
finally:
writer.close()
layout = read_h264_layout(path)
- return layout.decoder_config if layout is not None else None
+ return layout.sample_entry if layout is not None else None
def write_stereo_wav(path: Path | str, samples: np.ndarray, sample_rate: int) -> None:
diff --git a/tests/app/invocations/test_video_concat_splice.py b/tests/app/invocations/test_video_concat_splice.py
index 0f83d656c7..6336aa0826 100644
--- a/tests/app/invocations/test_video_concat_splice.py
+++ b/tests/app/invocations/test_video_concat_splice.py
@@ -22,8 +22,10 @@ import imageio_ffmpeg
import numpy as np
import pytest
+from invokeai.app.invocations import video_concat
from invokeai.app.invocations.fields import VideoField
from invokeai.app.invocations.video_concat import VideoConcatInvocation
+from invokeai.app.services.session_processor.session_processor_common import CanceledException
from invokeai.app.util.aac_splice import PREROLL_FRAMES
from invokeai.app.util.h264_splice import read_h264_layout
from invokeai.app.util.mp4_metadata import find_box, write_mp4_tags
@@ -358,3 +360,74 @@ def test_spliced_soundtrack_matches_a_full_re_encode(tmp_path, monkeypatch, tran
assert got is not None and want is not None
n = min(got[0].shape[1], want[0].shape[1])
assert float(np.abs(got[0][:, :n] - want[0][:, :n]).max()) < 0.1
+
+
+ "tag",
+ [("-color_primaries", "bt2020", "-color_trc", "smpte2084", "-colorspace", "bt2020nc"), ("-aspect", "16:9")],
+ ids=["colr", "pasp"],
+)
+def test_first_clip_with_presentation_tags_is_re_encoded(tmp_path, tag):
+ """The joined track would present the re-encoded continuation with the copied head's colour
+ or aspect tags, which were never applied to it."""
+ _encode(tmp_path / "plain.mp4", _frames(100, seed=1))
+ a = tmp_path / "a.mp4"
+ subprocess.run(
+ [imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(tmp_path / "plain.mp4")]
+ + ["-c", "copy", *tag, str(a)],
+ check=True,
+ )
+ b = _encode(tmp_path / "b.mp4", _frames(40, seed=2))
+ out, context = _concat(tmp_path, [a, b], "out", transition="crossfade", transition_frames=2)
+ assert "Stream-copied" not in _logged(context)
+ layout = read_h264_layout(out)
+ assert layout is not None and b"colr" not in layout.sample_entry and b"pasp" not in layout.sample_entry
+ assert len(_decode(out)) == 138
+
+
[email protected]("stage", ["copy_frames", "mux_spliced_aac"])
+def test_cancellation_during_a_splice_saves_nothing(tmp_path, stage):
+ """Cancelling while a splice stage runs stops it — the stage itself raises, not just the
+ pre-save check — and nothing is saved."""
+ a = _encode(tmp_path / "a.mp4", _frames(100, seed=1), tone=440.0)
+ b = _encode(tmp_path / "b.mp4", _frames(40, seed=2), tone=660.0)
+ canceled = [False]
+ raised: list[BaseException] = []
+ real = getattr(video_concat, stage)
+
+ def cancel_then_run(*args, **kwargs):
+ canceled[0] = True
+ try:
+ return real(*args, **kwargs)
+ except BaseException as e:
+ raised.append(e)
+ raise
+
+ context = MagicMock()
+ context.videos.get_path.side_effect = lambda name: {"a": a, "b": b}[name]
+ context.util.is_canceled.side_effect = lambda: canceled[0]
+ node = VideoConcatInvocation(videos=[VideoField(video_name="a"), VideoField(video_name="b")], transition="cut")
+ with patch(f"invokeai.app.invocations.video_concat.{stage}", side_effect=cancel_then_run):
+ with pytest.raises(CanceledException):
+ node.invoke(context)
+ assert len(raised) == 1 and isinstance(raised[0], CanceledException)
+ context.videos.save.assert_not_called()
+
+
+def test_tkhd_display_size_does_not_leak_onto_the_join(tmp_path):
+ """ffmpeg turns a track header display size that disagrees with the coded size into a
+ pasp when it copies the track: the copied head would then stretch the new clip too."""
+ source = _encode(tmp_path / "plain.mp4", _frames(100, seed=1))
+ data = bytearray(source.read_bytes())
+ tkhd = data.find(b"tkhd")
+ assert data[tkhd + 4] == 0 # version 0: width at payload offset 76, as 16.16 fixed point
+ (width,) = struct.unpack_from(">I", data, tkhd + 4 + 76)
+ struct.pack_into(">I", data, tkhd + 4 + 76, width * 2)
+ a = tmp_path / "a.mp4"
+ a.write_bytes(bytes(data))
+ b = _encode(tmp_path / "b.mp4", _frames(40, seed=2))
+
+ out, context = _concat(tmp_path, [a, b], "out", transition="cut", transition_frames=0)
+ layout = read_h264_layout(out)
+ assert layout is not None and b"pasp" not in layout.sample_entry
+ assert len(_decode(out)) == 140
diff --git a/tests/app/invocations/test_video_frame_extract_range.py b/tests/app/invocations/test_video_frame_extract_range.py
index debbaa4f68..1cd2dec8df 100644
--- a/tests/app/invocations/test_video_frame_extract_range.py
+++ b/tests/app/invocations/test_video_frame_extract_range.py
@@ -342,3 +342,31 @@ def test_squeezed_join_falls_back_to_re_encoding(tmp_path: Path, monkeypatch: py
_, _, _, fps = probe_video(saved)
assert fps == pytest.approx(16.0, rel=1e-3)
assert len(_decode(saved)) == 65
+
+
+def test_cancellation_during_a_trim_splice_saves_nothing(tmp_path: Path) -> None:
+ source = tmp_path / "source.mp4"
+ _textured_source(source, 200)
+ canceled = [False]
+ raised: list[BaseException] = []
+ from invokeai.app.invocations import video_frame_extract_range
+
+ real = video_frame_extract_range.copy_frames
+
+ def cancel_then_copy(*args, **kwargs):
+ canceled[0] = True
+ try:
+ return real(*args, **kwargs)
+ except BaseException as e:
+ raised.append(e)
+ raise
+
+ context = MagicMock()
+ context.videos.get_path.return_value = source
+ context.util.is_canceled.side_effect = lambda: canceled[0]
+ invocation = ExtractVideoRangeInvocation(video=VideoField(video_name="source.mp4"), start_frame=31, end_frame=130)
+ with patch("invokeai.app.invocations.video_frame_extract_range.copy_frames", side_effect=cancel_then_copy):
+ with pytest.raises(CanceledException):
+ invocation.invoke(context)
+ assert len(raised) == 1 and isinstance(raised[0], CanceledException)
+ context.videos.save.assert_not_called()
diff --git a/tests/app/util/test_h264_splice.py b/tests/app/util/test_h264_splice.py
index 8612b155ad..4ec5191a79 100644
--- a/tests/app/util/test_h264_splice.py
+++ b/tests/app/util/test_h264_splice.py
@@ -6,16 +6,24 @@ with an edit list, and a metadata rotation is applied to decoded frames but carr
by a stream copy; either would misalign or misorient a join. Real ffmpeg throughout.
"""
+import os
+import struct
import subprocess
+import sys
+import time
+import tracemalloc
from pathlib import Path
+from unittest.mock import patch
import imageio.v2 as iio2
import imageio_ffmpeg
import numpy as np
import pytest
-from invokeai.app.util.h264_splice import read_h264_layout
-from invokeai.app.util.video_encoding import make_mp4_writer, writer_decoder_config
+from invokeai.app.services.session_processor.session_processor_common import CanceledException
+from invokeai.app.util.aac_splice import read_aac_layout
+from invokeai.app.util.h264_splice import read_h264_layout, run_ffmpeg
+from invokeai.app.util.video_encoding import make_mp4_writer, write_stereo_wav, writer_sample_entry
FPS = 16.0
@@ -52,7 +60,7 @@ def test_own_output_lists_exactly_the_decoded_frames(tmp_path: Path) -> None:
assert layout is not None
assert layout.sample_count == _decoded_count(path) == 70
assert layout.sync_samples[0] == 0 and len(layout.sync_samples) > 1
- assert layout.decoder_config == writer_decoder_config(96, 64, FPS)
+ assert layout.sample_entry == writer_sample_entry(96, 64, FPS)
def test_edit_list_trim_is_refused(tmp_path: Path) -> None:
@@ -101,3 +109,151 @@ def test_open_gop_i_frames_are_not_cut_points(tmp_path: Path) -> None:
layout = read_h264_layout(path)
assert layout is not None
assert layout.sync_samples == (0,)
+
+
+def _patch_box(data: bytearray, box: bytes, offset: int, value: bytes) -> None:
+ at = data.find(box)
+ assert at > 0, box
+ data[at + 4 + offset : at + 4 + offset + len(value)] = value
+
+
[email protected](sys.platform == "win32", reason="bounds the child's address space with RLIMIT_AS")
[email protected]("uniform_size", [0, 1], ids=["size-table", "uniform-size"])
+def test_oversized_sample_count_is_refused_without_allocating(tmp_path: Path, uniform_size: int) -> None:
+ """Uploads that are already H.264 MP4s are stored as-is, so the sample tables are the
+ uploader's. A count claiming ~4 billion samples, in a track with no sync-sample table
+ (so every sample would be a keyframe), must be refused before anything is sized by it."""
+ data = bytearray(_encode(tmp_path / "a.mp4", 40).read_bytes())
+ # stsz payload: version/flags, uniform sample size, sample count.
+ _patch_box(data, b"stsz", 4, struct.pack(">II", uniform_size, 0xFFFFFFF0))
+ # Hide the sync-sample table: an all-sync track is the case that sized a tuple by the count.
+ at = data.find(b"stss")
+ assert at > 0
+ data[at : at + 4] = b"free"
+ path = tmp_path / "hostile.mp4"
+ path.write_bytes(bytes(data))
+
+ script = (
+ "import resource, sys\n"
+ # Far below the ~32 GB a count-sized tuple would take, with room for numpy's import.
+ "resource.setrlimit(resource.RLIMIT_AS, (4 << 30, 4 << 30))\n"
+ "from pathlib import Path\n"
+ "from invokeai.app.util.h264_splice import read_h264_layout\n"
+ "print(read_h264_layout(Path(sys.argv[1])))\n"
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script, str(path)],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ # One BLAS thread: each one reserves address space the limit would otherwise spend.
+ env={**os.environ, "OPENBLAS_NUM_THREADS": "1", "OMP_NUM_THREADS": "1"},
+ )
+ assert result.returncode == 0, result.stderr[-2000:]
+ assert result.stdout.strip() == "None"
+
+
+ "tag",
+ [
+ ("-color_primaries", "bt2020", "-color_trc", "smpte2084", "-colorspace", "bt2020nc"),
+ ("-aspect", "16:9"),
+ ],
+ ids=["colr", "pasp"],
+)
+def test_presentation_tags_set_the_track_apart(tmp_path: Path, tag: tuple[str, ...]) -> None:
+ """A remux can add colour or pixel-aspect boxes while ``avcC`` stays byte-identical; a
+ joined track would present every frame with the copied part's tags."""
+ source = _encode(tmp_path / "a.mp4", 40)
+ subprocess.run(
+ [imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-loglevel", "error", "-i", str(source), "-c", "copy", *tag]
+ + [str(tmp_path / "tagged.mp4")],
+ check=True,
+ )
+ plain, tagged = read_h264_layout(source), read_h264_layout(tmp_path / "tagged.mp4")
+ assert plain is not None and tagged is not None
+ assert tagged.decoder_config == plain.decoder_config
+ assert tagged.sample_entry != writer_sample_entry(96, 64, FPS) == plain.sample_entry
+
+
+def test_cancellation_kills_a_running_ffmpeg(tmp_path: Path) -> None:
+ """A canceled node must not wait out a long copy: the child is killed and reaped."""
+ started = time.monotonic()
+ calls = [0]
+
+ def is_canceled() -> bool:
+ calls[0] += 1
+ return time.monotonic() - started > 0.5
+
+ children: list[subprocess.Popen] = []
+ real_popen = subprocess.Popen
+
+ def spawn(*args, **kwargs) -> subprocess.Popen:
+ children.append(real_popen(*args, **kwargs))
+ return children[-1]
+
+ # An endless synthetic source that only stops when killed.
+ with patch("invokeai.app.util.h264_splice.subprocess.Popen", side_effect=spawn):
+ with pytest.raises(CanceledException):
+ run_ffmpeg(["-f", "lavfi", "-i", "anullsrc", "-f", "null", "-"], "running forever", is_canceled)
+ assert time.monotonic() - started < 10
+ # The last child is the copy (locating the binary may spawn a version probe first).
+ assert children and children[-1].returncode is not None, "the child was left running"
+
+
+def _grow_sample_entry(data: bytes, handler: bytes, blob: bytes) -> bytes:
+ """Append ``blob`` inside the ``handler`` track's sample entry, growing every ancestor box.
+ The file must keep ``moov`` after ``mdat`` so no chunk offset moves."""
+
+ def boxes(start: int, end: int):
+ while start + 8 <= end:
+ size, kind = struct.unpack(">I4s", data[start : start + 8])
+ yield kind, start, size
+ start += size
+
+ _, moov, moov_size = next(b for b in boxes(0, len(data)) if b[0] == b"moov")
+ for kind, trak, trak_size in boxes(moov + 8, moov + moov_size):
+ if kind != b"trak":
+ continue
+ chain = [(moov, moov_size), (trak, trak_size)]
+ start, end = trak + 8, trak + trak_size
+ for name in (b"mdia", b"minf", b"stbl", b"stsd"):
+ _, at, size = next(b for b in boxes(start, end) if b[0] == name)
+ chain.append((at, size))
+ start, end = at + 8, at + size
+ hdlr = data.find(b"hdlr", trak, trak + trak_size)
+ if data[hdlr + 12 : hdlr + 16] != handler:
+ continue
+ _, entry, entry_size = next(boxes(start + 8, end))
+ chain.append((entry, entry_size))
+ grown = bytearray(data)
+ grown[entry + entry_size : entry + entry_size] = blob
+ for at, size in chain:
+ struct.pack_into(">I", grown, at, size + len(blob))
+ return bytes(grown)
+ raise AssertionError(f"no {handler!r} track")
+
+
[email protected]("handler", [b"vide", b"soun"])
+def test_sample_entry_stuffed_with_boxes_is_refused_cheaply(tmp_path: Path, handler: bytes) -> None:
+ """The sample entry is the uploader's: a flood of child boxes must be refused after a
+ bounded look, not collected (memory) or concatenated (quadratic time)."""
+ wav = tmp_path / "a.wav"
+ write_stereo_wav(wav, np.zeros((2, 48000), dtype=np.float32), 48000)
+ source = tmp_path / "a.mp4"
+ writer = make_mp4_writer(source, FPS, audio_path=wav)
+ for _ in range(16):
+ writer.append_data(np.zeros((64, 96, 3), dtype=np.uint8))
+ writer.close()
+ hostile = tmp_path / "hostile.mp4"
+ hostile.write_bytes(_grow_sample_entry(source.read_bytes(), handler, struct.pack(">I4s", 8, b"free") * 200_000))
+
+ read = read_h264_layout if handler == b"vide" else read_aac_layout
+ tracemalloc.start()
+ try:
+ assert read(hostile) is None
+ _, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+ # 200k boxes are 1.6 MB of file; reading a bounded handful of them allocates almost nothing.
+ assert peak < 1 << 20