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 reads and walks, cancel audio decodes

Lincoln Steinca9837f4f4a2
diff --git a/invokeai/app/invocations/video_concat.py b/invokeai/app/invocations/video_concat.py
index cb4dfe5126..0d7a48957a 100644
--- a/invokeai/app/invocations/video_concat.py
+++ b/invokeai/app/invocations/video_concat.py
@@ -281,7 +281,7 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
):
wav_path = work_dir / "audio.wav"
write_stereo_wav(wav_path, pcm, rate)
- mux_audio_into_video(tmp_path, wav_path, muxed_path)
+ mux_audio_into_video(tmp_path, wav_path, muxed_path, context.util.is_canceled)
source_path = muxed_path
duration = num_frames / output_fps
@@ -557,7 +557,7 @@ class VideoConcatInvocation(BaseInvocation, WithMetadata, WithBoard):
for path in paths:
if context.util.is_canceled():
raise CanceledException
- extracted.append(extract_audio_pcm(path))
+ extracted.append(extract_audio_pcm(path, is_canceled=context.util.is_canceled))
if all(item is None for item in extracted):
return None
if context.util.is_canceled():
diff --git a/invokeai/app/invocations/video_frame_extract_range.py b/invokeai/app/invocations/video_frame_extract_range.py
index b71a9e919b..c14a8189ee 100644
--- a/invokeai/app/invocations/video_frame_extract_range.py
+++ b/invokeai/app/invocations/video_frame_extract_range.py
@@ -299,7 +299,7 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
wav_tmp.close()
wav_path = Path(wav_tmp.name)
write_stereo_wav(wav_path, pcm, rate)
- mux_audio_into_video(tmp_path, wav_path, muxed_path)
+ mux_audio_into_video(tmp_path, wav_path, muxed_path, context.util.is_canceled)
source_path = muxed_path
out_duration = num_frames / output_fps
@@ -452,7 +452,7 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
copy_path = Path(work) / "source.mp4"
# 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, {})
+ write_mp4_tags(video_path, copy_path, {}, context.util.is_canceled)
# A cancellation that arrived during an uninterruptible stage must not be saved.
if context.util.is_canceled():
raise CanceledException
@@ -564,7 +564,7 @@ class ExtractVideoRangeInvocation(BaseInvocation, WithMetadata, WithBoard):
(matching what the retime does to the video).
"""
context.util.signal_progress("Extracting audio")
- extracted = extract_audio_pcm(video_path)
+ extracted = extract_audio_pcm(video_path, is_canceled=context.util.is_canceled)
if extracted is None:
return None
if context.util.is_canceled():
diff --git a/invokeai/app/util/aac_splice.py b/invokeai/app/util/aac_splice.py
index e31d140a02..c46216293a 100644
--- a/invokeai/app/util/aac_splice.py
+++ b/invokeai/app/util/aac_splice.py
@@ -47,7 +47,13 @@ PREROLL_FRAMES = 4
# start (a lead-in) or its end-of-stream flush (a tail).
EDGE_FRAMES = PREROLL_FRAMES + 1
_MAX_TOP_LEVEL_BOXES = 1024
+# Children walked per container (moov, trak, mdia, minf, stbl, edts): real ones hold about a
+# dozen, and the boxes are the uploader's, so a flood is given up on rather than scanned.
+_MAX_CHILD_BOXES = 64
_MAX_PACKETS = 1 << 24
+# A real AAC sample entry (esds with a two-to-five-byte AudioSpecificConfig, btrt) is well
+# under a hundred bytes.
+_MAX_SAMPLE_ENTRY_BYTES = 4 * 1024
# AudioSampleEntry fields before its child boxes (SampleEntry 8 + version-0 audio header 20).
_AUDIO_SAMPLE_ENTRY_HEADER = 28
_ES_DESCRIPTOR, _DECODER_CONFIG_DESCRIPTOR, _DECODER_SPECIFIC_INFO = 3, 4, 5
@@ -122,11 +128,11 @@ def read_aac_layout(path: Path) -> Optional[AacLayout]:
moov = find_box(fh, 0, fh.tell(), b"moov", max_boxes=_MAX_TOP_LEVEL_BOXES)
if moov is None:
return None
- for box_type, trak_start, trak_end in iter_boxes(fh, *moov):
+ for box_type, trak_start, trak_end in iter_boxes(fh, *moov, max_boxes=_MAX_CHILD_BOXES):
if box_type != b"trak":
continue
- mdia = find_box(fh, trak_start, trak_end, b"mdia")
- hdlr = find_box(fh, *mdia, b"hdlr") if mdia is not None else None
+ mdia = find_box(fh, trak_start, trak_end, b"mdia", max_boxes=_MAX_CHILD_BOXES)
+ hdlr = find_box(fh, *mdia, b"hdlr", max_boxes=_MAX_CHILD_BOXES) if mdia is not None else None
if hdlr is None or hdlr[0] + 12 > hdlr[1]:
continue
fh.seek(hdlr[0] + 8)
@@ -137,16 +143,16 @@ def read_aac_layout(path: Path) -> Optional[AacLayout]:
def _read_audio_track(fh: BinaryIO, trak: tuple[int, int], mdia: tuple[int, int]) -> Optional[AacLayout]:
- mdhd = find_box(fh, *mdia, b"mdhd")
- minf = find_box(fh, *mdia, b"minf")
- stbl = find_box(fh, *minf, b"stbl") if minf is not None else None
+ mdhd = find_box(fh, *mdia, b"mdhd", max_boxes=_MAX_CHILD_BOXES)
+ minf = find_box(fh, *mdia, b"minf", max_boxes=_MAX_CHILD_BOXES)
+ stbl = find_box(fh, *minf, b"stbl", max_boxes=_MAX_CHILD_BOXES) if minf is not None else None
if mdhd is None or stbl is None or mdhd[0] + 24 > mdhd[1]:
return None
fh.seek(mdhd[0])
fh.seek(mdhd[0] + (20 if fh.read(1)[0] == 1 else 12))
(sample_rate,) = struct.unpack(">I", fh.read(4))
- stsd = find_box(fh, *stbl, b"stsd")
+ stsd = find_box(fh, *stbl, b"stsd", max_boxes=_MAX_CHILD_BOXES)
if stsd is None or stsd[0] + 8 > stsd[1]:
return None
fh.seek(stsd[0] + 4)
@@ -156,6 +162,10 @@ def _read_audio_track(fh: BinaryIO, trak: tuple[int, int], mdia: tuple[int, int]
if not entries or entries[0][0] != b"mp4a":
return None
_, entry_start, entry_end = entries[0]
+ # Everything read below — the esds above all — lies inside the entry, which is the
+ # uploader's: bounded before any of it is read.
+ if entry_end - entry_start > _MAX_SAMPLE_ENTRY_BYTES:
+ return None
fh.seek(entry_start + 8)
if fh.read(2) != b"\x00\x00": # QuickTime v1/v2 sound entries lay their fields out differently
return None
@@ -179,7 +189,7 @@ def _read_audio_track(fh: BinaryIO, trak: tuple[int, int], mdia: tuple[int, int]
if len(decoder_config) == 5 and decoder_config.endswith(_NO_SBR_EXTENSION):
decoder_config = decoder_config[:2]
- stts = find_box(fh, *stbl, b"stts")
+ stts = find_box(fh, *stbl, b"stts", max_boxes=_MAX_CHILD_BOXES)
if stts is None or stts[0] + 8 > stts[1]:
return None
fh.seek(stts[0] + 4)
@@ -195,8 +205,8 @@ def _read_audio_track(fh: BinaryIO, trak: tuple[int, int], mdia: tuple[int, int]
if packet_count > _MAX_PACKETS:
return None
- edts = find_box(fh, *trak, b"edts")
- elst = find_box(fh, *edts, b"elst") if edts is not None else None
+ edts = find_box(fh, *trak, b"edts", max_boxes=_MAX_CHILD_BOXES)
+ elst = find_box(fh, *edts, b"elst", max_boxes=_MAX_CHILD_BOXES) if edts is not None else None
priming = 0
if elst is not None:
if elst[0] + 8 > elst[1]:
@@ -275,7 +285,7 @@ def _set_audio_edit(path: Path, media_time: int, samples: int, sample_rate: int)
with open(path, "r+b") as fh:
fh.seek(0, 2)
moov = find_box(fh, 0, fh.tell(), b"moov", max_boxes=_MAX_TOP_LEVEL_BOXES)
- mvhd = find_box(fh, *moov, b"mvhd") if moov is not None else None
+ mvhd = find_box(fh, *moov, b"mvhd", max_boxes=_MAX_CHILD_BOXES) if moov is not None else None
if mvhd is None:
raise SpliceError(f"{path.name} has no movie header")
fh.seek(mvhd[0])
@@ -285,12 +295,12 @@ def _set_audio_edit(path: Path, media_time: int, samples: int, sample_rate: int)
duration = round(samples * movie_timescale / sample_rate)
track_durations: list[int] = []
patched = False
- for box_type, trak_start, trak_end in iter_boxes(fh, *moov):
+ for box_type, trak_start, trak_end in iter_boxes(fh, *moov, max_boxes=_MAX_CHILD_BOXES):
if box_type != b"trak":
continue
- tkhd = find_box(fh, trak_start, trak_end, b"tkhd")
- mdia = find_box(fh, trak_start, trak_end, b"mdia")
- hdlr = find_box(fh, *mdia, b"hdlr") if mdia is not None else None
+ tkhd = find_box(fh, trak_start, trak_end, b"tkhd", max_boxes=_MAX_CHILD_BOXES)
+ mdia = find_box(fh, trak_start, trak_end, b"mdia", max_boxes=_MAX_CHILD_BOXES)
+ hdlr = find_box(fh, *mdia, b"hdlr", max_boxes=_MAX_CHILD_BOXES) if mdia is not None else None
if tkhd is None or hdlr is None:
raise SpliceError(f"{path.name} has a malformed track")
fh.seek(hdlr[0] + 8)
@@ -299,8 +309,8 @@ def _set_audio_edit(path: Path, media_time: int, samples: int, sample_rate: int)
wide = fh.read(1)[0] == 1
tkhd_duration_at, field = tkhd[0] + (28 if wide else 20), ">Q" if wide else ">I"
if is_target and not patched:
- edts = find_box(fh, trak_start, trak_end, b"edts")
- elst = find_box(fh, *edts, b"elst") if edts is not None else None
+ edts = find_box(fh, trak_start, trak_end, b"edts", max_boxes=_MAX_CHILD_BOXES)
+ elst = find_box(fh, *edts, b"elst", max_boxes=_MAX_CHILD_BOXES) if edts is not None else None
if elst is None:
raise SpliceError(f"{path.name}'s {handler.decode()} track has no edit list")
fh.seek(elst[0])
@@ -328,7 +338,7 @@ def _encode(
wav, adts = work / f"{name}.wav", work / f"{name}.aac"
write_stereo_wav(wav, pcm, sample_rate)
run_ffmpeg(["-i", str(wav), *AAC_ENCODE_ARGS, "-f", "adts", str(adts)], "encoding the new audio", is_canceled)
- decoded = extract_audio_pcm(adts)
+ decoded = extract_audio_pcm(adts, is_canceled=is_canceled)
if decoded is None:
raise SpliceError("the new audio decoded to nothing")
return _adts_frames(adts.read_bytes()), decoded[0]
@@ -398,7 +408,20 @@ def splice_soundtrack(
# The source's packets as ADTS, sliced by index: an ADTS frame per packet.
source_adts = work_dir / "source.aac"
run_ffmpeg(
- ["-i", str(source), "-map", "0:a:0", "-c", "copy", "-f", "adts", str(source_adts)],
+ # Only the packets up to the copied run's end are needed.
+ [
+ "-i",
+ str(source),
+ "-map",
+ "0:a:0",
+ "-c",
+ "copy",
+ "-frames:a",
+ str(end),
+ "-f",
+ "adts",
+ str(source_adts),
+ ],
f"copying the audio packets of {source.name}",
is_canceled,
)
@@ -463,7 +486,7 @@ def splice_soundtrack(
is_canceled,
)
_set_audio_edit(out_path, media_time, timeline.shape[1], sample_rate)
- muxed = extract_audio_pcm(out_path)
+ muxed = extract_audio_pcm(out_path, is_canceled=is_canceled)
except (SpliceError, AudioExtractionError, OSError) as e:
return f"it cannot be stream-copied ({e})"
diff --git a/invokeai/app/util/h264_splice.py b/invokeai/app/util/h264_splice.py
index 33712d45dc..af35c267a2 100644
--- a/invokeai/app/util/h264_splice.py
+++ b/invokeai/app/util/h264_splice.py
@@ -38,30 +38,31 @@ import shutil
import struct
import subprocess
import tempfile
-import time
from pathlib import Path
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
+from invokeai.app.util.video_audio import run_ffmpeg_process
# 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
+# Children walked per container (moov, trak, mdia, minf, stbl, edts): real ones hold about a
+# dozen, and the boxes are the uploader's, so a flood is given up on rather than scanned.
+_MAX_CHILD_BOXES = 64
# 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.
+# A real sample entry holds a handful of boxes (avcC, btrt, colr, pasp...) in a few hundred
+# bytes; more of either is hostile, and refused before any of it is read.
_MAX_ENTRY_CHILDREN = 32
+_MAX_SAMPLE_ENTRY_BYTES = 64 * 1024
# 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
@@ -121,30 +122,30 @@ def read_h264_layout(path: Path) -> Optional[H264Layout]:
moov = find_box(fh, 0, file_size, b"moov", max_boxes=_MAX_TOP_LEVEL_BOXES)
if moov is None:
return None
- for box_type, trak_start, trak_end in iter_boxes(fh, *moov):
+ for box_type, trak_start, trak_end in iter_boxes(fh, *moov, max_boxes=_MAX_CHILD_BOXES):
if box_type != b"trak":
continue
- mdia = find_box(fh, trak_start, trak_end, b"mdia")
+ mdia = find_box(fh, trak_start, trak_end, b"mdia", max_boxes=_MAX_CHILD_BOXES)
if mdia is None:
continue
- hdlr = find_box(fh, *mdia, b"hdlr")
+ hdlr = find_box(fh, *mdia, b"hdlr", max_boxes=_MAX_CHILD_BOXES)
if hdlr is None or hdlr[0] + 12 > hdlr[1]:
continue
fh.seek(hdlr[0] + 8)
if fh.read(4) != b"vide":
continue
# First video track only: that is the stream every ffmpeg call here maps (0:v:0).
- minf = find_box(fh, *mdia, b"minf")
- stbl = find_box(fh, *minf, b"stbl") if minf is not None else None
- movie_timescale = _read_timescale(fh, find_box(fh, *moov, b"mvhd"))
- media_timescale = _read_timescale(fh, find_box(fh, *mdia, b"mdhd"))
+ minf = find_box(fh, *mdia, b"minf", max_boxes=_MAX_CHILD_BOXES)
+ stbl = find_box(fh, *minf, b"stbl", max_boxes=_MAX_CHILD_BOXES) if minf is not None else None
+ movie_timescale = _read_timescale(fh, find_box(fh, *moov, b"mvhd", max_boxes=_MAX_CHILD_BOXES))
+ media_timescale = _read_timescale(fh, find_box(fh, *mdia, b"mdhd", max_boxes=_MAX_CHILD_BOXES))
if stbl is None or movie_timescale is None or media_timescale is None:
return None
- if not _has_identity_matrix(fh, find_box(fh, trak_start, trak_end, b"tkhd")):
+ if not _has_identity_matrix(fh, find_box(fh, trak_start, trak_end, b"tkhd", max_boxes=_MAX_CHILD_BOXES)):
return None
- edts = find_box(fh, trak_start, trak_end, b"edts")
+ edts = find_box(fh, trak_start, trak_end, b"edts", max_boxes=_MAX_CHILD_BOXES)
if edts is not None and not _edits_show_every_sample(
- fh, find_box(fh, *edts, b"elst"), stbl, movie_timescale, media_timescale
+ fh, find_box(fh, *edts, b"elst", max_boxes=_MAX_CHILD_BOXES), stbl, movie_timescale, media_timescale
):
return None
return _read_video_stbl(fh, *stbl)
@@ -208,7 +209,7 @@ def _edits_show_every_sample(
first_delta = runs[0][1]
first_offset = 0
- ctts = find_box(fh, *stbl, b"ctts")
+ ctts = find_box(fh, *stbl, b"ctts", max_boxes=_MAX_CHILD_BOXES)
if ctts is not None:
if ctts[0] + 16 > ctts[1]:
return False
@@ -223,7 +224,7 @@ def _edits_show_every_sample(
def _read_stts(fh: BinaryIO, stbl: tuple[int, int]) -> Optional[list[tuple[int, int]]]:
"""The ``(sample_count, sample_delta)`` runs of the time-to-sample table."""
- stts = find_box(fh, *stbl, b"stts")
+ stts = find_box(fh, *stbl, b"stts", max_boxes=_MAX_CHILD_BOXES)
if stts is None or stts[0] + 8 > stts[1]:
return None
fh.seek(stts[0] + 4)
@@ -260,8 +261,11 @@ 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")
+ stsc = find_box(fh, *stbl, b"stsc", max_boxes=_MAX_CHILD_BOXES)
+ stco, co64 = (
+ find_box(fh, *stbl, b"stco", max_boxes=_MAX_CHILD_BOXES),
+ find_box(fh, *stbl, b"co64", max_boxes=_MAX_CHILD_BOXES),
+ )
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)):
@@ -326,8 +330,8 @@ def _is_idr(fh: BinaryIO, offset: int, size: int, length_size: int) -> bool:
def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H264Layout]:
stbl = (stbl_start, stbl_end)
- stsd = find_box(fh, *stbl, b"stsd")
- stsz = find_box(fh, *stbl, b"stsz")
+ stsd = find_box(fh, *stbl, b"stsd", max_boxes=_MAX_CHILD_BOXES)
+ stsz = find_box(fh, *stbl, b"stsz", max_boxes=_MAX_CHILD_BOXES)
if stsd is None or stsz is None:
return None
@@ -340,7 +344,15 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
if not entries or entries[0][0] != b"avc1":
return None
_, entry_start, entry_end = entries[0]
- avcc = find_box(fh, entry_start + _VISUAL_SAMPLE_ENTRY_HEADER, entry_end, b"avcC")
+ # Everything read below lies inside the entry, so one size bound covers every child box.
+ if entry_end - entry_start > _MAX_SAMPLE_ENTRY_BYTES:
+ return None
+ 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
+ avcc = next(((start, end) for child, start, end in children if child == b"avcC"), None)
if avcc is None or avcc[0] >= avcc[1]:
return None
fh.seek(avcc[0])
@@ -351,11 +363,6 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
# 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
for child, child_start, child_end in children:
if child != b"btrt":
fh.seek(child_start)
@@ -372,7 +379,7 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
return None
sample_count = len(sizes)
- stss = find_box(fh, *stbl, b"stss")
+ stss = find_box(fh, *stbl, b"stss", max_boxes=_MAX_CHILD_BOXES)
if stss is None:
# 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.
@@ -416,38 +423,16 @@ def _read_video_stbl(fh: BinaryIO, stbl_start: int, stbl_end: int) -> Optional[H
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.
+ ``is_canceled`` stops the child promptly and raises CanceledException (see
+ ``run_ffmpeg_process``), 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],
- stdin=subprocess.DEVNULL,
- stdout=subprocess.DEVNULL,
- stderr=stderr,
- )
- 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:]}")
+ try:
+ proc = run_ffmpeg_process(args, SPLICE_TIMEOUT_SECONDS, is_canceled)
+ except subprocess.TimeoutExpired as e:
+ raise SpliceError(f"ffmpeg timed out {description}") from e
+ if proc.returncode != 0:
+ message = proc.stderr.decode("utf-8", errors="replace").strip()
+ raise SpliceError(f"ffmpeg failed {description}: {message[-500:]}")
def copy_frames(
diff --git a/invokeai/app/util/mp4_metadata.py b/invokeai/app/util/mp4_metadata.py
index d4b1a9759d..1074ff6b75 100644
--- a/invokeai/app/util/mp4_metadata.py
+++ b/invokeai/app/util/mp4_metadata.py
@@ -25,9 +25,7 @@ import subprocess
import tempfile
from collections.abc import Collection, Iterator, Mapping
from pathlib import Path
-from typing import BinaryIO, Optional
-
-import imageio_ffmpeg
+from typing import BinaryIO, Callable, Optional
# A single tag is a JSON string the app itself produced; a graph JSON is the largest and
# runs to a few hundred KiB. The cap exists only so a hostile file cannot make the reader
@@ -52,10 +50,6 @@ class Mp4MetadataError(RuntimeError):
"""The MP4 could not be rewritten with the requested tags."""
-def _ffmpeg_exe() -> str:
- return imageio_ffmpeg.get_ffmpeg_exe()
-
-
def iter_boxes(fh: BinaryIO, start: int, end: int, max_boxes: Optional[int] = None) -> Iterator[tuple[bytes, int, int]]:
"""Yield ``(type, payload_start, payload_end)`` for each box in ``[start, end)``.
@@ -220,7 +214,9 @@ def _escape_ffmetadata(value: str) -> str:
)
-def write_mp4_tags(src: Path, dst: Path, tags: Mapping[str, str]) -> None:
+def write_mp4_tags(
+ src: Path, dst: Path, tags: Mapping[str, str], is_canceled: Optional[Callable[[], bool]] = None
+) -> None:
"""Write ``dst`` = ``src``'s first video stream and every audio stream, stream-copied, with
``tags`` as the file's keyed metadata (replacing any global tags ``src`` had). An empty
mapping therefore strips ``src``'s global tags.
@@ -243,12 +239,11 @@ def write_mp4_tags(src: Path, dst: Path, tags: Mapping[str, str]) -> None:
ffmeta_path = Path(ffmeta.name)
try:
try:
- proc = subprocess.run(
+ # Imported here: video_audio is a heavier module than this one's other callers need.
+ from invokeai.app.util.video_audio import run_ffmpeg_process
+
+ proc = run_ffmpeg_process(
[
- _ffmpeg_exe(),
- "-y",
- "-loglevel",
- "error",
"-i",
str(src),
"-i",
@@ -267,8 +262,8 @@ def write_mp4_tags(src: Path, dst: Path, tags: Mapping[str, str]) -> None:
"mp4",
str(dst),
],
- capture_output=True,
- timeout=REMUX_TIMEOUT_SECONDS,
+ REMUX_TIMEOUT_SECONDS,
+ is_canceled,
)
except subprocess.TimeoutExpired as e:
raise Mp4MetadataError(f"ffmpeg timed out writing metadata into {dst.name}") from e
diff --git a/invokeai/app/util/video_audio.py b/invokeai/app/util/video_audio.py
index eca1db2828..2a28b259d1 100644
--- a/invokeai/app/util/video_audio.py
+++ b/invokeai/app/util/video_audio.py
@@ -18,11 +18,19 @@ video).
import subprocess
import tempfile
+import time
import wave
from pathlib import Path
+from typing import Callable, Optional
import numpy as np
+from invokeai.app.services.session_processor.session_processor_common import CanceledException
+
+# How often a running ffmpeg child is checked for cancellation, and how much of its stderr is kept.
+_CANCEL_POLL_SECONDS = 0.1
+_STDERR_TAIL_BYTES = 8 * 1024
+
# How every soundtrack the app writes is encoded; ``aac_splice`` matches a spliced tail to it.
# Perceptual noise substitution is off: the decoder fills those bands from a random generator
# whose state carries across packets, so a freshly encoded lead-in that used it would change
@@ -37,11 +45,50 @@ def _ffmpeg_exe() -> str:
return imageio_ffmpeg.get_ffmpeg_exe()
+def run_ffmpeg_process(
+ args: list[str], timeout: float, is_canceled: Optional[Callable[[], bool]] = None
+) -> subprocess.CompletedProcess[bytes]:
+ """Run the bundled ffmpeg (quiet, overwriting) with ``args``; returns its exit status and stderr.
+
+ The child is polled rather than waited on, so ``is_canceled`` can stop it: a cancellation
+ (checked before it starts, too) kills and reaps it and raises CanceledException, and
+ outliving ``timeout`` kills and reaps it and raises ``subprocess.TimeoutExpired``. A
+ canceled node therefore never waits on a long decode, encode or copy.
+ """
+ if is_canceled is not None and is_canceled():
+ raise CanceledException
+ command = [_ffmpeg_exe(), "-y", "-loglevel", "error", *args]
+ with tempfile.TemporaryFile() as stderr:
+ proc = subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=stderr)
+ deadline = time.monotonic() + timeout
+ 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 subprocess.TimeoutExpired(command, timeout)
+ finally:
+ if proc.returncode is None:
+ proc.kill()
+ proc.wait()
+ # Only the tail is ever reported; a decoder logging per packet could write a great deal.
+ stderr.seek(0, 2)
+ stderr.seek(max(0, stderr.tell() - _STDERR_TAIL_BYTES))
+ return subprocess.CompletedProcess(command, proc.returncode, b"", stderr.read())
+
+
class AudioExtractionError(RuntimeError):
"""ffmpeg failed to decode an audio track for a reason other than 'no audio stream'."""
-def extract_audio_pcm(video_path: Path, *, float_pcm: bool = False) -> tuple[np.ndarray, int] | None:
+def extract_audio_pcm(
+ video_path: Path, *, float_pcm: bool = False, is_canceled: Optional[Callable[[], bool]] = None
+) -> tuple[np.ndarray, int] | None:
"""Decode ``video_path``'s first audio stream to float32 stereo PCM at its native sample rate.
Returns ``(samples, sample_rate)`` with ``samples`` shaped ``(2, n)`` in [-1, 1], or
@@ -52,6 +99,8 @@ def extract_audio_pcm(video_path: Path, *, float_pcm: bool = False) -> tuple[np.
With ``float_pcm=True`` the decode goes through ``pcm_f32le`` instead of ``pcm_s16le``,
preserving the container's float samples without an int16 quantization. MiniMax H3
reference conditioning requires this: upstream conditions on the decoder's float output.
+
+ ``is_canceled`` stops the decode promptly (see :func:`run_ffmpeg_process`).
"""
suffix = ".f32" if float_pcm else ".wav"
with tempfile.NamedTemporaryFile(prefix="invokeai_audio_extract_", suffix=suffix, delete=False) as tmp:
@@ -63,24 +112,10 @@ def extract_audio_pcm(video_path: Path, *, float_pcm: bool = False) -> tuple[np.
)
try:
try:
- proc = subprocess.run(
- [
- _ffmpeg_exe(),
- "-y",
- "-loglevel",
- "error",
- "-i",
- str(video_path),
- "-map",
- "0:a:0?",
- "-vn",
- "-ac",
- "2",
- *codec_args,
- str(out_path),
- ],
- capture_output=True,
+ proc = run_ffmpeg_process(
+ ["-i", str(video_path), "-map", "0:a:0?", "-vn", "-ac", "2", *codec_args, str(out_path)],
timeout=600,
+ is_canceled=is_canceled,
)
except subprocess.TimeoutExpired as e:
raise AudioExtractionError(f"ffmpeg timed out extracting audio from {video_path.name}") from e
@@ -164,13 +199,16 @@ def resample_linear(samples: np.ndarray, num_output_samples: int) -> np.ndarray:
return np.stack([np.interp(positions, grid, samples[c]) for c in range(2)]).astype(np.float32)
-def mux_audio_into_video(video_path: Path, wav_path: Path, output_path: Path) -> None:
+def mux_audio_into_video(
+ video_path: Path, wav_path: Path, output_path: Path, is_canceled: Optional[Callable[[], bool]] = None
+) -> None:
"""Produce ``output_path`` = ``video_path``'s streams with ``wav_path`` as an AAC track.
The video stream is copied bit-exactly (no re-encode); only the audio is encoded.
+ ``is_canceled`` stops the mux promptly (see :func:`run_ffmpeg_process`).
"""
try:
- proc = _run_mux(video_path, wav_path, output_path)
+ proc = _run_mux(video_path, wav_path, output_path, is_canceled)
except subprocess.TimeoutExpired as e:
raise AudioExtractionError(f"ffmpeg timed out muxing audio into {output_path.name}") from e
if proc.returncode != 0:
@@ -178,13 +216,11 @@ def mux_audio_into_video(video_path: Path, wav_path: Path, output_path: Path) ->
raise AudioExtractionError(f"ffmpeg could not mux audio into {output_path.name}: {stderr.strip()[-500:]}")
-def _run_mux(video_path: Path, wav_path: Path, output_path: Path) -> subprocess.CompletedProcess[bytes]:
- return subprocess.run(
+def _run_mux(
+ video_path: Path, wav_path: Path, output_path: Path, is_canceled: Optional[Callable[[], bool]]
+) -> subprocess.CompletedProcess[bytes]:
+ return run_ffmpeg_process(
[
- _ffmpeg_exe(),
- "-y",
- "-loglevel",
- "error",
"-i",
str(video_path),
"-i",
@@ -198,6 +234,6 @@ def _run_mux(video_path: Path, wav_path: Path, output_path: Path) -> subprocess.
*AAC_ENCODE_ARGS,
str(output_path),
],
- capture_output=True,
timeout=600,
+ is_canceled=is_canceled,
)
diff --git a/tests/app/invocations/test_video_concat_splice.py b/tests/app/invocations/test_video_concat_splice.py
index b108ff82d6..2bb2a80f37 100644
--- a/tests/app/invocations/test_video_concat_splice.py
+++ b/tests/app/invocations/test_video_concat_splice.py
@@ -11,6 +11,7 @@ cannot be spliced losslessly still join correctly by re-encoding.
Real ffmpeg (the imageio-ffmpeg bundled binary) encodes and decodes throughout.
"""
+import importlib
import shutil
import struct
import subprocess
@@ -22,7 +23,6 @@ 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
@@ -385,7 +385,16 @@ def test_first_clip_with_presentation_tags_is_re_encoded(tmp_path, tag):
assert len(_decode(out)) == 138
[email protected]("stage", ["copy_frames", "splice_soundtrack"])
+ "stage",
+ [
+ "invokeai.app.invocations.video_concat.copy_frames",
+ "invokeai.app.invocations.video_concat.splice_soundtrack",
+ # The audio decodes: an input's soundtrack, and the splice's own validation decodes.
+ "invokeai.app.invocations.video_concat.extract_audio_pcm",
+ "invokeai.app.util.aac_splice.extract_audio_pcm",
+ ],
+)
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."""
@@ -393,7 +402,8 @@ def test_cancellation_during_a_splice_saves_nothing(tmp_path, stage):
b = _encode(tmp_path / "b.mp4", _frames(40, seed=2), tone=660.0)
canceled = [False]
raised: list[BaseException] = []
- real = getattr(video_concat, stage)
+ module, name = stage.rsplit(".", 1)
+ real = getattr(importlib.import_module(module), name)
def cancel_then_run(*args, **kwargs):
canceled[0] = True
@@ -407,7 +417,7 @@ def test_cancellation_during_a_splice_saves_nothing(tmp_path, stage):
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 patch(stage, side_effect=cancel_then_run):
with pytest.raises(CanceledException):
node.invoke(context)
assert len(raised) == 1 and isinstance(raised[0], CanceledException)
diff --git a/tests/app/util/test_h264_splice.py b/tests/app/util/test_h264_splice.py
index 4ec5191a79..3a4aa1daae 100644
--- a/tests/app/util/test_h264_splice.py
+++ b/tests/app/util/test_h264_splice.py
@@ -6,6 +6,7 @@ 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 io
import os
import struct
import subprocess
@@ -201,13 +202,23 @@ def test_cancellation_kills_a_running_ffmpeg(tmp_path: Path) -> None:
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 _grow_sample_entry(
+ data: bytes,
+ handler: bytes,
+ blob: bytes,
+ first: bool = False,
+ inside: bytes | None = None,
+ in_stbl: bool = False,
+) -> bytes:
+ """Insert ``blob`` inside the ``handler`` track's sample entry — after its other child boxes,
+ before them if ``first``, or at the end of its ``inside`` child box — or, with ``in_stbl``,
+ at the start of the track's sample table, 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])
+ assert size >= 8, "the fixture must be a well-formed MP4"
yield kind, start, size
start += size
@@ -224,20 +235,33 @@ def _grow_sample_entry(data: bytes, handler: bytes, blob: bytes) -> bytes:
hdlr = data.find(b"hdlr", trak, trak + trak_size)
if data[hdlr + 12 : hdlr + 16] != handler:
continue
+ grown = bytearray(data)
+ if in_stbl:
+ # Ahead of stsd and every other table.
+ chain.pop()
+ stbl_at = chain[-1][0]
+ grown[stbl_at + 8 : stbl_at + 8] = blob
+ for box_at, size in chain:
+ struct.pack_into(">I", grown, box_at, size + len(blob))
+ return bytes(grown)
_, entry, entry_size = next(boxes(start + 8, end))
chain.append((entry, entry_size))
- grown = bytearray(data)
- grown[entry + entry_size : entry + entry_size] = blob
+ # Child boxes follow the entry's box header and fixed fields: 78 bytes for avc1, 28 for mp4a.
+ children_at = entry + 8 + (78 if handler == b"vide" else 28)
+ at = children_at if first else entry + entry_size
+ if inside is not None:
+ _, child, child_size = next(b for b in boxes(children_at, entry + entry_size) if b[0] == inside)
+ chain.append((child, child_size))
+ at = child + child_size
+ grown[at:at] = 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)."""
+def _audio_clip(tmp_path: Path) -> Path:
+ """A clip of this app's own encoding, with a soundtrack, and moov after mdat."""
wav = tmp_path / "a.wav"
write_stereo_wav(wav, np.zeros((2, 48000), dtype=np.float32), 48000)
source = tmp_path / "a.mp4"
@@ -245,6 +269,14 @@ def test_sample_entry_stuffed_with_boxes_is_refused_cheaply(tmp_path: Path, hand
for _ in range(16):
writer.append_data(np.zeros((64, 96, 3), dtype=np.uint8))
writer.close()
+ return source
+
+
[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)."""
+ source = _audio_clip(tmp_path)
hostile = tmp_path / "hostile.mp4"
hostile.write_bytes(_grow_sample_entry(source.read_bytes(), handler, struct.pack(">I4s", 8, b"free") * 200_000))
@@ -257,3 +289,76 @@ def test_sample_entry_stuffed_with_boxes_is_refused_cheaply(tmp_path: Path, hand
tracemalloc.stop()
# 200k boxes are 1.6 MB of file; reading a bounded handful of them allocates almost nothing.
assert peak < 1 << 20
+
+
+ "handler,inside", [(b"vide", None), (b"vide", b"avcC"), (b"soun", b"esds")], ids=["free", "avcC", "esds"]
+)
+def test_oversized_sample_entry_is_refused_unread(tmp_path: Path, handler: bytes, inside: bytes | None) -> None:
+ """One huge child box — a free box, or the decoder config padded out — must be refused by
+ size, not read into memory."""
+ source = _audio_clip(tmp_path)
+ hostile = tmp_path / "hostile.mp4"
+ padding = 16 << 20
+ blob = bytes(padding) if inside else struct.pack(">I4s", 8 + padding, b"free") + bytes(padding)
+ hostile.write_bytes(_grow_sample_entry(source.read_bytes(), handler, blob, inside=inside))
+ 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()
+ assert peak < 1 << 20
+
+
+def test_box_flood_before_avcc_is_not_scanned(tmp_path: Path) -> None:
+ """``avcC`` is found among a bounded number of child boxes, so a flood placed before it is
+ refused after a fixed look rather than walked in full."""
+ source = _audio_clip(tmp_path)
+ hostile = tmp_path / "hostile.mp4"
+ hostile.write_bytes(
+ _grow_sample_entry(source.read_bytes(), b"vide", struct.pack(">I4s", 8, b"free") * 2_000_000, first=True)
+ )
+ seeks = [0]
+
+ class CountingFile(io.BufferedReader):
+ def seek(self, *args):
+ seeks[0] += 1
+ return super().seek(*args)
+
+ def counting_open(path, mode="r", *args, **kwargs):
+ return CountingFile(io.FileIO(path, "r"))
+
+ # The flood really sits inside the sample entry, ahead of its avcC.
+ data = hostile.read_bytes()
+ entry = data.find(b"avc1")
+ assert entry < data.find(b"\x00\x00\x00\x08free", entry) < data.find(b"avcC", entry)
+ with patch("invokeai.app.util.h264_splice.open", counting_open, create=True):
+ assert read_h264_layout(hostile) is None
+ # Walking the flood would take a seek per box: two million of them.
+ assert seeks[0] < 10_000
+
+
[email protected]("handler", [b"vide", b"soun"])
+def test_box_flood_in_a_container_is_not_scanned(tmp_path: Path, handler: bytes) -> None:
+ """Every container walk (moov, trak, mdia, minf, stbl) stops after a fixed number of boxes:
+ a flood ahead of the sample tables would otherwise be walked once per table looked up."""
+ source = _audio_clip(tmp_path)
+ hostile = tmp_path / "hostile.mp4"
+ hostile.write_bytes(
+ _grow_sample_entry(source.read_bytes(), handler, struct.pack(">I4s", 8, b"free") * 200_000, in_stbl=True)
+ )
+ module = "h264_splice" if handler == b"vide" else "aac_splice"
+ read = read_h264_layout if handler == b"vide" else read_aac_layout
+ seeks = [0]
+
+ class CountingFile(io.BufferedReader):
+ def seek(self, *args):
+ seeks[0] += 1
+ return super().seek(*args)
+
+ with patch(f"invokeai.app.util.{module}.open", lambda path, *a, **k: CountingFile(io.FileIO(path)), create=True):
+ assert read(hostile) is None
+ # Walking the flood would take a seek per box per lookup: hundreds of thousands at least.
+ assert seeks[0] < 10_000