Repository navigation
[format][python] Replace persisted keyframe indexes with MP4 metadata - #10905
JingsongLi merged 7 commits into
Conversation
|
Thanks for the PR! The page directory looks like the right direction to me, and from my local tests most of the improvement comes from it. But I have some concerns about the format design, mainly the versioning and the compression part. 1. The v1 layout changes again without bumping the version This is the third v1 layout within one month (#9831: On the read path I know none of these commits is released yet, but people building from master may already have such data. Since we already have a version byte, I think we should just use version 2 here (it costs nothing), and let readers report "unsupported keyframe index version" instead of misparsing. Maybe also reserve a flags or header-length field, so next time we don't need to break the layout again. 2. Most of the gain comes from the directory, not compression I counted GETs with an instrumented
Compression reduces the bytes by ~3x, but the GET count is the same. On OSS the latency is mostly decided by the number of requests; with a simple model (15 ms per GET + 100 MB/s, my assumption, not measured) it's about 7.8 s vs 7.4 s. For storage, the index is 24 bytes per keyframe while one keyframe usually covers tens of KB of video, so the saving is very small. Also, once a codec is in the spec it's hard to change, and I'm not sure zlib over row-major int64 triples is a good choice. On the same data (GOP 2):
So my suggestion is to split this PR: land the directory with codec 0 first, and discuss compression separately. If we keep compression, maybe define the codec as per-column delta encoding. It would also be great if the benchmark could show the directory and compression separately. 3. Unsupported version / codec cannot be distinguished from corruption If we add codec 2 later, old readers will fail with
4. Directory caches can be simpler (minor) Python keeps three caches: directory blocks (512 records, LRU of 2), descriptors (LRU of 512) and pages. The directory for 1M keyframes is only 16.6 KB and is usually already in the 64 KB prefix. If we read the whole directory at open, the binary search needs no I/O and the first two caches can be removed. I also left a few smaller comments inline (page size wording in the spec, the eager-loading threshold, and the temp file in the Java validator). WDYT? |
| Each page holds 4,096 uncompressed `(frame ordinal, PTS, packet position)` int64 triples | ||
| and their 4-byte CRC32; the last page may be shorter. Page `p` starts at | ||
| `21 + 16 * metadata_count + p * 98308`. | ||
| Each page holds up to 4,096 `(frame ordinal, PTS, packet position)` int64 triples, |
There was a problem hiding this comment.
This says "up to 4,096", but both readers assume every page except the last has exactly 4,096 entries: they compute the entry count as min(4096, count - p * 4096) and locate the page by divmod(index, 4096). So a writer which follows the spec and writes variable-size pages (e.g. a future Rust writer) will be rejected.
Maybe say "exactly 4,096 except the last page" here, or store page_entries in the header. The directory already has the first ordinal of each page, so variable-size pages are not hard to support.
| prefix = read_at(0, min(length, cls.HEADER.size + _PagedKeyframes.PAGE_BYTES + 4)) | ||
| if len(prefix) != min(length, cls.HEADER.size + _PagedKeyframes.PAGE_BYTES + 4): | ||
| # Small indexes use one request; larger indexes retain only a bounded prefix. | ||
| prefix_size = length if length <= _IndexedKeyframes.EAGER_BYTES else 64 * 1024 |
There was a problem hiding this comment.
Here the whole index is read when the encoded length <= 2 MiB, but load_small() only goes eager when the decoded size count * 24 <= 2 MiB. For compressed indexes in between, the whole encoded index stays in prefix, and pages are still decoded into the 1 MiB page cache. With 200K keyframes I see 1.58 MB held + 0.97 MB page cache, and it's not eager.
So the memory per open index goes from ~1.1 MB to ~2.5 MB, multiplied by max_open_videos (16 by default) and the number of DataLoader workers. Maybe use one threshold on the decoded size, or document this case.
| crc.update(page, 0, bytes); | ||
| if (crc.getValue() != expected) { | ||
| throw invalid("page checksum"); | ||
| Path path = Files.createTempFile("paimon-video-directory-", ".tmp"); |
There was a problem hiding this comment.
This creates a temp file for every index only to read the directory twice. The caller's spool in VideoFormatWriter is already a RandomAccessFile, so maybe we can pass a seekable input here, or just keep the directory in memory. It is bounded by the index length, and only about 16.6 KB for 1M keyframes.
|
Please just use DeltaVarintCodec, and let’s redesign the fields for the Video entity; ensure that every field serves a purpose, and remove any that are unnecessary. |
| if version == 1: | ||
| return cls._open_v1(read, length, payload_length, prefix) |
There was a problem hiding this comment.
Indexes written by master since #10891 (Oct 31) also carry version byte 1, so they take this branch and are parsed as the 2.1.0 layout, with every field after the header shifted by 4 bytes. Opening one raises a plain ValueError: Video metadata range is outside the video payload. rather than UnsupportedVideoIndex. As a result:
VideoFrameCollatordoesn't fall back to scanning.- The copy path in both writers rejects it, so compaction fails. That path is
video_format_writer.py:216, plusVideoFormatWriter.java:343, which goes through the sameversion == 1branch atVideoKeyframeIndex.java:61.
The layout was never released, but anything built from master since then writes it. Could we recognize it and raise UnsupportedVideoIndex (or UnsupportedIndexException in Java)? Its length is exactly 21 + 16 * metadata_count + 24 * count + 4 * pages, and the CRC32 of the first page can confirm it. Then it gets scanned and survives rewrite like any other unknown index.
| _validate_entries(raw, payload_length, initial=True) | ||
| result = cls.__new__(cls) | ||
| result.metadata_ranges = ranges | ||
| result.keyframes = cls.ENTRY.iter_unpack(raw) |
There was a problem hiding this comment.
This routes a released v1 index through the keyframes setter. So every open spools the entries to a temp file and serves them through _PagedKeyframes plus a Python bisect over _Ordinals. The page cache holds 10 pages, while a full v1 index has 16.
Measured with 65,536 keyframes:
| 2.1.0 | this PR | |
|---|---|---|
| open | 37 ms | 88 ms + 1 temp file |
preceding() |
0.5 µs | 207 µs |
The same keyframes stored as eager v2 take 2.5 µs per lookup. A decoded v1 index is at most 1.5 MiB, so raw could stay in memory and reuse the eager path with searchsorted, with no temp file.
56c990a to
ba80cc3
Compare
1aaaae6 to
d5e308a
Compare
d5e308a to
e1f6a99
Compare
JingsongLi
left a comment
There was a problem hiding this comment.
Two findings on video track selection and native reader compatibility.
| raise ValueError("Truncated MP4 handler.") | ||
| if bytes(handler[8:12]) == b"vide": | ||
| if selected is not None: | ||
| raise ValueError("Multiple video tracks require exact mode.") |
There was a problem hiding this comment.
[P1] Preserve the video track when falling back. LeRobot assigns frame ordinals from the first video stream. Rejecting a second video track here sends the default backend to TorchCodec exact mode without a stream_index, so TorchCodec can select a different stream. I reproduced this with a two-track MP4 whose second track is marked as default. Reading frame 0 through the .video writer and reader returned the first track's red frame on the base commit and the second track's blue frame on this PR. Both tracks have the same dimensions, so the shape check passes. Please keep the first video stream in the fallback path and add a regression test with a different default track.
| _NATIVE_READ_FILE_SUFFIXES = tuple('.%s' % file_format for file_format in _NATIVE_READ_FILE_FORMATS) | ||
| _NATIVE_BLOB_FILE_SUFFIXES = ('.blob', '.video') | ||
| # Released native readers use the previous five-array layout. | ||
| _NATIVE_BLOB_FILE_SUFFIXES = ('.blob',) |
There was a problem hiding this comment.
[P2] Land Rust support for the new .video layout first. This check sends an entire split to the Python reader whenever it contains a .video file. I reproduced a regression by reusing a full-column split from a Data Evolution table and projecting only try_variant_get on its Parquet VARIANT column. The base commit returned 1.5 with Rust 0.6.0. This PR raises Variant extraction requires a compatible native reader even though the query only needs the Parquet file. Please land apache/paimon-rust#1347 first and make the compatible Rust runtime available to PyPaimon. Then remove this split-wide fallback and keep .video on the native read path.
Purpose
Keep complete video payloads and row-to-frame mappings, while deriving frame locations from MP4 sample tables instead of persisting a separate keyframe index. Retain moov offset/length to avoid repeated container discovery on cold reads.
The six arrays use Delta-Varint encoding; the footer is 29 bytes, version 1. Frame descriptors also carry moov offset/length. Python locates moov while copying video bytes; Java preserves supplied ranges during rewrites.
PyAV and explicit TorchCodec derive and share frame mappings for ordinary single-video-track MP4, including VFR and B-frames. Stored moov hints are validated before use. Unsupported timelines use scan/exact fallback.
Compatibility: this replaces the previous v1 layout; existing
.videofiles require reimport. The matching Rust reader is apache/paimon-rust#1347.Native reads:
.videoremains on the native path with Rust #1347 (merged). Native CI builds Rust main; installations need a build containing that change.Tests
Python video, MP4, LeRobot and rolling regressions: 207 passed, 44 skipped.
Java video format regressions: 9 passed.
Regressions cover invalid sync samples, transient I/O, out-of-range frames, failed footer writes, bounded metadata caching and bootstrap reads.
Shared fixtures cover moov ranges, frames, NULLs and placeholders.
Review regressions: 146 passed, 42 skipped; dual-track MP4 keeps the first video track through exact fallback, including
.videoround trips. Native tests reject Python fallback and cover VARIANT-only projection from a video-containing split.