tensorcodec 0.1.3__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/PKG-INFO +18 -6
  2. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/README.md +17 -5
  3. tensorcodec-0.1.4/benchmarks/README.md +99 -0
  4. tensorcodec-0.1.4/benchmarks/__init__.py +1 -0
  5. tensorcodec-0.1.4/benchmarks/__main__.py +5 -0
  6. tensorcodec-0.1.4/benchmarks/container_bench.py +157 -0
  7. tensorcodec-0.1.4/benchmarks/counting_fs.py +128 -0
  8. tensorcodec-0.1.4/benchmarks/decoders/__init__.py +85 -0
  9. tensorcodec-0.1.4/benchmarks/decoders/decord_decoder.py +50 -0
  10. tensorcodec-0.1.4/benchmarks/decoders/opencv_decoder.py +77 -0
  11. tensorcodec-0.1.4/benchmarks/decoders/tensorcodec_decoder.py +33 -0
  12. tensorcodec-0.1.4/benchmarks/decoders/torchcodec_decoder.py +129 -0
  13. tensorcodec-0.1.4/benchmarks/decoders/torchvision_decoder.py +116 -0
  14. tensorcodec-0.1.4/benchmarks/open_cost.py +114 -0
  15. tensorcodec-0.1.4/benchmarks/plot_results.py +193 -0
  16. tensorcodec-0.1.4/benchmarks/protocol.py +87 -0
  17. tensorcodec-0.1.4/benchmarks/runner.py +532 -0
  18. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/docs/compatibility.md +21 -0
  19. tensorcodec-0.1.4/docs/container_robustness.md +45 -0
  20. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/docs/releasing.md +3 -3
  21. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/docs/system_ffmpeg.md +1 -1
  22. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/native/Cargo.lock +1 -1
  23. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/native/Cargo.toml +1 -1
  24. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/native/src/ffmpeg.rs +327 -161
  25. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/native/src/lib.rs +59 -35
  26. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/packaging/size-baseline.json +12 -12
  27. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/pyproject.toml +5 -7
  28. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/__init__.py +1 -1
  29. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/decoders/_decoder.py +60 -17
  30. tensorcodec-0.1.4/tests/test_timestamp.py +224 -0
  31. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/LICENSE +0 -0
  32. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/docs/package_size.md +0 -0
  33. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/docs/playback_semantics.md +0 -0
  34. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/FFmpeg-GPL-3.0.txt +0 -0
  35. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/FFmpeg-LGPL-3.0.txt +0 -0
  36. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/FFmpeg-NOTICE.md +0 -0
  37. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/OpenSSL.txt +0 -0
  38. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/README.md +0 -0
  39. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/licenses/Zstandard.txt +0 -0
  40. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/packaging/size-policy.json +0 -0
  41. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/build_ffmpeg.sh +0 -0
  42. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/build_linux_wheel.sh +0 -0
  43. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/build_macos_wheel.sh +0 -0
  44. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/build_nasm.sh +0 -0
  45. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/build_openssl.sh +0 -0
  46. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/check_wheel_runtime.py +0 -0
  47. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/check_wheel_size.py +0 -0
  48. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/configure_oracle_ffmpeg.py +0 -0
  49. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/scripts/update_size_comparison.py +0 -0
  50. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/_frame.py +0 -0
  51. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/_metadata.py +0 -0
  52. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/decoders/__init__.py +0 -0
  53. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/src/tensorcodec/py.typed +0 -0
  54. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/__init__.py +0 -0
  55. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/conftest.py +0 -0
  56. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_audio_contract.py +0 -0
  57. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_differential.py +0 -0
  58. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_native_output.py +0 -0
  59. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_open_cost.py +0 -0
  60. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_runtime.py +0 -0
  61. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_size_comparison.py +0 -0
  62. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_video_contract.py +0 -0
  63. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_video_fidelity.py +0 -0
  64. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/test_wheel_size.py +0 -0
  65. {tensorcodec-0.1.3 → tensorcodec-0.1.4}/tests/utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tensorcodec
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Operating System :: POSIX :: Linux
6
6
  Classifier: Operating System :: MacOS :: MacOS X
@@ -34,7 +34,7 @@ CPU video/audio decoding with TorchCodec-style APIs and NumPy output.
34
34
  <a href="https://pypi.org/project/tensorcodec/"><img src="https://img.shields.io/pypi/v/tensorcodec" alt="PyPI"></a>
35
35
  <a href="https://pypi.org/project/tensorcodec/"><img src="https://img.shields.io/badge/Python-3.10%2B-blue" alt="Python"></a>
36
36
  <!-- wheel-size-badge:start -->
37
- <a href="#package-size"><img src="https://img.shields.io/badge/wheel-10.4%20MiB-blue" alt="Wheel download"></a>
37
+ <a href="#package-size"><img src="https://img.shields.io/badge/wheel-10.5%20MiB-blue" alt="Wheel download"></a>
38
38
  <!-- wheel-size-badge:end -->
39
39
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue" alt="License: MIT"></a>
40
40
  </p>
@@ -48,8 +48,9 @@ CPU video/audio decoding with TorchCodec-style APIs and NumPy output.
48
48
  - **Validated playback semantics.** Frame selection, ordering, timestamps and audio
49
49
  ranges are checked against TorchCodec 0.17.0 and independently generated media.
50
50
  - **Efficient batch decoding.** Rust/PyO3 bindings to FFmpeg process frame batches
51
- in a single native call, avoiding per-frame Python calls.
52
- - **Lightweight installation.** Linux wheels are 10.2–10.4 MiB (v0.1.2), including
51
+ in a single native call, avoiding per-frame Python calls. Closing a decoder
52
+ releases its FFmpeg resources without waiting for Python's cyclic GC.
53
+ - **Lightweight installation.** Linux wheels are 10.3–10.5 MiB (v0.1.3), including
53
54
  FFmpeg shared libraries. NumPy is the only Python dependency.
54
55
 
55
56
  ## Quick start
@@ -77,9 +78,20 @@ with AudioDecoder("audio.wav", sample_rate=16000, num_channels=1) as audio:
77
78
  Arrays keep their storage after the decoder closes. Paths, URLs, encoded bytes,
78
79
  1-D uint8 arrays and seekable file objects are supported.
79
80
 
81
+ For time-based windows without an initial full packet scan (since v0.1.4):
82
+
83
+ ```python
84
+ with VideoDecoder("video.mkv", seek_mode="timestamp") as decoder:
85
+ frames = decoder.get_frames_played_at([10.0, 10.1, 10.2])
86
+ ```
87
+
88
+ This TensorCodec extension selects by actual PTS and retries seeks that overshoot.
89
+ It supports time queries, including ranges with explicit `fps`, but not frame
90
+ indices, `len(decoder)`, or `get_all_frames()`. See [the contract](docs/compatibility.md#timestamp-mode).
91
+
80
92
  ## Features
81
93
 
82
- TensorCodec 0.1.3 relative to TorchCodec 0.17.0.
94
+ TensorCodec 0.1.4 relative to TorchCodec 0.17.0.
83
95
  ✓ supported · △ partial support · — not implemented.
84
96
 
85
97
  | Component | TensorCodec | TorchCodec 0.17.0 |
@@ -132,7 +144,7 @@ Linux CPU wheels, Python 3.12. Download / unpacked size in MiB.
132
144
 
133
145
  | Package | x86_64 | ARM64 |
134
146
  | --- | ---: | ---: |
135
- | TensorCodec | 10.2 / 24.7 | 10.4 / 22.9 |
147
+ | TensorCodec | 10.3 / 24.8 | 10.5 / 23.0 |
136
148
  | PyAV | 33.4 / 125.5 | 31.2 / 90.4 |
137
149
  | TorchCodec + PyTorch (CPU) | 196.7 / 704.7 | 160.3 / 585.7 |
138
150
  <!-- wheel-size:end -->
@@ -9,7 +9,7 @@ CPU video/audio decoding with TorchCodec-style APIs and NumPy output.
9
9
  <a href="https://pypi.org/project/tensorcodec/"><img src="https://img.shields.io/pypi/v/tensorcodec" alt="PyPI"></a>
10
10
  <a href="https://pypi.org/project/tensorcodec/"><img src="https://img.shields.io/badge/Python-3.10%2B-blue" alt="Python"></a>
11
11
  <!-- wheel-size-badge:start -->
12
- <a href="#package-size"><img src="https://img.shields.io/badge/wheel-10.4%20MiB-blue" alt="Wheel download"></a>
12
+ <a href="#package-size"><img src="https://img.shields.io/badge/wheel-10.5%20MiB-blue" alt="Wheel download"></a>
13
13
  <!-- wheel-size-badge:end -->
14
14
  <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue" alt="License: MIT"></a>
15
15
  </p>
@@ -23,8 +23,9 @@ CPU video/audio decoding with TorchCodec-style APIs and NumPy output.
23
23
  - **Validated playback semantics.** Frame selection, ordering, timestamps and audio
24
24
  ranges are checked against TorchCodec 0.17.0 and independently generated media.
25
25
  - **Efficient batch decoding.** Rust/PyO3 bindings to FFmpeg process frame batches
26
- in a single native call, avoiding per-frame Python calls.
27
- - **Lightweight installation.** Linux wheels are 10.2–10.4 MiB (v0.1.2), including
26
+ in a single native call, avoiding per-frame Python calls. Closing a decoder
27
+ releases its FFmpeg resources without waiting for Python's cyclic GC.
28
+ - **Lightweight installation.** Linux wheels are 10.3–10.5 MiB (v0.1.3), including
28
29
  FFmpeg shared libraries. NumPy is the only Python dependency.
29
30
 
30
31
  ## Quick start
@@ -52,9 +53,20 @@ with AudioDecoder("audio.wav", sample_rate=16000, num_channels=1) as audio:
52
53
  Arrays keep their storage after the decoder closes. Paths, URLs, encoded bytes,
53
54
  1-D uint8 arrays and seekable file objects are supported.
54
55
 
56
+ For time-based windows without an initial full packet scan (since v0.1.4):
57
+
58
+ ```python
59
+ with VideoDecoder("video.mkv", seek_mode="timestamp") as decoder:
60
+ frames = decoder.get_frames_played_at([10.0, 10.1, 10.2])
61
+ ```
62
+
63
+ This TensorCodec extension selects by actual PTS and retries seeks that overshoot.
64
+ It supports time queries, including ranges with explicit `fps`, but not frame
65
+ indices, `len(decoder)`, or `get_all_frames()`. See [the contract](docs/compatibility.md#timestamp-mode).
66
+
55
67
  ## Features
56
68
 
57
- TensorCodec 0.1.3 relative to TorchCodec 0.17.0.
69
+ TensorCodec 0.1.4 relative to TorchCodec 0.17.0.
58
70
  ✓ supported · △ partial support · — not implemented.
59
71
 
60
72
  | Component | TensorCodec | TorchCodec 0.17.0 |
@@ -107,7 +119,7 @@ Linux CPU wheels, Python 3.12. Download / unpacked size in MiB.
107
119
 
108
120
  | Package | x86_64 | ARM64 |
109
121
  | --- | ---: | ---: |
110
- | TensorCodec | 10.2 / 24.7 | 10.4 / 22.9 |
122
+ | TensorCodec | 10.3 / 24.8 | 10.5 / 23.0 |
111
123
  | PyAV | 33.4 / 125.5 | 31.2 / 90.4 |
112
124
  | TorchCodec + PyTorch (CPU) | 196.7 / 704.7 | 160.3 / 585.7 |
113
125
  <!-- wheel-size:end -->
@@ -0,0 +1,99 @@
1
+ # TensorCodec benchmarks
2
+
3
+ These tools measure the current TensorCodec implementation and optional comparison
4
+ backends. Performance depends on the input, seek mode, thread count, storage and
5
+ cache state. Measure your workload before choosing a decoder.
6
+
7
+ ## Setup
8
+
9
+ Use the [development environment](../README.md#development-and-verification).
10
+ TensorCodec-only runs need NumPy and TensorCodec; TorchCodec comparisons also need
11
+ the pinned oracle group. FFmpeg CLI with the requested encoders is required to
12
+ generate fixtures. Run from the repository root.
13
+
14
+ ```sh
15
+ uv run --no-sync python -m benchmarks --list-decoders
16
+ uv run --no-sync python -m benchmarks --prepare --num-videos 4 --video-duration 10
17
+ uv run --no-sync python -m benchmarks --no-io --decoders tensorcodec \
18
+ --runs 3 --output json --save benchmarks/results/speed.json
19
+ ```
20
+
21
+ For a CPU comparison, explicitly select the same thread count and seek mode:
22
+
23
+ ```sh
24
+ uv run --no-sync python -m benchmarks --no-io \
25
+ --decoders tensorcodec 'torchcodec(seek=exact,thr=1)' \
26
+ --runs 3 --output json --save benchmarks/results/speed.json
27
+ ```
28
+
29
+ ## Measurements
30
+
31
+ | Scenario | Workload | Included costs |
32
+ | --- | --- | --- |
33
+ | `temporal_window` | Random playback queries, 11 samples over a 1-second window | Decoder open, exact-mode packet scan, seeking, decoding, NumPy output |
34
+ | `sequential_range` | Decode the full video range | Decoder open, range selection, decoding, NumPy output |
35
+
36
+ The TensorCodec adapter opens and closes a decoder for each request. Results do
37
+ not represent a persistent decoder cache such as MediaRef's. Compare exact and
38
+ approximate modes separately: approximate mode does not guarantee exact VFR frame
39
+ selection. GPU comparison adapters include transfer back to CPU NumPy arrays.
40
+
41
+ For codec/container throughput experiments:
42
+
43
+ ```sh
44
+ uv run --no-sync python -m benchmarks.container_bench --help
45
+ uv run --no-sync python -m benchmarks.container_bench
46
+ ```
47
+
48
+ This tool generates fresh inputs with FFmpeg. Its codec matrix measures speed;
49
+ it does not assert pixel or timestamp correctness. See
50
+ [container and seek behavior](../docs/container_robustness.md) for tested guarantees.
51
+
52
+ ## Optional I/O and plotting
53
+
54
+ To separate opening from an 11-frame playback window, counting bytes returned by
55
+ file reads (including rereads, **not** physical disk or network traffic):
56
+
57
+ ```sh
58
+ ffprobe -v error -select_streams v:0 -show_frames \
59
+ -show_entries frame=pts,duration,key_frame -of json video.mp4 > frames.json
60
+ uv run --no-sync python -m benchmarks.open_cost video.mp4 --start 10 \
61
+ --backends tensorcodec torchcodec --mappings frames.json
62
+ ```
63
+
64
+ Both libraries scan packets to EOF on each fresh default `exact` open. Precomputed
65
+ `custom_frame_mappings` skip that scan while preserving exact selection; header
66
+ probing and window reads remain. Generate mappings once for the **same encoded
67
+ stream**, outside training. PTS alone is insufficient: durations and keyframe flags
68
+ are also required, in the stream's integer time base. The tool checks mapped
69
+ window pixels/PTS/durations against exact, and rotates mode order between trials;
70
+ it does not control OS caches. `approximate` is measured separately without an
71
+ accuracy guarantee. Container seek indexes are not generally complete frame maps
72
+ (e.g. MKV Cues); they cannot universally replace an exact scan.
73
+
74
+ FUSE measurements require Linux FUSE access, `pyfuse3` and `trio`. Install these
75
+ only in the benchmark environment, then omit `--no-io`. The runner can fall back
76
+ to speed-only results when FUSE is unavailable; check that `io_bytes` is populated
77
+ before reporting I/O figures. FUSE timing includes its own filesystem overhead.
78
+
79
+ ```sh
80
+ uv run --no-sync python -m benchmarks --decoders tensorcodec \
81
+ 'torchcodec(seek=exact,thr=1)' --scenarios temporal_window \
82
+ --runs 3 --output json --save benchmarks/results/io.json
83
+ ```
84
+
85
+ Install `matplotlib` in the benchmark environment to plot measurements:
86
+
87
+ ```sh
88
+ uv run --no-sync python -m benchmarks.plot_results \
89
+ --speed benchmarks/results/speed.json --io benchmarks/results/io.json
90
+ ```
91
+
92
+ ## Reporting results
93
+
94
+ Generated JSON and charts stay in `benchmarks/results/`, which is gitignored.
95
+ Publish results only with the TensorCodec/TorchCodec/FFmpeg/NumPy versions,
96
+ hardware, corpus, seek/thread settings, cache conditions and commands. Identify
97
+ timeouts as partial results. Check frame selection and pixel agreement separately
98
+ using the [compatibility contract](../docs/compatibility.md); throughput alone is
99
+ not a correctness check.
@@ -0,0 +1 @@
1
+ """tensorcodec benchmark suite — FPS and disk I/O measurement for video decoders."""
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m benchmarks`` to launch the runner."""
2
+
3
+ from benchmarks.runner import main
4
+
5
+ main()
@@ -0,0 +1,157 @@
1
+ """Container & codec robustness benchmark.
2
+
3
+ Generates synthetic videos in various codec × container combinations and
4
+ measures random-seek performance for tensorcodec and (optionally) TorchCodec.
5
+
6
+ Usage::
7
+
8
+ uv run --no-sync python -m benchmarks.container_bench
9
+ uv run --no-sync python -m benchmarks.container_bench --duration 60 --queries 200
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import os
16
+ import random
17
+ import subprocess
18
+ import tempfile
19
+ import time
20
+
21
+ import numpy as np
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Video generation
25
+ # ---------------------------------------------------------------------------
26
+
27
+ COMBOS: list[tuple[str, str, str, str, dict]] = [
28
+ # (codec_label, extension, av_codec, pix_fmt, encoder_opts)
29
+ ("h264", "mp4", "libx264", "yuv420p", {"g": "10"}),
30
+ ("h264", "mkv", "libx264", "yuv420p", {"g": "10"}),
31
+ ("h264", "avi", "libx264", "yuv420p", {"g": "10"}),
32
+ ("h264", "ts", "libx264", "yuv420p", {"g": "10"}),
33
+ ("h265", "mp4", "libx265", "yuv420p", {"g": "10", "x265-params": "log-level=error"}),
34
+ ("h265", "mkv", "libx265", "yuv420p", {"g": "10", "x265-params": "log-level=error"}),
35
+ ("h265", "ts", "libx265", "yuv420p", {"g": "10", "x265-params": "log-level=error"}),
36
+ ("vp9", "mkv", "libvpx-vp9", "yuv420p", {"g": "10", "quality": "realtime", "speed": "8"}),
37
+ ("vp9", "webm", "libvpx-vp9", "yuv420p", {"g": "10", "quality": "realtime", "speed": "8"}),
38
+ ("mpeg4", "mp4", "mpeg4", "yuv420p", {"g": "10"}),
39
+ ("mpeg4", "mkv", "mpeg4", "yuv420p", {"g": "10"}),
40
+ ("mpeg4", "avi", "mpeg4", "yuv420p", {"g": "10"}),
41
+ ("mjpeg", "mkv", "mjpeg", "yuvj420p", {}),
42
+ ("mjpeg", "avi", "mjpeg", "yuvj420p", {}),
43
+ ]
44
+
45
+
46
+ def _create_video(
47
+ path: str,
48
+ codec: str,
49
+ pix_fmt: str = "yuv420p",
50
+ duration_sec: int = 30,
51
+ fps: int = 30,
52
+ opts: dict | None = None,
53
+ ) -> None:
54
+ cmd = [
55
+ "ffmpeg",
56
+ "-hide_banner",
57
+ "-loglevel",
58
+ "error",
59
+ "-y",
60
+ "-f",
61
+ "lavfi",
62
+ "-i",
63
+ f"testsrc2=size=640x480:rate={fps}:duration={duration_sec}",
64
+ "-c:v",
65
+ codec,
66
+ "-pix_fmt",
67
+ pix_fmt,
68
+ ]
69
+ for key, value in (opts or {}).items():
70
+ cmd.extend([f"-{key}", str(value)])
71
+ subprocess.run([*cmd, path], capture_output=True, check=True)
72
+
73
+
74
+ # ---------------------------------------------------------------------------
75
+ # Benchmark helpers
76
+ # ---------------------------------------------------------------------------
77
+
78
+
79
+ def _bench_tensorcodec(path: str, windows: list[list[float]]) -> str:
80
+ from tensorcodec.decoders import VideoDecoder
81
+
82
+ try:
83
+ with VideoDecoder(path) as d:
84
+ d.get_frames_played_at([1.0])
85
+ except (RuntimeError, ValueError, OSError):
86
+ return "FAIL"
87
+ t0 = time.perf_counter()
88
+ total = 0
89
+ for w in windows:
90
+ with VideoDecoder(path) as d:
91
+ total += d.get_frames_played_at(w).data.shape[0]
92
+ return f"{total / (time.perf_counter() - t0):.0f}"
93
+
94
+
95
+ def _bench_torchcodec(path: str, windows: list[list[float]], seek_mode: str) -> str:
96
+ try:
97
+ from torchcodec.decoders import VideoDecoder
98
+ except ImportError:
99
+ return "N/A"
100
+ try:
101
+ VideoDecoder(path, seek_mode=seek_mode, num_ffmpeg_threads=1).get_frames_played_at([1.0])
102
+ except (RuntimeError, ValueError, OSError):
103
+ return "FAIL"
104
+ t0 = time.perf_counter()
105
+ total = 0
106
+ for w in windows:
107
+ dec = VideoDecoder(path, seek_mode=seek_mode, num_ffmpeg_threads=1)
108
+ total += dec.get_frames_played_at(w).data.shape[0]
109
+ return f"{total / (time.perf_counter() - t0):.0f}"
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # Main
114
+ # ---------------------------------------------------------------------------
115
+
116
+
117
+ def main() -> None:
118
+ parser = argparse.ArgumentParser(description="Container robustness benchmark")
119
+ parser.add_argument("--duration", type=int, default=30, help="Video duration in seconds")
120
+ parser.add_argument("--queries", type=int, default=100, help="Number of random-seek queries")
121
+ parser.add_argument("--seed", type=int, default=42)
122
+ args = parser.parse_args()
123
+
124
+ random.seed(args.seed)
125
+ lo = max(2.0, args.duration * 0.1)
126
+ hi = args.duration - 1.0
127
+ ts = [random.uniform(lo, hi) for _ in range(args.queries)]
128
+ windows = [[t + o for o in np.arange(-1.0, 0.05, 0.1).tolist()] for t in ts]
129
+
130
+ with tempfile.TemporaryDirectory(prefix="container_bench_") as tmp:
131
+ hdr = (
132
+ f"{'codec.container':20s} {'tensorcodec':>10s} {'TC(apx)':>10s} {'TC(ext)':>10s} {'apx/tensorcodec':>10s}"
133
+ )
134
+ print(hdr)
135
+ print("-" * len(hdr))
136
+
137
+ for codec_label, ext, av_codec, pix, opts in COMBOS:
138
+ path = os.path.join(tmp, f"{codec_label}.{ext}")
139
+ try:
140
+ _create_video(path, av_codec, pix, args.duration, opts=opts)
141
+ except (OSError, subprocess.CalledProcessError) as e:
142
+ print(f"{codec_label}.{ext:20s} CREATE FAILED: {e}")
143
+ continue
144
+
145
+ r1 = _bench_tensorcodec(path, windows)
146
+ r2 = _bench_torchcodec(path, windows, "approximate")
147
+ r3 = _bench_torchcodec(path, windows, "exact")
148
+ try:
149
+ ratio = f"{float(r2) / float(r1):.2f}x"
150
+ except (ValueError, ZeroDivisionError):
151
+ ratio = "N/A"
152
+ label = f"{codec_label}.{ext}"
153
+ print(f"{label:20s} {r1:>10s} {r2:>10s} {r3:>10s} {ratio:>10s}")
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()
@@ -0,0 +1,128 @@
1
+ """FUSE passthrough filesystem that counts read I/O.
2
+
3
+ Requires ``pyfuse3`` and ``trio``. The benchmark runner gracefully
4
+ falls back to speed-only measurement when these are unavailable.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import errno
10
+ import os
11
+ import threading
12
+
13
+ import pyfuse3
14
+
15
+
16
+ class CountingFS(pyfuse3.Operations):
17
+ """Passthrough FS that transparently counts bytes read and read calls."""
18
+
19
+ def __init__(self, root: str):
20
+ super().__init__()
21
+ self.root = root
22
+ self.read_bytes = 0
23
+ self.read_calls = 0
24
+ self._lock = threading.Lock()
25
+ self._fd_map: dict[int, int] = {}
26
+ self._inode_path: dict[int, str] = {pyfuse3.ROOT_INODE: root}
27
+ self._path_inode: dict[str, int] = {root: pyfuse3.ROOT_INODE}
28
+ self._next_inode = pyfuse3.ROOT_INODE + 1
29
+
30
+ # ---- helpers -----------------------------------------------------------
31
+ def _get_path(self, inode: int) -> str | None:
32
+ return self._inode_path.get(inode)
33
+
34
+ def _get_or_create_inode(self, path: str) -> int:
35
+ if path in self._path_inode:
36
+ return self._path_inode[path]
37
+ inode = self._next_inode
38
+ self._next_inode += 1
39
+ self._inode_path[inode] = path
40
+ self._path_inode[path] = inode
41
+ return inode
42
+
43
+ def reset_stats(self) -> None:
44
+ with self._lock:
45
+ self.read_bytes = 0
46
+ self.read_calls = 0
47
+
48
+ def get_stats(self) -> dict[str, int]:
49
+ with self._lock:
50
+ return {"bytes": self.read_bytes, "calls": self.read_calls}
51
+
52
+ # ---- FUSE ops ----------------------------------------------------------
53
+ async def getattr(self, inode, ctx=None):
54
+ path = self._get_path(inode)
55
+ if path is None:
56
+ raise pyfuse3.FUSEError(errno.ENOENT)
57
+ try:
58
+ st = os.lstat(path)
59
+ except OSError as exc:
60
+ raise pyfuse3.FUSEError(exc.errno)
61
+ entry = pyfuse3.EntryAttributes()
62
+ entry.st_ino = inode
63
+ entry.st_mode = st.st_mode
64
+ entry.st_nlink = st.st_nlink
65
+ entry.st_uid = st.st_uid
66
+ entry.st_gid = st.st_gid
67
+ entry.st_size = st.st_size
68
+ entry.st_atime_ns = int(st.st_atime * 1e9)
69
+ entry.st_mtime_ns = int(st.st_mtime * 1e9)
70
+ entry.st_ctime_ns = int(st.st_ctime * 1e9)
71
+ entry.st_blksize = 512
72
+ entry.st_blocks = (st.st_size + 511) // 512
73
+ return entry
74
+
75
+ async def lookup(self, parent_inode, name, ctx=None):
76
+ parent_path = self._get_path(parent_inode)
77
+ if parent_path is None:
78
+ raise pyfuse3.FUSEError(errno.ENOENT)
79
+ name = name.decode("utf-8") if isinstance(name, bytes) else name
80
+ path = os.path.join(parent_path, name)
81
+ if not os.path.exists(path):
82
+ raise pyfuse3.FUSEError(errno.ENOENT)
83
+ inode = self._get_or_create_inode(path)
84
+ return await self.getattr(inode)
85
+
86
+ async def opendir(self, inode, ctx):
87
+ path = self._get_path(inode)
88
+ if path is None or not os.path.isdir(path):
89
+ raise pyfuse3.FUSEError(errno.ENOENT)
90
+ return inode
91
+
92
+ async def readdir(self, inode, start_id, token):
93
+ path = self._get_path(inode)
94
+ if path is None:
95
+ raise pyfuse3.FUSEError(errno.ENOENT)
96
+ entries = list(os.listdir(path))
97
+ for i, name in enumerate(entries[start_id:], start=start_id):
98
+ child_path = os.path.join(path, name)
99
+ child_inode = self._get_or_create_inode(child_path)
100
+ attr = await self.getattr(child_inode)
101
+ if not pyfuse3.readdir_reply(token, name.encode(), attr, i + 1):
102
+ break
103
+
104
+ async def open(self, inode, flags, ctx):
105
+ path = self._get_path(inode)
106
+ if path is None:
107
+ raise pyfuse3.FUSEError(errno.ENOENT)
108
+ fd = os.open(path, flags)
109
+ # Key by fd (not inode) so concurrent opens of the same file
110
+ # each get their own entry and don't overwrite each other.
111
+ self._fd_map[fd] = fd
112
+ return pyfuse3.FileInfo(fh=fd, direct_io=True)
113
+
114
+ async def read(self, fh, offset, size):
115
+ fd = self._fd_map.get(fh)
116
+ if fd is None:
117
+ raise pyfuse3.FUSEError(errno.EBADF)
118
+ os.lseek(fd, offset, os.SEEK_SET)
119
+ data = os.read(fd, size)
120
+ with self._lock:
121
+ self.read_bytes += len(data)
122
+ self.read_calls += 1
123
+ return data
124
+
125
+ async def release(self, fh):
126
+ fd = self._fd_map.pop(fh, None)
127
+ if fd is not None:
128
+ os.close(fd)
@@ -0,0 +1,85 @@
1
+ """Decoder implementations for benchmarks.
2
+
3
+ The registry maps decoder names to either *classes* (instantiated with no
4
+ args) or *pre-built instances* (used as-is). This allows parameterised
5
+ decoders like TorchCodec to expose multiple configurations.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Union
11
+
12
+ from benchmarks.decoders.tensorcodec_decoder import TensorCodecDecoder
13
+ from benchmarks.protocol import VideoDecoderProtocol
14
+
15
+ # Values are either a class (called with no args) or a ready instance.
16
+ _Entry = Union[type[VideoDecoderProtocol], VideoDecoderProtocol]
17
+
18
+ DECODERS: dict[str, _Entry] = {
19
+ "tensorcodec": TensorCodecDecoder,
20
+ }
21
+
22
+ # Optional decoders — register only when the library is importable.
23
+ try:
24
+ from benchmarks.decoders.torchcodec_decoder import TORCHCODEC_CONFIGS
25
+
26
+ for _cfg in TORCHCODEC_CONFIGS:
27
+ DECODERS[_cfg.name] = _cfg
28
+ except ImportError:
29
+ pass
30
+
31
+ try:
32
+ import torch as _torch
33
+
34
+ if _torch.cuda.is_available():
35
+ from benchmarks.decoders.torchcodec_decoder import TORCHCODEC_GPU_CONFIGS
36
+
37
+ for _cfg in TORCHCODEC_GPU_CONFIGS:
38
+ DECODERS[_cfg.name] = _cfg
39
+ except ImportError:
40
+ pass
41
+
42
+ try:
43
+ from benchmarks.decoders.decord_decoder import DecordDecoder
44
+
45
+ DECODERS["decord"] = DecordDecoder
46
+ except ImportError:
47
+ pass
48
+
49
+ try:
50
+ from benchmarks.decoders.opencv_decoder import OpenCVDecoder
51
+
52
+ DECODERS["opencv"] = OpenCVDecoder
53
+ except ImportError:
54
+ pass
55
+
56
+ try:
57
+ from benchmarks.decoders.torchvision_decoder import (
58
+ TorchVisionPyAVDecoder,
59
+ TorchVisionVideoReaderDecoder,
60
+ available_backends,
61
+ )
62
+
63
+ _tv_backends = available_backends()
64
+ if "pyav" in _tv_backends:
65
+ DECODERS["torchvision-pyav"] = TorchVisionPyAVDecoder
66
+ if "video_reader" in _tv_backends:
67
+ DECODERS["torchvision-video_reader"] = TorchVisionVideoReaderDecoder
68
+ except ImportError:
69
+ pass
70
+
71
+
72
+ def get_decoder(name: str) -> VideoDecoderProtocol:
73
+ """Return a decoder by name (instantiating if needed)."""
74
+ if name not in DECODERS:
75
+ available = ", ".join(DECODERS.keys())
76
+ raise ValueError(f"Unknown decoder: {name}. Available: {available}")
77
+ entry = DECODERS[name]
78
+ if isinstance(entry, type):
79
+ return entry()
80
+ return entry # already an instance
81
+
82
+
83
+ def list_available_decoders() -> list[str]:
84
+ """Return names of all importable decoders."""
85
+ return list(DECODERS.keys())
@@ -0,0 +1,50 @@
1
+ """Benchmark adapter for Decord.
2
+
3
+ Requires ``decord`` to be installed. The benchmark registry in
4
+ ``__init__.py`` catches the ``ImportError`` if it is missing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import List, Optional
10
+
11
+ import numpy as np
12
+ from decord import VideoReader, cpu
13
+
14
+
15
+ class DecordDecoder:
16
+ """Wraps :class:`decord.VideoReader` for the benchmark protocol."""
17
+
18
+ name = "decord"
19
+
20
+ def get_frames_played_at(self, video_path: str, seconds: List[float]) -> np.ndarray:
21
+ vr = VideoReader(video_path, ctx=cpu(0))
22
+ fps = vr.get_avg_fps()
23
+ # Convert timestamps to frame indices using playback-frame semantics:
24
+ # frame[i].pts <= timestamp < frame[i+1].pts
25
+ indices = [min(int(t * fps), len(vr) - 1) for t in seconds]
26
+ frames = vr.get_batch(indices).asnumpy() # (N, H, W, C)
27
+ return np.transpose(frames, (0, 3, 1, 2)) # -> NCHW
28
+
29
+ def get_frames_played_in_range(
30
+ self,
31
+ video_path: str,
32
+ start_seconds: float,
33
+ stop_seconds: float,
34
+ fps: Optional[float] = None,
35
+ ) -> np.ndarray:
36
+ if fps is not None:
37
+ raise ValueError("DecordDecoder does not support the fps parameter")
38
+ vr = VideoReader(video_path, ctx=cpu(0))
39
+ avg_fps = vr.get_avg_fps()
40
+ start_idx = int(start_seconds * avg_fps)
41
+ stop_idx = min(int(stop_seconds * avg_fps), len(vr))
42
+ indices = list(range(start_idx, stop_idx))
43
+ if not indices:
44
+ return np.empty((0, 3, 0, 0), dtype=np.uint8)
45
+ frames = vr.get_batch(indices).asnumpy() # (N, H, W, C)
46
+ return np.transpose(frames, (0, 3, 1, 2)) # -> NCHW
47
+
48
+ def get_video_duration(self, video_path: str) -> float:
49
+ vr = VideoReader(video_path, ctx=cpu(0))
50
+ return len(vr) / vr.get_avg_fps()